@quirekit/xlsx 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +21 -0
- package/THIRD_PARTY_NOTICES.md +150 -0
- package/dist/index.d.mts +122 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +19167 -0
- package/dist/index.mjs.map +1 -0
- package/licenses/saxes.LICENSE +64 -0
- package/licenses/xmlchars.LICENSE +18 -0
- package/package.json +52 -3
- package/src/bundle.ts +17 -0
- package/src/comments/legacy/read.ts +68 -0
- package/src/comments/legacy/write.ts +64 -0
- package/src/comments/package/ranges.ts +78 -0
- package/src/comments/package/read.ts +95 -0
- package/src/comments/package/roundtrip.test.ts +106 -0
- package/src/comments/package/write.ts +130 -0
- package/src/comments/thread/read.ts +69 -0
- package/src/comments/thread/write.ts +61 -0
- package/src/comments/types.ts +43 -0
- package/src/comments/xml.ts +50 -0
- package/src/create.ts +13 -0
- package/src/drawing/cache.ts +48 -0
- package/src/drawing/chart.test.ts +96 -0
- package/src/drawing/chart.ts +87 -0
- package/src/drawing/definition/plots.ts +76 -0
- package/src/drawing/definition/read.ts +65 -0
- package/src/drawing/definition/shape.ts +40 -0
- package/src/drawing/definition/types.ts +24 -0
- package/src/drawing/editable-picture.ts +80 -0
- package/src/drawing/graph.ts +148 -0
- package/src/drawing/identity.ts +22 -0
- package/src/drawing/import.ts +133 -0
- package/src/drawing/namespaces.ts +11 -0
- package/src/drawing/picture.test.ts +98 -0
- package/src/drawing/picture.ts +54 -0
- package/src/drawing/placement/anchor.ts +71 -0
- package/src/drawing/placement/axes.ts +113 -0
- package/src/drawing/placement/marker.ts +16 -0
- package/src/drawing/placement/transform.ts +132 -0
- package/src/drawing/placement/types.ts +20 -0
- package/src/drawing/presentation/cartesian/axes.ts +103 -0
- package/src/drawing/presentation/cartesian/plot.ts +109 -0
- package/src/drawing/presentation/cartesian/types.ts +9 -0
- package/src/drawing/presentation/layout.ts +29 -0
- package/src/drawing/presentation/paint.ts +56 -0
- package/src/drawing/presentation/properties.ts +31 -0
- package/src/drawing/read.ts +85 -0
- package/src/drawing/shapes/connector.ts +55 -0
- package/src/drawing/shapes/paint.ts +108 -0
- package/src/drawing/shapes/read.ts +89 -0
- package/src/drawing/shapes/text.ts +89 -0
- package/src/drawing/shapes/types.ts +13 -0
- package/src/drawing/sources.test.ts +27 -0
- package/src/drawing/sources.ts +43 -0
- package/src/drawing/types.ts +54 -0
- package/src/drawing/worksheet-connector.test.ts +135 -0
- package/src/drawing/worksheet-shape.test.ts +61 -0
- package/src/drawing/write/anchor.ts +17 -0
- package/src/drawing/write/axes.ts +23 -0
- package/src/drawing/write/chart.ts +56 -0
- package/src/drawing/write/drawing.ts +61 -0
- package/src/drawing/write/pictures.ts +68 -0
- package/src/drawing/write/series.ts +43 -0
- package/src/drawing/write/shapes.ts +113 -0
- package/src/drawing/write/text.ts +26 -0
- package/src/drawing/write/workbook.test.ts +199 -0
- package/src/drawing/write/workbook.ts +217 -0
- package/src/external-links/formulas.ts +21 -0
- package/src/external-links/read.test.ts +93 -0
- package/src/external-links/read.ts +104 -0
- package/src/external-links/types.ts +9 -0
- package/src/external-links/write.ts +120 -0
- package/src/image/excel.ts +122 -0
- package/src/image/native.ts +21 -0
- package/src/image/ownership.ts +77 -0
- package/src/image/parts.ts +45 -0
- package/src/image/raster.ts +25 -0
- package/src/image/read.test.ts +95 -0
- package/src/image/read.ts +66 -0
- package/src/image/relationships.ts +26 -0
- package/src/image/types.ts +48 -0
- package/src/image/wps.ts +43 -0
- package/src/image/write.test.ts +53 -0
- package/src/image/write.ts +118 -0
- package/src/index.ts +6 -0
- package/src/metadata/dynamic-array.ts +105 -0
- package/src/metadata/package.ts +75 -0
- package/src/metadata/types.ts +7 -0
- package/src/opc/archive.ts +26 -0
- package/src/opc/ownership.ts +40 -0
- package/src/opc/relationships.ts +98 -0
- package/src/opc/revision.ts +28 -0
- package/src/opc/shape.ts +23 -0
- package/src/opc/types.ts +13 -0
- package/src/opc/xml.test.ts +49 -0
- package/src/opc/xml.ts +128 -0
- package/src/optimization/blanks.ts +53 -0
- package/src/optimization/optimize.test.ts +117 -0
- package/src/optimization/optimize.ts +41 -0
- package/src/optimization/package.ts +65 -0
- package/src/optimization/rules.ts +46 -0
- package/src/optimization/styles.ts +76 -0
- package/src/optimization/types.ts +33 -0
- package/src/package/assembly.test.ts +117 -0
- package/src/package/calculation-metadata.test.ts +85 -0
- package/src/package/calculation-metadata.ts +88 -0
- package/src/package/checkboxes.ts +37 -0
- package/src/package/cleanup.test.ts +61 -0
- package/src/package/dashboard.test.ts +53 -0
- package/src/package/dashboard.ts +84 -0
- package/src/package/extensions.ts +16 -0
- package/src/package/merge-recipes.ts +84 -0
- package/src/package/names/conditional.ts +64 -0
- package/src/package/names/defined.test.ts +52 -0
- package/src/package/names/defined.ts +75 -0
- package/src/package/names/filter.ts +68 -0
- package/src/package/names/print-layout.ts +62 -0
- package/src/package/names/print.ts +62 -0
- package/src/package/new.ts +46 -0
- package/src/package/open/appearance.ts +46 -0
- package/src/package/open/directory.ts +61 -0
- package/src/package/open/restrictions.ts +27 -0
- package/src/package/open/snapshot.test.ts +48 -0
- package/src/package/open/snapshot.ts +34 -0
- package/src/package/open/source-write.ts +130 -0
- package/src/package/open/types.ts +73 -0
- package/src/package/open/worksheets.ts +149 -0
- package/src/package/positions.ts +40 -0
- package/src/package/read.ts +143 -0
- package/src/package/save/types.ts +57 -0
- package/src/package/save/worksheets.ts +126 -0
- package/src/package/selection-copy.test.ts +70 -0
- package/src/package/styles.ts +39 -0
- package/src/package/types.ts +52 -0
- package/src/package/workbook-views.ts +34 -0
- package/src/package/worksheets.test.ts +190 -0
- package/src/package/worksheets.ts +162 -0
- package/src/package/write.ts +175 -0
- package/src/pivot/cache/calculated.ts +34 -0
- package/src/pivot/cache/dates.ts +124 -0
- package/src/pivot/cache/groups.ts +11 -0
- package/src/pivot/cache/members.ts +99 -0
- package/src/pivot/cache/numbers.ts +63 -0
- package/src/pivot/cache/read.ts +131 -0
- package/src/pivot/cache/time.ts +20 -0
- package/src/pivot/cache/values.ts +43 -0
- package/src/pivot/cache/write.ts +117 -0
- package/src/pivot/definition/axes.ts +35 -0
- package/src/pivot/definition/dates.ts +87 -0
- package/src/pivot/definition/display.ts +86 -0
- package/src/pivot/definition/extension.ts +57 -0
- package/src/pivot/definition/field-settings/caption.ts +38 -0
- package/src/pivot/definition/field-settings/comparison.ts +47 -0
- package/src/pivot/definition/field-settings/field.ts +66 -0
- package/src/pivot/definition/field-settings/filters.ts +86 -0
- package/src/pivot/definition/field-settings/measure.ts +79 -0
- package/src/pivot/definition/field-settings/types.ts +19 -0
- package/src/pivot/definition/functions.ts +21 -0
- package/src/pivot/definition/items.ts +144 -0
- package/src/pivot/definition/members.ts +98 -0
- package/src/pivot/definition/numbers.ts +19 -0
- package/src/pivot/definition/presentation.ts +52 -0
- package/src/pivot/definition/read.ts +143 -0
- package/src/pivot/definition/report-layout.ts +39 -0
- package/src/pivot/definition/write.ts +157 -0
- package/src/pivot/package/calculated.test.ts +103 -0
- package/src/pivot/package/dates.test.ts +266 -0
- package/src/pivot/package/display.test.ts +133 -0
- package/src/pivot/package/field-settings.test.ts +59 -0
- package/src/pivot/package/layout.test.ts +148 -0
- package/src/pivot/package/measure-settings.test.ts +85 -0
- package/src/pivot/package/members.test.ts +167 -0
- package/src/pivot/package/numbers.test.ts +120 -0
- package/src/pivot/package/read.ts +93 -0
- package/src/pivot/package/roundtrip.test.ts +244 -0
- package/src/pivot/package/write.ts +103 -0
- package/src/pivot/types.ts +36 -0
- package/src/pivot/xml.ts +50 -0
- package/src/presentation.test.ts +186 -0
- package/src/roundtrip.test.ts +72 -0
- package/src/styles/checkbox/bags.ts +85 -0
- package/src/styles/checkbox/style.ts +45 -0
- package/src/styles/checkbox/types.ts +7 -0
- package/src/styles/color.ts +64 -0
- package/src/styles/differential-preview.ts +60 -0
- package/src/styles/differential.ts +119 -0
- package/src/styles/numbers.ts +9 -0
- package/src/styles/parts.ts +107 -0
- package/src/styles/read.ts +95 -0
- package/src/styles/reference.ts +14 -0
- package/src/styles/types.ts +9 -0
- package/src/styles/write.test.ts +88 -0
- package/src/styles/write.ts +162 -0
- package/src/table/conversion.test.ts +73 -0
- package/src/table/definition.ts +89 -0
- package/src/table/filter.ts +42 -0
- package/src/table/ownership.ts +112 -0
- package/src/table/read.test.ts +274 -0
- package/src/table/read.ts +117 -0
- package/src/table/remove.ts +55 -0
- package/src/table/sort.test.ts +79 -0
- package/src/table/styles/builtin.ts +40 -0
- package/src/table/styles/differential.ts +55 -0
- package/src/table/styles/preset-data.ts +17 -0
- package/src/table/styles/presets/dark.ts +104 -0
- package/src/table/styles/presets/light-grid.ts +68 -0
- package/src/table/styles/presets/light.ts +145 -0
- package/src/table/styles/presets/medium-edges.ts +131 -0
- package/src/table/styles/presets/medium.ts +131 -0
- package/src/table/styles/read.ts +70 -0
- package/src/table/styles/types.ts +27 -0
- package/src/table/totals.test.ts +77 -0
- package/src/table/totals.ts +79 -0
- package/src/table/types.ts +21 -0
- package/src/table/write.ts +189 -0
- package/src/types.ts +74 -0
- package/src/value/date.ts +21 -0
- package/src/worksheet/appearance.ts +55 -0
- package/src/worksheet/axis.test.ts +185 -0
- package/src/worksheet/axis.ts +131 -0
- package/src/worksheet/background/read.ts +41 -0
- package/src/worksheet/background/roundtrip.test.ts +77 -0
- package/src/worksheet/background/write.ts +96 -0
- package/src/worksheet/cell-shift.ts +44 -0
- package/src/worksheet/cells.ts +75 -0
- package/src/worksheet/checkbox/formats.ts +53 -0
- package/src/worksheet/checkbox/ranges.ts +112 -0
- package/src/worksheet/checkbox/write.test.ts +62 -0
- package/src/worksheet/conditional/color-scale.ts +61 -0
- package/src/worksheet/conditional/data-bar.ts +76 -0
- package/src/worksheet/conditional/extensions.ts +95 -0
- package/src/worksheet/conditional/icon-reference.ts +69 -0
- package/src/worksheet/conditional/icon-set.test.ts +60 -0
- package/src/worksheet/conditional/icon-set.ts +79 -0
- package/src/worksheet/conditional/preview.ts +44 -0
- package/src/worksheet/conditional/read.ts +185 -0
- package/src/worksheet/conditional/text.test.ts +71 -0
- package/src/worksheet/conditional/text.ts +122 -0
- package/src/worksheet/conditional/threshold.ts +47 -0
- package/src/worksheet/conditional/types.ts +20 -0
- package/src/worksheet/conditional/write-bar.ts +66 -0
- package/src/worksheet/conditional/write.test.ts +218 -0
- package/src/worksheet/conditional/write.ts +103 -0
- package/src/worksheet/copied-axis.ts +70 -0
- package/src/worksheet/data/rows.ts +59 -0
- package/src/worksheet/data/source.test.ts +68 -0
- package/src/worksheet/data/source.ts +31 -0
- package/src/worksheet/data/types.ts +9 -0
- package/src/worksheet/data.test.ts +314 -0
- package/src/worksheet/dimensions/columns.ts +87 -0
- package/src/worksheet/dimensions/write.test.ts +110 -0
- package/src/worksheet/dimensions/write.ts +36 -0
- package/src/worksheet/filters/advanced.test.ts +57 -0
- package/src/worksheet/filters/color.ts +105 -0
- package/src/worksheet/filters/icon.test.ts +83 -0
- package/src/worksheet/filters/icon.ts +39 -0
- package/src/worksheet/filters/read.ts +114 -0
- package/src/worksheet/filters/relative-dates.ts +47 -0
- package/src/worksheet/filters/restore-icons.ts +33 -0
- package/src/worksheet/filters/restore.ts +169 -0
- package/src/worksheet/filters/rules.ts +23 -0
- package/src/worksheet/filters/types.ts +23 -0
- package/src/worksheet/filters/visibility.ts +188 -0
- package/src/worksheet/filters/write.ts +121 -0
- package/src/worksheet/formula/cache.ts +29 -0
- package/src/worksheet/formula/external-results.test.ts +39 -0
- package/src/worksheet/formula/functions.ts +29 -0
- package/src/worksheet/formula/prefix.ts +27 -0
- package/src/worksheet/formula/shared/read.test.ts +121 -0
- package/src/worksheet/formula/shared/read.ts +94 -0
- package/src/worksheet/formula/shared/references.ts +100 -0
- package/src/worksheet/formula/shared/types.ts +21 -0
- package/src/worksheet/formula/spill-read.ts +54 -0
- package/src/worksheet/formula/spill-write.ts +32 -0
- package/src/worksheet/formula/spill.test.ts +101 -0
- package/src/worksheet/formula/write.test.ts +26 -0
- package/src/worksheet/hyperlinks/location.ts +59 -0
- package/src/worksheet/hyperlinks/model.ts +22 -0
- package/src/worksheet/hyperlinks/read.ts +70 -0
- package/src/worksheet/hyperlinks/types.ts +21 -0
- package/src/worksheet/hyperlinks/write.test.ts +203 -0
- package/src/worksheet/hyperlinks/write.ts +51 -0
- package/src/worksheet/merge.test.ts +58 -0
- package/src/worksheet/merge.ts +61 -0
- package/src/worksheet/outline/columns.ts +46 -0
- package/src/worksheet/outline/metadata.ts +68 -0
- package/src/worksheet/outline/native.ts +81 -0
- package/src/worksheet/outline/read.ts +50 -0
- package/src/worksheet/outline/roundtrip.test.ts +73 -0
- package/src/worksheet/outline/types.ts +37 -0
- package/src/worksheet/outline/write.ts +110 -0
- package/src/worksheet/positions.test.ts +46 -0
- package/src/worksheet/positions.ts +48 -0
- package/src/worksheet/print/breaks.ts +72 -0
- package/src/worksheet/print/elements.ts +16 -0
- package/src/worksheet/print/page-text.ts +139 -0
- package/src/worksheet/print/setup.test.ts +141 -0
- package/src/worksheet/print/setup.ts +116 -0
- package/src/worksheet/progress/read.ts +73 -0
- package/src/worksheet/progress/solid.ts +26 -0
- package/src/worksheet/progress/types.ts +11 -0
- package/src/worksheet/progress/write.test.ts +63 -0
- package/src/worksheet/progress/write.ts +46 -0
- package/src/worksheet/read.ts +197 -0
- package/src/worksheet/rich-text.test.ts +41 -0
- package/src/worksheet/rich-text.ts +76 -0
- package/src/worksheet/sort/read.ts +115 -0
- package/src/worksheet/sort/relocate.ts +62 -0
- package/src/worksheet/sort/roundtrip.test.ts +116 -0
- package/src/worksheet/sort/types.ts +11 -0
- package/src/worksheet/sort/write.ts +77 -0
- package/src/worksheet/template.ts +9 -0
- package/src/worksheet/text.ts +33 -0
- package/src/worksheet/validation/extended.ts +36 -0
- package/src/worksheet/validation/image.ts +7 -0
- package/src/worksheet/validation/list-options/portable.ts +90 -0
- package/src/worksheet/validation/list-options/types.ts +14 -0
- package/src/worksheet/validation/list-options/wps.ts +51 -0
- package/src/worksheet/validation/read.ts +162 -0
- package/src/worksheet/validation/text.ts +13 -0
- package/src/worksheet/validation/write.test.ts +259 -0
- package/src/worksheet/validation/write.ts +99 -0
- package/src/worksheet/view/coordinates.ts +39 -0
- package/src/worksheet/view/named/read.ts +116 -0
- package/src/worksheet/view/named/roundtrip.test.ts +136 -0
- package/src/worksheet/view/named/sort.ts +57 -0
- package/src/worksheet/view/named/types.ts +15 -0
- package/src/worksheet/view/named/write.ts +107 -0
- package/src/worksheet/view/named/xml.ts +33 -0
- package/src/worksheet/view/panes.ts +75 -0
- package/src/worksheet/view/read.ts +61 -0
- package/src/worksheet/view/relocate.ts +57 -0
- package/src/worksheet/view/write.test.ts +91 -0
- package/src/worksheet/view/write.ts +57 -0
- package/src/worksheet/write.ts +86 -0
- package/README.md +0 -3
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import type { WorkbookCellImage } from "@quirekit/workbook";
|
|
3
|
+
import { hasKnownAttributes, hasKnownChildren } from "../opc/shape";
|
|
4
|
+
import { readRelationships, relationshipsPath } from "../opc/relationships";
|
|
5
|
+
import type { PackageRelationship } from "../opc/types";
|
|
6
|
+
import { child, children, parsePart, readIndex, relationshipNs, rootOf, spreadNs } from "../opc/xml";
|
|
7
|
+
import { decodeXlsxText } from "../worksheet/text";
|
|
8
|
+
import { xlsxImageMetadataExtension as richMetadataExtension, xlsxImageMetadataName as valueMetadataName, xlsxImageRoles,
|
|
9
|
+
xlsxRichValueNs as richNs, xlsxRichValueRelationNs as richRelNs } from "./native";
|
|
10
|
+
import { countedChildren, ownsExcelImageMetadata, ownsExcelImageRelations, ownsOptionalExcelImageTypes } from "./ownership";
|
|
11
|
+
import { retainedXlsxRelationshipTargets } from "./relationships";
|
|
12
|
+
import type { XlsxExcelImages, XlsxImageAssetReader } from "./types";
|
|
13
|
+
|
|
14
|
+
/** @param parts - Native package entries. @param workbookRelations - Workbook part relationships.
|
|
15
|
+
* @param readAsset - Local raster resolver. @param workbookPath - Owner of workbook-level relationships. @returns Indexed images and original parts when all their semantics are supported. */
|
|
16
|
+
export function readExcelCellImages(parts: Readonly<Record<string, Uint8Array>>, workbookRelations: ReadonlyMap<string, PackageRelationship>,
|
|
17
|
+
readAsset: XlsxImageAssetReader, workbookPath: string): XlsxExcelImages {
|
|
18
|
+
const byRole = new Map<string, PackageRelationship>();
|
|
19
|
+
for (const relation of workbookRelations.values()) {
|
|
20
|
+
if (!Object.values<string>(xlsxImageRoles).includes(relation.type)) continue;
|
|
21
|
+
if (!relation.path || byRole.has(relation.type)) throw new Error("无法定位 XLSX 格内图片部件。");
|
|
22
|
+
byRole.set(relation.type, relation);
|
|
23
|
+
}
|
|
24
|
+
const metadataPath = byRole.get(xlsxImageRoles.metadata)?.path;
|
|
25
|
+
const relationshipsOwner = byRole.get(xlsxImageRoles.relations)?.path;
|
|
26
|
+
const valuesPath = byRole.get(xlsxImageRoles.values)?.path;
|
|
27
|
+
const structuresPath = byRole.get(xlsxImageRoles.structures)?.path;
|
|
28
|
+
if (!metadataPath || !relationshipsOwner || !valuesPath || !structuresPath) throw new Error("XLSX 缺少格内图片部件。");
|
|
29
|
+
const metadata = rootOf(parsePart(parts[metadataPath], metadataPath), spreadNs, "metadata");
|
|
30
|
+
const imageRelations = rootOf(parsePart(parts[relationshipsOwner], relationshipsOwner), richRelNs, "richValueRels");
|
|
31
|
+
const values = rootOf(parsePart(parts[valuesPath], valuesPath), richNs, "rvData");
|
|
32
|
+
const structures = rootOf(parsePart(parts[structuresPath], structuresPath), richNs, "rvStructures");
|
|
33
|
+
const relationshipPath = relationshipsPath(relationshipsOwner);
|
|
34
|
+
const relationships = readRelationships(parsePart(parts[relationshipPath], relationshipPath), relationshipsOwner);
|
|
35
|
+
|
|
36
|
+
// These arrays preserve documented record ordinals even when an individual slot is unsupported.
|
|
37
|
+
const relationNodes = children(imageRelations, "rel");
|
|
38
|
+
const local = relationNodes.map(entry => entry.namespaceURI === richRelNs
|
|
39
|
+
? readAsset(relationships.get(entry.getAttributeNS(relationshipNs, "id") ?? "")) : undefined);
|
|
40
|
+
const structureNodes = children(structures, "s");
|
|
41
|
+
const schemas = structureNodes.map(entry => {
|
|
42
|
+
if (entry.namespaceURI !== richNs || entry.getAttribute("t") !== "_localImage") return undefined;
|
|
43
|
+
const keys = children(entry, "k");
|
|
44
|
+
const targets = keys.filter(key => key.getAttribute("n") === "_rvRel:LocalImageIdentifier");
|
|
45
|
+
if (targets.length !== 1 || targets[0]!.namespaceURI !== richNs || targets[0]!.getAttribute("t") !== "i") return undefined;
|
|
46
|
+
/** @param name - Supported key name. @param type - Native key type. @returns Its ordinal or -1. */
|
|
47
|
+
const position = (name: string, type: string) => keys.findIndex(key => key.namespaceURI === richNs
|
|
48
|
+
&& key.getAttribute("n") === name && key.getAttribute("t") === type);
|
|
49
|
+
const image = keys.indexOf(targets[0]!), alt = position("Text", "s"), origin = position("CalcOrigin", "i");
|
|
50
|
+
const portable = hasKnownAttributes(entry, ["t"]) && keys.length === children(entry).length
|
|
51
|
+
&& keys.length === 1 + (alt >= 0 ? 1 : 0) + (origin >= 0 ? 1 : 0)
|
|
52
|
+
&& keys.every(key => hasKnownAttributes(key, ["n", "t"]) && hasKnownChildren(key, []));
|
|
53
|
+
return { image, alt, origin, length: keys.length, portable };
|
|
54
|
+
});
|
|
55
|
+
const valueNodes = children(values, "rv");
|
|
56
|
+
let everyValuePortable = true;
|
|
57
|
+
const images = valueNodes.map(entry => {
|
|
58
|
+
const index = readIndex(entry, "s");
|
|
59
|
+
const schema = index === undefined ? undefined : schemas[index];
|
|
60
|
+
if (!schema || entry.namespaceURI !== richNs) return undefined;
|
|
61
|
+
const values = children(entry, "v");
|
|
62
|
+
const reference = values[schema.image];
|
|
63
|
+
const id = reference?.namespaceURI === richNs && reference.textContent;
|
|
64
|
+
const asset = id && /^\d+$/u.test(id) ? local[Number(id)] : undefined;
|
|
65
|
+
if (!asset) return undefined;
|
|
66
|
+
const text = values[schema.alt];
|
|
67
|
+
const rawAlt = text?.namespaceURI === richNs && text.textContent;
|
|
68
|
+
const alt = rawAlt ? decodeXlsxText(rawAlt) : "";
|
|
69
|
+
everyValuePortable &&= schema.portable && values.length === schema.length && values.length === children(entry).length
|
|
70
|
+
&& (schema.origin < 0 || values[schema.origin]?.textContent === "5")
|
|
71
|
+
&& hasKnownAttributes(entry, ["s"]) && values.every(value => value.namespaceURI === richNs && hasKnownAttributes(value, []) && hasKnownChildren(value, []))
|
|
72
|
+
&& alt.length <= 32767;
|
|
73
|
+
return Object.freeze({ asset, ...(alt && { alt }) });
|
|
74
|
+
});
|
|
75
|
+
const records = readImageMetadata(metadata, images);
|
|
76
|
+
let owned: XlsxExcelImages["owned"];
|
|
77
|
+
// Preview survives unusual metadata. Write authority requires a fully modeled, exclusively owned graph.
|
|
78
|
+
try {
|
|
79
|
+
const candidate = [...byRole.values()];
|
|
80
|
+
const paths = new Set(candidate.map(({ path }) => path));
|
|
81
|
+
const externalTargets = retainedXlsxRelationshipTargets(parts, relationshipsPath(workbookPath));
|
|
82
|
+
if (externalTargets && paths.size === candidate.length && [...paths].every(path => path && !externalTargets.has(path))
|
|
83
|
+
&& [...workbookRelations.values()].every(entry => !paths.has(entry.path) || byRole.get(entry.type) === entry)
|
|
84
|
+
&& candidate.every(({ path }) => path === relationshipsOwner || !parts[relationshipsPath(path!)])
|
|
85
|
+
&& hasKnownAttributes(values, ["count"]) && hasKnownAttributes(structures, ["count"])
|
|
86
|
+
&& countedChildren(values, "rv").length === valueNodes.length && countedChildren(structures, "s").length === structureNodes.length
|
|
87
|
+
&& everyValuePortable && schemas.every(schema => schema?.portable) && images.every(Boolean) && records.length > 0 && records.every(Boolean)
|
|
88
|
+
&& local.every(Boolean) && countedChildren(imageRelations, "rel").length === relationNodes.length
|
|
89
|
+
&& ownsExcelImageRelations(relationNodes, imageRelations, relationships) && ownsExcelImageMetadata(metadata)
|
|
90
|
+
&& ownsOptionalExcelImageTypes(parts, byRole.get(xlsxImageRoles.types))) {
|
|
91
|
+
owned = { roles: candidate, relationPath: relationshipsOwner, media: [...new Set([...relationships.values()].flatMap(({ path }) => path ? [path] : []))] };
|
|
92
|
+
}
|
|
93
|
+
} catch { /* Unmodeled XML contributes only a source preview. */ }
|
|
94
|
+
return { images: records, owned };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** @param metadata - Workbook's sheet metadata. @param images - The rich value table, with unsupported slots.
|
|
98
|
+
* @returns Values resolved from each metadata block through the rich future metadata index. */
|
|
99
|
+
function readImageMetadata(metadata: Element, images: readonly (WorkbookCellImage | undefined)[]): readonly (WorkbookCellImage | undefined)[] {
|
|
100
|
+
const types = child(metadata, "metadataTypes");
|
|
101
|
+
const values = child(metadata, "valueMetadata");
|
|
102
|
+
const catalogs = children(metadata, "futureMetadata").filter(node => node.namespaceURI === spreadNs
|
|
103
|
+
&& node.getAttribute("name") === valueMetadataName);
|
|
104
|
+
if (!types || !values || catalogs.length !== 1) return [];
|
|
105
|
+
const typeNames = children(types, "metadataType").map(node => node.namespaceURI === spreadNs && node.getAttribute("name"));
|
|
106
|
+
const catalog = children(catalogs[0]!, "bk").map(block => {
|
|
107
|
+
const list = child(block, "extLst");
|
|
108
|
+
if (!list || block.namespaceURI !== spreadNs) return undefined;
|
|
109
|
+
const extension = children(list, "ext").find(node => node.namespaceURI === spreadNs
|
|
110
|
+
&& node.getAttribute("uri")?.toLowerCase() === richMetadataExtension);
|
|
111
|
+
const value = extension && child(extension, "rvb");
|
|
112
|
+
const index = value?.namespaceURI === richNs ? readIndex(value, "i") : undefined;
|
|
113
|
+
return index === undefined ? undefined : images[index];
|
|
114
|
+
});
|
|
115
|
+
return children(values, "bk").map(block => {
|
|
116
|
+
if (block.namespaceURI !== spreadNs) return undefined;
|
|
117
|
+
const records = children(block, "rc").filter(node => node.namespaceURI === spreadNs
|
|
118
|
+
&& typeNames[(readIndex(node, "t") ?? 0) - 1] === valueMetadataName);
|
|
119
|
+
const index = records.length === 1 ? readIndex(records[0], "v") : undefined;
|
|
120
|
+
return index === undefined ? undefined : catalog[index];
|
|
121
|
+
});
|
|
122
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { relationshipNs } from "../opc/xml";
|
|
2
|
+
|
|
3
|
+
/** Namespaces used for native spreadsheet rich values. */
|
|
4
|
+
export const xlsxRichValueNs = "http://schemas.microsoft.com/office/spreadsheetml/2017/richdata";
|
|
5
|
+
export const xlsxRichValueTypeNs = "http://schemas.microsoft.com/office/spreadsheetml/2017/richdata2";
|
|
6
|
+
export const xlsxRichValueRelationNs = "http://schemas.microsoft.com/office/spreadsheetml/2022/richvaluerel";
|
|
7
|
+
|
|
8
|
+
const richRole = "http://schemas.microsoft.com/office/2017/06/relationships/";
|
|
9
|
+
|
|
10
|
+
/** Relationship roles owned by the standalone image graph. */
|
|
11
|
+
export const xlsxImageRoles = {
|
|
12
|
+
metadata: relationshipNs + "/sheetMetadata",
|
|
13
|
+
relations: "http://schemas.microsoft.com/office/2022/10/relationships/richValueRel",
|
|
14
|
+
values: richRole + "rdRichValue",
|
|
15
|
+
structures: richRole + "rdRichValueStructure",
|
|
16
|
+
types: richRole + "rdRichValueTypes"
|
|
17
|
+
} as const;
|
|
18
|
+
|
|
19
|
+
/** Metadata type and extension identifying an indexed rich value. */
|
|
20
|
+
export const xlsxImageMetadataName = "XLRICHVALUE";
|
|
21
|
+
export const xlsxImageMetadataExtension = "{3e2802c4-a4d2-4d8b-9148-e3be6c30e623}";
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import type { PackageRelationship } from "../opc/types";
|
|
3
|
+
import { hasKnownAttributes, hasKnownChildren } from "../opc/shape";
|
|
4
|
+
import { child, children, parsePart, readIndex, relationshipNs, rootOf } from "../opc/xml";
|
|
5
|
+
import { relationshipsPath } from "../opc/relationships";
|
|
6
|
+
import { readXlsxDynamicArrayMetadata, xlsxMetadataFlags } from "../metadata/dynamic-array";
|
|
7
|
+
import { xlsxImageMetadataExtension, xlsxImageMetadataName, xlsxRichValueNs, xlsxRichValueRelationNs, xlsxRichValueTypeNs } from "./native";
|
|
8
|
+
|
|
9
|
+
/** @param root - Sheet metadata root. @returns Whether every metadata record is the modeled rich image mapping. */
|
|
10
|
+
export function ownsExcelImageMetadata(root: Element): boolean {
|
|
11
|
+
const types = child(root, "metadataTypes"), values = child(root, "valueMetadata");
|
|
12
|
+
const arrays = readXlsxDynamicArrayMetadata(root);
|
|
13
|
+
const futures = children(root, "futureMetadata").filter(node => node.getAttribute("name") === xlsxImageMetadataName);
|
|
14
|
+
const future = futures.length === 1 && futures[0];
|
|
15
|
+
const typeList = types && countedChildren(types, "metadataType");
|
|
16
|
+
const typeIndex = typeList ? typeList.findIndex(node => node.getAttribute("name") === xlsxImageMetadataName) : -1;
|
|
17
|
+
const type = typeList && typeList[typeIndex];
|
|
18
|
+
const members = children(root);
|
|
19
|
+
const known = arrays ? members.length === 5 && members.every(node => node.namespaceURI === root.namespaceURI
|
|
20
|
+
&& ["metadataTypes", "futureMetadata", "valueMetadata", "cellMetadata"].includes(node.localName ?? ""))
|
|
21
|
+
: hasKnownChildren(root, ["metadataTypes", "futureMetadata", "valueMetadata"]);
|
|
22
|
+
if (!type || !types || !future || !values || !known || !hasKnownAttributes(root, [])
|
|
23
|
+
|| !hasKnownAttributes(types, ["count"]) || typeList!.length !== (arrays ? 2 : 1)
|
|
24
|
+
|| !hasKnownAttributes(type, xlsxMetadataFlags) || !hasKnownChildren(type, [])
|
|
25
|
+
|| type.getAttribute("cellMeta") === "1" || type.getAttribute("cellMeta") === "true"
|
|
26
|
+
|| !hasKnownAttributes(future, ["name", "count"]) || future.getAttribute("name") !== xlsxImageMetadataName
|
|
27
|
+
|| !hasKnownAttributes(values, ["count"])) return false;
|
|
28
|
+
|
|
29
|
+
return countedChildren(future, "bk").every(block => {
|
|
30
|
+
const extensionList = child(block, "extLst"), extension = extensionList && child(extensionList, "ext");
|
|
31
|
+
const richBlock = extension && child(extension, "rvb");
|
|
32
|
+
return Boolean(richBlock && extension && extensionList && hasKnownAttributes(block, [])
|
|
33
|
+
&& hasKnownChildren(block, ["extLst"]) && hasKnownAttributes(extensionList, []) && hasKnownChildren(extensionList, ["ext"])
|
|
34
|
+
&& hasKnownAttributes(extension, ["uri"]) && extension.getAttribute("uri")?.toLowerCase() === xlsxImageMetadataExtension
|
|
35
|
+
&& hasKnownChildren(extension, ["rvb"], extension.namespaceURI, { rvb: xlsxRichValueNs })
|
|
36
|
+
&& hasKnownAttributes(richBlock, ["i"]) && hasKnownChildren(richBlock, []) && readIndex(richBlock, "i") !== undefined);
|
|
37
|
+
}) && countedChildren(values, "bk").every(block => {
|
|
38
|
+
const record = child(block, "rc");
|
|
39
|
+
return Boolean(record && hasKnownAttributes(block, []) && hasKnownChildren(block, ["rc"])
|
|
40
|
+
&& hasKnownAttributes(record, ["t", "v"]) && hasKnownChildren(record, []) && readIndex(record, "t") === typeIndex + 1
|
|
41
|
+
&& readIndex(record, "v") !== undefined);
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** @param root - Native rich part container. @param name - Name repeated in source order.
|
|
46
|
+
* @returns All modeled entries, or throws before ownership can be assigned to a malformed graph. */
|
|
47
|
+
export function countedChildren(root: Element, name: string): Element[] {
|
|
48
|
+
const all = children(root);
|
|
49
|
+
if (!all.every(node => node.localName === name && node.namespaceURI === root.namespaceURI)
|
|
50
|
+
|| root.hasAttribute("count") && readIndex(root, "count") !== all.length) throw new Error("格内图片元数据包含额外部件。");
|
|
51
|
+
return all;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** @param relations - Rich value relationship ordinal entries. @param attributesOwner - Native image relationship root.
|
|
55
|
+
* @param source - Image-owned relationship table. @returns Whether all edges are local raster links. */
|
|
56
|
+
export function ownsExcelImageRelations(relations: readonly Element[], attributesOwner: Element,
|
|
57
|
+
source: ReadonlyMap<string, PackageRelationship>): boolean {
|
|
58
|
+
if (!hasKnownAttributes(attributesOwner, []) || relations.length !== source.size) return false;
|
|
59
|
+
const used = new Set<string>();
|
|
60
|
+
for (const entry of relations) {
|
|
61
|
+
const id = entry.getAttributeNS(relationshipNs, "id");
|
|
62
|
+
const relation = id && source.get(id);
|
|
63
|
+
if (!id || used.has(id) || !relation || !relation.path || relation.type !== relationshipNs + "/image"
|
|
64
|
+
|| entry.namespaceURI !== xlsxRichValueRelationNs || !hasKnownAttributes(entry, [], true) || !hasKnownChildren(entry, [])) return false;
|
|
65
|
+
used.add(id);
|
|
66
|
+
}
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** @param parts - Retained archive. @param part - Optional types part.
|
|
71
|
+
* @returns Whether it has only type-wide settings and no other modeled or foreign rich values. */
|
|
72
|
+
export function ownsOptionalExcelImageTypes(parts: Readonly<Record<string, Uint8Array>>, part: PackageRelationship | undefined): boolean {
|
|
73
|
+
if (!part) return true;
|
|
74
|
+
if (!part.path || parts[relationshipsPath(part.path)]) return false;
|
|
75
|
+
const root = rootOf(parsePart(parts[part.path], part.path), xlsxRichValueTypeNs, "rvTypesInfo");
|
|
76
|
+
return hasKnownChildren(root, ["global"]);
|
|
77
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { strToU8 } from "fflate";
|
|
2
|
+
import { relationshipNs, spreadNs } from "../opc/xml";
|
|
3
|
+
import { encodeXlsxText } from "../worksheet/text";
|
|
4
|
+
import { xlsxImageMetadataExtension, xlsxImageMetadataName, xlsxRichValueNs, xlsxRichValueRelationNs } from "./native";
|
|
5
|
+
import type { XlsxCellImageValue } from "./types";
|
|
6
|
+
|
|
7
|
+
/** @param count - Number of image metadata records. @returns Worksheet value metadata with one-based vm references. */
|
|
8
|
+
export function xlsxImageMetadata(count: number): Uint8Array {
|
|
9
|
+
const records = Array.from({ length: count }, (_, index) => index);
|
|
10
|
+
const future = records.map(index =>
|
|
11
|
+
'<bk><extLst><ext uri="' + xlsxImageMetadataExtension + '"><xlrd:rvb i="' + index + '"/></ext></extLst></bk>').join("");
|
|
12
|
+
const values = records.map(index => '<bk><rc t="1" v="' + index + '"/></bk>').join("");
|
|
13
|
+
return strToU8('<metadata xmlns="' + spreadNs + '" xmlns:xlrd="' + xlsxRichValueNs + '">'
|
|
14
|
+
+ '<metadataTypes count="1"><metadataType name="' + xlsxImageMetadataName + '" minSupportedVersion="120000"'
|
|
15
|
+
+ ' copy="1" pasteAll="1" pasteValues="1" merge="1" splitFirst="1" rowColShift="1" clearFormats="1" clearComments="1" assign="1" coerce="1"/></metadataTypes>'
|
|
16
|
+
+ '<futureMetadata name="' + xlsxImageMetadataName + '" count="' + count + '">' + future + '</futureMetadata>'
|
|
17
|
+
+ '<valueMetadata count="' + count + '">' + values + '</valueMetadata></metadata>');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** @returns Structures for local images with and without alternative text. */
|
|
21
|
+
export function xlsxImageStructures(): Uint8Array {
|
|
22
|
+
const common = '<k n="_rvRel:LocalImageIdentifier" t="i"/><k n="CalcOrigin" t="i"/>';
|
|
23
|
+
return strToU8('<rvStructures xmlns="' + xlsxRichValueNs + '" count="2"><s t="_localImage">' + common + '</s><s t="_localImage">'
|
|
24
|
+
+ common + '<k n="Text" t="s"/></s></rvStructures>');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** @param records - Ordered image values as referenced by metadata. @returns Native local image rich value payload. */
|
|
28
|
+
export function xlsxImageValues(records: readonly XlsxCellImageValue[]): Uint8Array {
|
|
29
|
+
const values = records.map(({ media, alt }) => {
|
|
30
|
+
const text = alt ? '<v>' + xmlText(encodeXlsxText(alt)) + '</v>' : "";
|
|
31
|
+
return '<rv s="' + (alt ? 1 : 0) + '"><v>' + media + '</v><v>5</v>' + text + '</rv>';
|
|
32
|
+
});
|
|
33
|
+
return strToU8('<rvData xmlns="' + xlsxRichValueNs + '" count="' + records.length + '">' + values.join("") + '</rvData>');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** @param ids - Media relationship IDs in their zero-based reference order. @returns Native rich value relationship list. */
|
|
37
|
+
export function xlsxImageRelations(ids: readonly string[]): Uint8Array {
|
|
38
|
+
return strToU8('<richValueRels xmlns="' + xlsxRichValueRelationNs + '" xmlns:r="' + relationshipNs + '">'
|
|
39
|
+
+ ids.map(id => '<rel r:id="' + id + '"/>').join("") + '</richValueRels>');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** @param text - Alternative text with SpreadsheetML escapes already applied. @returns XML body text. */
|
|
43
|
+
function xmlText(text: string): string {
|
|
44
|
+
return text.replace(/&/gu, "&").replace(/</gu, "<").replace(/>/gu, ">");
|
|
45
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { readWorkbookRaster, type WorkbookCellImageAsset } from "@quirekit/workbook";
|
|
2
|
+
import { relationshipNs } from "../opc/xml";
|
|
3
|
+
import type { XlsxImageAssetReader } from "./types";
|
|
4
|
+
|
|
5
|
+
/** @param parts - Package entries under the existing decompression budget.
|
|
6
|
+
* @returns Validated local raster resources memoized by actual image-part path. */
|
|
7
|
+
export function createXlsxImageAssetReader(parts: Readonly<Record<string, Uint8Array>>): XlsxImageAssetReader {
|
|
8
|
+
const resources = new Map<string, WorkbookCellImageAsset | undefined>();
|
|
9
|
+
return relation => {
|
|
10
|
+
if (!relation?.path || relation.type !== relationshipNs + "/image") return undefined;
|
|
11
|
+
const path = relation.path;
|
|
12
|
+
if (!resources.has(path)) resources.set(path, localRaster(parts[path]));
|
|
13
|
+
return resources.get(path);
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** @param bytes - Contained image part. @returns Bounded local PNG/JPEG, when its header supplies a valid intrinsic size. */
|
|
18
|
+
function localRaster(bytes: Uint8Array | undefined): WorkbookCellImageAsset | undefined {
|
|
19
|
+
const header = readWorkbookRaster(bytes);
|
|
20
|
+
if (!bytes || !header) return;
|
|
21
|
+
return Object.freeze({ ...header,
|
|
22
|
+
/** @returns Detached original raster bytes. */
|
|
23
|
+
bytes() { return Uint8Array.from(bytes); }
|
|
24
|
+
});
|
|
25
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
|
|
5
|
+
import { expect, test } from "vitest";
|
|
6
|
+
import { workbookImagePresentation } from "@quirekit/workbook";
|
|
7
|
+
import { openXlsx } from "../package/read";
|
|
8
|
+
|
|
9
|
+
/** @param name - Small workbook fixture. @returns The untouched archived bytes. */
|
|
10
|
+
function fixture(name: string): Uint8Array {
|
|
11
|
+
return Uint8Array.from(readFileSync(new URL("../../test/fixtures/" + name, import.meta.url)));
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** @param xlsx - Imported workbook. @param sheet - Sheet position. @param row - Zero-based row.
|
|
15
|
+
* @param column - Zero-based column. @returns The resolved visual value. */
|
|
16
|
+
function at(xlsx: ReturnType<typeof openXlsx>, sheet: number, row: number, column: number) {
|
|
17
|
+
const source = xlsx.snapshot.sheets[sheet]!;
|
|
18
|
+
const input = source.cells.find(cell => cell.row === row && cell.column === column)?.input;
|
|
19
|
+
if (input?.kind === "image") {
|
|
20
|
+
const asset = xlsx.snapshot.imageAssets?.find(record => record.id === input.assetId);
|
|
21
|
+
if (asset) return { asset: workbookImagePresentation(asset), alt: input.alt };
|
|
22
|
+
}
|
|
23
|
+
return xlsx.cellImages.get(source.id)?.get(row)?.get(column);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
test("projects native Excel PNG and JPEG values by metadata index and shares identical media across sheets", () => {
|
|
27
|
+
const bytes = fixture("excel-cell-images.xlsx");
|
|
28
|
+
const xlsx = openXlsx("products", bytes);
|
|
29
|
+
const png = at(xlsx, 0, 1, 1);
|
|
30
|
+
expect(png).toMatchObject({ alt: "Orange and green product", asset: { mimeType: "image/png", width: 120, height: 64 } });
|
|
31
|
+
expect(at(xlsx, 0, 7, 2)).toMatchObject({ alt: "Purple product", asset: { mimeType: "image/jpeg", width: 120, height: 64 } });
|
|
32
|
+
expect(at(xlsx, 1, 3, 2)?.asset.bytes()).toEqual(png?.asset.bytes());
|
|
33
|
+
expect(xlsx.snapshot.imageAssets).toHaveLength(3);
|
|
34
|
+
expect(xlsx.snapshot.sheets[0]?.cells.find(cell => cell.row === 1 && cell.column === 1)?.input)
|
|
35
|
+
.toMatchObject({ kind: "image", alt: "Orange and green product" });
|
|
36
|
+
expect(at(xlsx, 0, 1, 2)).toBeUndefined();
|
|
37
|
+
expect(xlsx.restrictions).toEqual([]);
|
|
38
|
+
expect(xlsx.write(xlsx.snapshot)).toEqual(bytes);
|
|
39
|
+
|
|
40
|
+
const image = png!.asset.bytes();
|
|
41
|
+
image.fill(0);
|
|
42
|
+
expect(png?.asset.bytes()[0]).toBe(137);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test("resolves the WPS formula through its workbook relationship and preserves the original formula", () => {
|
|
46
|
+
const bytes = fixture("wps-cell-image.xlsx");
|
|
47
|
+
const parts = unzipSync(bytes);
|
|
48
|
+
const originalXml = parts["xl/cellimages.xml"]!;
|
|
49
|
+
delete parts["xl/cellimages.xml"];
|
|
50
|
+
parts["xl/prv/pictures.xml"] = originalXml;
|
|
51
|
+
parts["xl/prv/_rels/pictures.xml.rels"] = strToU8(strFromU8(parts["xl/_rels/cellimages.xml.rels"]!).replace("media/sample.png", "../media/sample.png"));
|
|
52
|
+
delete parts["xl/_rels/cellimages.xml.rels"];
|
|
53
|
+
for (const path of ["xl/_rels/workbook.xml.rels", "[Content_Types].xml"]) {
|
|
54
|
+
parts[path] = strToU8(strFromU8(parts[path]!).replace("cellimages.xml", "prv/pictures.xml"));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const moved = zipSync(parts);
|
|
58
|
+
const xlsx = openXlsx("products", moved);
|
|
59
|
+
expect(at(xlsx, 0, 1, 1)).toMatchObject({ alt: "合成产品图片", asset: { mimeType: "image/png", width: 30, height: 20 } });
|
|
60
|
+
expect(xlsx.snapshot.sheets[0]?.cells.find(({ row, column }) => row === 1 && column === 1)?.input)
|
|
61
|
+
.toEqual({ kind: "formula", formula: '=_xlfn.DISPIMG("ID_EE00112233445566778899AABBCCDDEE",1)' });
|
|
62
|
+
expect(xlsx.restrictions).toContain("单元格图片");
|
|
63
|
+
expect(xlsx.write(xlsx.snapshot)).toEqual(moved);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
test("keeps readable cells and retained source when a metadata entry or a media target is invalid", () => {
|
|
67
|
+
const parts = unzipSync(fixture("excel-cell-images.xlsx"));
|
|
68
|
+
const metaPath = "xl/metadata.xml";
|
|
69
|
+
const relsPath = "xl/richData/_rels/richValueRel.xml.rels";
|
|
70
|
+
parts[metaPath] = strToU8(strFromU8(parts[metaPath]!).replace('<xlrd:rvb i="0"/>', '<xlrd:rvb i="1000"/>'));
|
|
71
|
+
parts[relsPath] = strToU8(strFromU8(parts[relsPath]!).replace('Target="../media/image2.jpeg"', 'TargetMode="External" Target="https://example.com/only-local.jpg"'));
|
|
72
|
+
const bytes = zipSync(parts);
|
|
73
|
+
const xlsx = openXlsx("products", bytes);
|
|
74
|
+
expect(at(xlsx, 0, 1, 1)).toBeUndefined();
|
|
75
|
+
expect(at(xlsx, 0, 7, 2)).toBeUndefined();
|
|
76
|
+
expect(at(xlsx, 0, 400, 2)?.alt).toBe("Distant product");
|
|
77
|
+
expect(xlsx.snapshot.sheets[0]?.cells[0]?.input).toEqual({ kind: "value", value: "Frozen product" });
|
|
78
|
+
expect(xlsx.restrictions.length).toBeGreaterThan(0);
|
|
79
|
+
expect(xlsx.write(xlsx.snapshot)).toEqual(bytes);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test("declines oversized raster dimensions and duplicate WPS image identifiers without dropping the workbook", () => {
|
|
83
|
+
const source = unzipSync(fixture("wps-cell-image.xlsx"));
|
|
84
|
+
const path = "xl/cellimages.xml";
|
|
85
|
+
const xml = strFromU8(source[path]!);
|
|
86
|
+
const entry = /<etc:cellImage>.*?<\/etc:cellImage>/su.exec(xml)![0];
|
|
87
|
+
const duplicate = { ...source, [path]: strToU8(xml.replace(entry, entry + entry)) };
|
|
88
|
+
expect(openXlsx("duplicates", zipSync(duplicate)).cellImages.size).toBe(0);
|
|
89
|
+
|
|
90
|
+
const bytes = source["xl/media/sample.png"]!;
|
|
91
|
+
const header = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
92
|
+
header.setUint32(16, 40_000);
|
|
93
|
+
header.setUint32(20, 40_000);
|
|
94
|
+
expect(openXlsx("oversized", zipSync(source)).cellImages.size).toBe(0);
|
|
95
|
+
});
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { createWorkbookImageAsset, type WorkbookCellImage, type WorkbookCellImageAsset, type WorkbookRasterAsset } from "@quirekit/workbook";
|
|
2
|
+
import type { PackageRelationship } from "../opc/types";
|
|
3
|
+
import { child, readIndex, spreadNs } from "../opc/xml";
|
|
4
|
+
import { readExcelCellImages } from "./excel";
|
|
5
|
+
import { xlsxImageRoles } from "./native";
|
|
6
|
+
import { createXlsxImageAssetReader } from "./raster";
|
|
7
|
+
import type { XlsxCellImagesImport, XlsxExcelImages } from "./types";
|
|
8
|
+
import { readWpsCellImages, wpsCellImageRole } from "./wps";
|
|
9
|
+
|
|
10
|
+
const wpsFormula = /^\s*(?:_xlfn\.)?DISPIMG\(\s*"([^"]+)"\s*(?:,\s*[12]\s*)?\)\s*$/iu;
|
|
11
|
+
|
|
12
|
+
/** @param parts - Parts of the retained XLSX package. @param relationships - Workbook relationships.
|
|
13
|
+
* @param restrictions - Read-only diagnostics owned by the file codec. @param workbookPath - Workbook relationship owner.
|
|
14
|
+
* @returns Resolver and native write authority, when the file has a known image format. */
|
|
15
|
+
export function createXlsxCellImageImport(parts: Readonly<Record<string, Uint8Array>>,
|
|
16
|
+
relationships: ReadonlyMap<string, PackageRelationship>, restrictions: Set<string>, workbookPath: string): XlsxCellImagesImport | undefined {
|
|
17
|
+
const workbookRelations = [...relationships.values()];
|
|
18
|
+
const wps = workbookRelations.filter(({ type }) => type === wpsCellImageRole);
|
|
19
|
+
const withRichValues = workbookRelations.some(({ type }) => type === xlsxImageRoles.relations);
|
|
20
|
+
if (!wps.length && !withRichValues) return;
|
|
21
|
+
const readAsset = createXlsxImageAssetReader(parts);
|
|
22
|
+
const resources = new Map<WorkbookCellImageAsset, WorkbookRasterAsset>();
|
|
23
|
+
let excel: XlsxExcelImages | undefined;
|
|
24
|
+
let pictures: ReadonlyMap<string, WorkbookCellImage> | undefined;
|
|
25
|
+
|
|
26
|
+
// A malformed image graph cannot take away access to the other format or to ordinary cell values.
|
|
27
|
+
if (withRichValues) {
|
|
28
|
+
try { excel = readExcelCellImages(parts, relationships, readAsset, workbookPath); }
|
|
29
|
+
catch { restrictions.add("部分单元格图片无法读取"); }
|
|
30
|
+
}
|
|
31
|
+
if (wps.length) {
|
|
32
|
+
try {
|
|
33
|
+
if (wps.length !== 1 || !wps[0]?.path) throw new Error("无法定位 WPS 格内图片部件。");
|
|
34
|
+
pictures = readWpsCellImages(parts, wps[0].path, readAsset);
|
|
35
|
+
} catch { restrictions.add("部分单元格图片无法读取"); }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const graph = excel?.owned;
|
|
39
|
+
return {
|
|
40
|
+
graph,
|
|
41
|
+
/** @param cell - Native worksheet cell. @returns Its supported image value or a retained source preview. */
|
|
42
|
+
resolve(cell) {
|
|
43
|
+
const id = readIndex(cell, "vm");
|
|
44
|
+
const picture = id === undefined ? undefined : excel?.images[id - 1];
|
|
45
|
+
if (picture) {
|
|
46
|
+
const formula = child(cell, "f");
|
|
47
|
+
if (!graph || formula || cell.hasAttribute("cm") || cell.getAttribute("t") !== "e" || child(cell, "v")?.textContent !== "#VALUE!") return { picture };
|
|
48
|
+
let asset = resources.get(picture.asset);
|
|
49
|
+
if (!asset) {
|
|
50
|
+
asset = createWorkbookImageAsset("xlsx-image-" + (resources.size + 1), picture.asset.bytes());
|
|
51
|
+
resources.set(picture.asset, asset);
|
|
52
|
+
}
|
|
53
|
+
return { picture, input: { kind: "image", assetId: asset.id, ...(picture.alt && { alt: picture.alt }) } };
|
|
54
|
+
}
|
|
55
|
+
if (!pictures?.size) return undefined;
|
|
56
|
+
const formula = child(cell, "f");
|
|
57
|
+
const type = formula?.getAttribute("t");
|
|
58
|
+
if (formula?.namespaceURI !== spreadNs || !formula.textContent || (type && type !== "normal")) return undefined;
|
|
59
|
+
const match = wpsFormula.exec(formula.textContent);
|
|
60
|
+
const image = match?.[1] ? pictures.get(match[1]) : undefined;
|
|
61
|
+
return image ? { picture: image } : undefined;
|
|
62
|
+
},
|
|
63
|
+
/** @returns Recorded portable media, one asset per source raster. */
|
|
64
|
+
assets() { return [...resources.values()]; }
|
|
65
|
+
};
|
|
66
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { readRelationships } from "../opc/relationships";
|
|
2
|
+
import { parsePart } from "../opc/xml";
|
|
3
|
+
|
|
4
|
+
/** @param path - OPC relationships part. @returns The originating owner's normalized archive path. */
|
|
5
|
+
function relationshipOwner(path: string): string | undefined {
|
|
6
|
+
if (path === "_rels/.rels") return "";
|
|
7
|
+
const match = /^(.*\/)?_rels\/([^/]+)\.rels$/u.exec(path);
|
|
8
|
+
return match ? (match[1] ?? "") + match[2] : undefined;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** @param parts - Retained archive. @param ignored - Relationship part removed by the caller.
|
|
12
|
+
* @returns Every remaining internal relationship target, or undefined if the archive cannot be analyzed safely. */
|
|
13
|
+
export function retainedXlsxRelationshipTargets(parts: Readonly<Record<string, Uint8Array>>, ignored?: string): ReadonlySet<string> | undefined {
|
|
14
|
+
const result = new Set<string>();
|
|
15
|
+
try {
|
|
16
|
+
for (const path in parts) {
|
|
17
|
+
if (path === ignored || !path.endsWith(".rels")) continue;
|
|
18
|
+
const owner = relationshipOwner(path);
|
|
19
|
+
if (owner === undefined) continue;
|
|
20
|
+
for (const { path: target } of readRelationships(parsePart(parts[path], path), owner).values()) {
|
|
21
|
+
if (target !== null) result.add(target);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
} catch { return undefined; }
|
|
25
|
+
return result;
|
|
26
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import type { WorkbookCellImage, WorkbookCellImageAsset, WorkbookImageCell, WorkbookRasterAsset } from "@quirekit/workbook";
|
|
3
|
+
import type { PackageRelationship } from "../opc/types";
|
|
4
|
+
|
|
5
|
+
/** Reads only local raster assets from a resolved image relationship. */
|
|
6
|
+
export type XlsxImageAssetReader = (relation: PackageRelationship | undefined) => WorkbookCellImageAsset | undefined;
|
|
7
|
+
|
|
8
|
+
/** Read-only workbook presentation or a fully modeled image input. */
|
|
9
|
+
export type XlsxResolvedCellImage = { readonly picture: WorkbookCellImage; readonly input?: WorkbookImageCell | undefined };
|
|
10
|
+
|
|
11
|
+
/** Resolves a source cell through its native workbook-level image data. */
|
|
12
|
+
export type XlsxCellImageResolver = (cell: Element) => XlsxResolvedCellImage | undefined;
|
|
13
|
+
|
|
14
|
+
/** Standalone image parts whose original native records can be regenerated. */
|
|
15
|
+
export interface XlsxOwnedImageGraph {
|
|
16
|
+
/** Exclusively owned metadata and rich-value relationship targets. */
|
|
17
|
+
readonly roles: readonly PackageRelationship[];
|
|
18
|
+
/** Rich-value relation list, which owns the media relationships. */
|
|
19
|
+
readonly relationPath: string;
|
|
20
|
+
/** Raster targets that can be removed if no other part references them. */
|
|
21
|
+
readonly media: readonly string[];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Parsed Excel image value records and their optional write authority. */
|
|
25
|
+
export interface XlsxExcelImages {
|
|
26
|
+
/** Lookup by zero-based value metadata index. */
|
|
27
|
+
readonly images: readonly (WorkbookCellImage | undefined)[];
|
|
28
|
+
/** Complete supported graph, when no unsupported data would be rewritten. */
|
|
29
|
+
readonly owned?: XlsxOwnedImageGraph | undefined;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** One source workbook's image reading and portable resource capture. */
|
|
33
|
+
export interface XlsxCellImagesImport {
|
|
34
|
+
/** Original roles and paths if the whole image graph is editable. */
|
|
35
|
+
readonly graph?: XlsxOwnedImageGraph | undefined;
|
|
36
|
+
/** Resolves original records at the observed worksheet cell. */
|
|
37
|
+
readonly resolve: XlsxCellImageResolver;
|
|
38
|
+
/** @returns Encoded resources for image cells imported so far. */
|
|
39
|
+
assets(): readonly WorkbookRasterAsset[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Native rich value entry for one image and its accessibility description. */
|
|
43
|
+
export interface XlsxCellImageValue {
|
|
44
|
+
/** Zero-based position in the XML relationship list. */
|
|
45
|
+
readonly media: number;
|
|
46
|
+
/** Optional alternative text preserved independently of the binary asset. */
|
|
47
|
+
readonly alt?: string | undefined;
|
|
48
|
+
}
|
package/src/image/wps.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { WorkbookCellImage } from "@quirekit/workbook";
|
|
2
|
+
import { readRelationships, relationshipsPath } from "../opc/relationships";
|
|
3
|
+
import { child, children, parsePart, relationshipNs, rootOf } from "../opc/xml";
|
|
4
|
+
import type { XlsxImageAssetReader } from "./types";
|
|
5
|
+
|
|
6
|
+
const wpsCellImagesNs = "http://www.wps.cn/officeDocument/2017/etCustomData";
|
|
7
|
+
const spreadsheetDrawingNs = "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing";
|
|
8
|
+
const drawingNs = "http://schemas.openxmlformats.org/drawingml/2006/main";
|
|
9
|
+
|
|
10
|
+
/** Relationship from a workbook to its WPS cell image registry. */
|
|
11
|
+
export const wpsCellImageRole = "http://www.wps.cn/officeDocument/2020/cellImage";
|
|
12
|
+
|
|
13
|
+
/** @param parts - Native package entries. @param owner - Resolved image registry path.
|
|
14
|
+
* @param readAsset - Local raster resolver. @returns Unambiguous package-local images keyed by DISPIMG identifier. */
|
|
15
|
+
export function readWpsCellImages(parts: Readonly<Record<string, Uint8Array>>, owner: string,
|
|
16
|
+
readAsset: XlsxImageAssetReader): ReadonlyMap<string, WorkbookCellImage> {
|
|
17
|
+
const root = rootOf(parsePart(parts[owner], owner), wpsCellImagesNs, "cellImages");
|
|
18
|
+
const result = new Map<string, WorkbookCellImage>();
|
|
19
|
+
const entries = children(root, "cellImage");
|
|
20
|
+
if (!entries.length) return result;
|
|
21
|
+
|
|
22
|
+
const relsPath = relationshipsPath(owner);
|
|
23
|
+
const relationships = readRelationships(parsePart(parts[relsPath], relsPath), owner);
|
|
24
|
+
const seen = new Set<string>();
|
|
25
|
+
for (const entry of entries) {
|
|
26
|
+
const picture = entry.namespaceURI === wpsCellImagesNs && child(entry, "pic");
|
|
27
|
+
if (!picture || picture.namespaceURI !== spreadsheetDrawingNs) continue;
|
|
28
|
+
const identification = child(picture, "nvPicPr");
|
|
29
|
+
const properties = identification && child(identification, "cNvPr");
|
|
30
|
+
const id = properties?.namespaceURI === spreadsheetDrawingNs && properties.getAttribute("name");
|
|
31
|
+
if (!id) continue;
|
|
32
|
+
if (seen.has(id)) { result.delete(id); continue; }
|
|
33
|
+
seen.add(id);
|
|
34
|
+
const fill = child(picture, "blipFill");
|
|
35
|
+
const blip = fill && child(fill, "blip");
|
|
36
|
+
const relation = blip?.namespaceURI === drawingNs && blip.getAttributeNS(relationshipNs, "embed");
|
|
37
|
+
const asset = relation ? readAsset(relationships.get(relation)) : undefined;
|
|
38
|
+
if (!asset) continue;
|
|
39
|
+
const alt = properties.getAttribute("descr") || undefined;
|
|
40
|
+
result.set(id, Object.freeze({ asset, ...(alt && { alt }) }));
|
|
41
|
+
}
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import { createWorkbookImageAsset, parseWorkbookRange, type WorkbookSnapshot } from "@quirekit/workbook";
|
|
5
|
+
import { strFromU8, unzipSync } from "fflate";
|
|
6
|
+
import { expect, test } from "vitest";
|
|
7
|
+
import { createXlsx, openXlsx } from "../index";
|
|
8
|
+
|
|
9
|
+
const fixture = unzipSync(Uint8Array.from(readFileSync(new URL("../../test/fixtures/excel-cell-images.xlsx", import.meta.url))));
|
|
10
|
+
const png = createWorkbookImageAsset("picture", fixture["xl/media/image1.png"]!);
|
|
11
|
+
const jpeg = createWorkbookImageAsset("picture2", fixture["xl/media/image2.jpeg"]!);
|
|
12
|
+
|
|
13
|
+
test("exports shared PNG and JPEG as native XLSX values and saves later edits using consistent ordinals", () => {
|
|
14
|
+
const initial: WorkbookSnapshot = { version: 1, revision: 0, id: "products", name: "图片", imageAssets: [png, jpeg],
|
|
15
|
+
sheets: [{ id: "sheet", name: "商品", validations: [{ range: parseWorkbookRange("sheet", "B2:B1048576"),
|
|
16
|
+
definition: { type: "image", allowBlank: true, alert: { level: "stop" } } }], cells: [
|
|
17
|
+
{ row: 0, column: 1, input: { kind: "value", value: "照片" } },
|
|
18
|
+
{ row: 1, column: 1, input: { kind: "image", assetId: png.id, alt: "商品 A" } },
|
|
19
|
+
{ row: 2, column: 1, input: { kind: "image", assetId: png.id, alt: "商品 B & <图>" } },
|
|
20
|
+
{ row: 3, column: 1, input: { kind: "image", assetId: jpeg.id } }
|
|
21
|
+
] }] };
|
|
22
|
+
const bytes = createXlsx(initial);
|
|
23
|
+
const parts = unzipSync(bytes);
|
|
24
|
+
expect(Object.keys(parts).filter(path => path.startsWith("xl/media/"))).toHaveLength(2);
|
|
25
|
+
expect(strFromU8(parts["xl/worksheets/sheet1.xml"]!)).toContain('t="e" vm="2"><v>#VALUE!</v>');
|
|
26
|
+
expect(strFromU8(parts["xl/richData/rdrichvalue.xml"]!)).toContain("商品 B & <图>");
|
|
27
|
+
|
|
28
|
+
const file = openXlsx("图片", bytes);
|
|
29
|
+
expect(file.restrictions).toEqual([]);
|
|
30
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
31
|
+
const sheet = file.snapshot.sheets[0]!;
|
|
32
|
+
expect(sheet.validations?.[0]).toMatchObject({
|
|
33
|
+
range: { startRow: 1, endRow: 1_048_575, startColumn: 1, endColumn: 1 },
|
|
34
|
+
definition: { type: "image", allowBlank: true, alert: { level: "stop" } }
|
|
35
|
+
});
|
|
36
|
+
const [header, first, second, third] = sheet.cells;
|
|
37
|
+
expect(first?.input).toMatchObject({ kind: "image", assetId: "xlsx-image-1", alt: "商品 A" });
|
|
38
|
+
expect(second?.input).toMatchObject({ kind: "image", assetId: "xlsx-image-1", alt: "商品 B & <图>" });
|
|
39
|
+
expect(third?.input).toEqual({ kind: "image", assetId: "xlsx-image-2" });
|
|
40
|
+
expect(file.snapshot.imageAssets?.map(asset => asset.data)).toEqual([png.data, jpeg.data]);
|
|
41
|
+
|
|
42
|
+
const changed = file.write({ ...file.snapshot, sheets: [{ ...sheet, cells: [header!, { ...third!, row: 1 }, second!] }] });
|
|
43
|
+
const reread = openXlsx("修改", changed);
|
|
44
|
+
expect(reread.restrictions).toEqual([]);
|
|
45
|
+
expect(reread.snapshot.sheets[0]?.cells.slice(1).map(({ input }) => input)).toEqual([
|
|
46
|
+
{ kind: "image", assetId: "xlsx-image-1" }, { kind: "image", assetId: "xlsx-image-2", alt: "商品 B & <图>" }
|
|
47
|
+
]);
|
|
48
|
+
expect(reread.snapshot.imageAssets?.map(asset => asset.data)).toEqual([jpeg.data, png.data]);
|
|
49
|
+
|
|
50
|
+
const cleared = file.write({ ...file.snapshot, imageAssets: [], sheets: [{ ...sheet, cells: [header!] }] });
|
|
51
|
+
expect(Object.keys(unzipSync(cleared)).filter(path => /richData|metadata\.xml|xl\/media\//u.test(path))).toEqual([]);
|
|
52
|
+
expect(openXlsx("清空", cleared).restrictions).toEqual([]);
|
|
53
|
+
});
|