@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,22 @@
|
|
|
1
|
+
import { formatWorkbookColumn, indexWorkbookValidationRules, workbookTextValidationHref, type WorkbookSheet } from "@quirekit/workbook";
|
|
2
|
+
import type { XlsxTextColumnLink } from "./types";
|
|
3
|
+
|
|
4
|
+
/** Excel's native hyperlink limit per worksheet. */
|
|
5
|
+
const maximumLinks = 65_530;
|
|
6
|
+
|
|
7
|
+
/** @param sheet - Sparse saved worksheet. @returns Literal links in stored cell order within the native limit. */
|
|
8
|
+
export function xlsxTextColumnLinks(sheet: Pick<WorkbookSheet, "id" | "cells" | "validations">): readonly XlsxTextColumnLink[] {
|
|
9
|
+
const rules = sheet.validations?.filter(rule => rule.definition.type === "email" || rule.definition.type === "url");
|
|
10
|
+
if (!rules?.length) return [];
|
|
11
|
+
const ruleAt = indexWorkbookValidationRules(rules);
|
|
12
|
+
const links: XlsxTextColumnLink[] = [];
|
|
13
|
+
for (const { row, column, input } of sheet.cells) {
|
|
14
|
+
if (input.kind !== "value" || typeof input.value !== "string") continue;
|
|
15
|
+
const type = ruleAt(sheet.id, row, column)?.type;
|
|
16
|
+
if (type !== "email" && type !== "url") continue;
|
|
17
|
+
const href = workbookTextValidationHref(type, input.value);
|
|
18
|
+
if (href) links.push({ ref: formatWorkbookColumn(column) + (row + 1), display: input.value, type, href });
|
|
19
|
+
if (links.length === maximumLinks) break;
|
|
20
|
+
}
|
|
21
|
+
return links;
|
|
22
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { copyWorkbookHyperlink, formatWorkbookRange, normalizeWorkbookHyperlinkHref, parseWorkbookRange, workbookHyperlinkLimit,
|
|
3
|
+
type WorkbookHyperlinkTarget, type WorkbookSheet, type WorkbookStoredHyperlink, type workbookDefinedNameLookup } from "@quirekit/workbook";
|
|
4
|
+
import { hyperlinkRelationship, readRelationships, relationshipsPath } from "../../opc/relationships";
|
|
5
|
+
import { hasKnownAttributes, hasKnownChildren } from "../../opc/shape";
|
|
6
|
+
import type { PackageRelationship } from "../../opc/types";
|
|
7
|
+
import { children, parsePart, relationshipNs, spreadNs } from "../../opc/xml";
|
|
8
|
+
import { decodeXlsxText } from "../text";
|
|
9
|
+
import { xlsxTextColumnLinks } from "./model";
|
|
10
|
+
import { readXlsxHyperlinkLocation } from "./location";
|
|
11
|
+
import type { XlsxHyperlinkOwnership } from "./types";
|
|
12
|
+
|
|
13
|
+
/** @param relation - Native sheet relationship. @param location - Optional bookmark in a web resource.
|
|
14
|
+
* @returns Validated web or mailto destination. */
|
|
15
|
+
function externalTarget(relation: PackageRelationship | undefined, location: string): WorkbookHyperlinkTarget | undefined {
|
|
16
|
+
if (!relation || relation.type !== hyperlinkRelationship || relation.path !== null
|
|
17
|
+
|| !hasKnownAttributes(relation.element, ["Id", "Type", "Target", "TargetMode"]) || !hasKnownChildren(relation.element, [])) return;
|
|
18
|
+
let href = relation.element.getAttribute("Target") ?? "";
|
|
19
|
+
if (!/^(?:https?:\/\/|mailto:)/iu.test(href)) return;
|
|
20
|
+
if (location) {
|
|
21
|
+
const web = new URL(href);
|
|
22
|
+
if (web.protocol !== "https:" && web.protocol !== "http:") return;
|
|
23
|
+
web.hash = location;
|
|
24
|
+
href = web.href;
|
|
25
|
+
}
|
|
26
|
+
const safe = normalizeWorkbookHyperlinkHref(href);
|
|
27
|
+
return safe && { kind: "external", href: safe } || undefined;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** @param worksheet - Retained native worksheet. @param sheet - Decoded cells and rules. @param path - Worksheet member.
|
|
31
|
+
* @param parts - Original package. @param names - Workbook worksheet names and stable IDs. @param definedNames - Scoped native names.
|
|
32
|
+
* @returns Explicit placements and relationship ownership when every native link is understood. */
|
|
33
|
+
export function readXlsxHyperlinks(worksheet: Element, sheet: Pick<WorkbookSheet, "id" | "cells" | "validations">, path: string,
|
|
34
|
+
parts: Readonly<Record<string, Uint8Array>>, names: ReadonlyMap<string, string>,
|
|
35
|
+
definedNames: ReturnType<typeof workbookDefinedNameLookup>): XlsxHyperlinkOwnership | undefined {
|
|
36
|
+
const groups = children(worksheet, "hyperlinks"), group = groups[0];
|
|
37
|
+
if (!group || group.namespaceURI !== spreadNs || groups.length !== 1 || !hasKnownAttributes(group, [])) return;
|
|
38
|
+
const owner = relationshipsPath(path);
|
|
39
|
+
const entries = children(group);
|
|
40
|
+
if (entries.length > workbookHyperlinkLimit) return;
|
|
41
|
+
try {
|
|
42
|
+
const relationships = parts[owner] ? readRelationships(parsePart(parts[owner], owner), path) : new Map<string, PackageRelationship>();
|
|
43
|
+
const expected = new Map(xlsxTextColumnLinks(sheet).map(link => [link.ref, link]));
|
|
44
|
+
const ids = new Set<string>(), used = new Set<string>();
|
|
45
|
+
const hyperlinks: WorkbookStoredHyperlink[] = [];
|
|
46
|
+
for (const entry of entries) {
|
|
47
|
+
if (entry.namespaceURI !== spreadNs || entry.localName !== "hyperlink" || !hasKnownChildren(entry, [])
|
|
48
|
+
|| !hasKnownAttributes(entry, ["ref", "display", "location", "tooltip"], true)) return;
|
|
49
|
+
const range = parseWorkbookRange(sheet.id, entry.getAttribute("ref") ?? "");
|
|
50
|
+
if (range.startRow !== range.endRow || range.startColumn !== range.endColumn) return;
|
|
51
|
+
const ref = formatWorkbookRange(range);
|
|
52
|
+
if (used.has(ref)) return;
|
|
53
|
+
const id = entry.getAttributeNS(relationshipNs, "id");
|
|
54
|
+
const location = decodeXlsxText(entry.getAttribute("location") ?? "");
|
|
55
|
+
const target = id ? externalTarget(relationships.get(id), location) : readXlsxHyperlinkLocation(location, sheet.id, names, definedNames);
|
|
56
|
+
if (!target) return;
|
|
57
|
+
const display = entry.hasAttribute("display") ? decodeXlsxText(entry.getAttribute("display") ?? "") : undefined;
|
|
58
|
+
const tooltip = entry.hasAttribute("tooltip") ? decodeXlsxText(entry.getAttribute("tooltip") ?? "") : undefined;
|
|
59
|
+
const derived = expected.get(ref);
|
|
60
|
+
// Native text columns declare the echoed label. An explicit link without it keeps independent ownership.
|
|
61
|
+
if (target.kind !== "external" || !derived || target.href !== derived.href || display !== derived.display || tooltip !== undefined || location) {
|
|
62
|
+
hyperlinks.push({ row: range.startRow, column: range.startColumn, hyperlink: copyWorkbookHyperlink({ target, display, tooltip }) });
|
|
63
|
+
}
|
|
64
|
+
used.add(ref);
|
|
65
|
+
if (id) ids.add(id);
|
|
66
|
+
}
|
|
67
|
+
hyperlinks.sort((a, b) => a.row - b.row || a.column - b.column);
|
|
68
|
+
return { ids, hyperlinks };
|
|
69
|
+
} catch { /* Opaque source records retain their original worksheet and relationships. */ }
|
|
70
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { WorkbookStoredHyperlink } from "@quirekit/workbook";
|
|
2
|
+
|
|
3
|
+
/** Native link derived from one stored string and its worksheet validation rule. */
|
|
4
|
+
export interface XlsxTextColumnLink {
|
|
5
|
+
/** Single-cell A1 reference. */
|
|
6
|
+
readonly ref: string;
|
|
7
|
+
/** Original authored label. */
|
|
8
|
+
readonly display: string;
|
|
9
|
+
/** Email or web rule that owns this link. */
|
|
10
|
+
readonly type: "email" | "url";
|
|
11
|
+
/** Validated native destination. */
|
|
12
|
+
readonly href: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Complete native link group with independently managed relationship IDs. */
|
|
16
|
+
export interface XlsxHyperlinkOwnership {
|
|
17
|
+
/** Existing managed external relationships, empty for an internal-only group. */
|
|
18
|
+
readonly ids: ReadonlySet<string>;
|
|
19
|
+
/** Explicit links whose targets cannot be inferred solely from a column rule. */
|
|
20
|
+
readonly hyperlinks: readonly WorkbookStoredHyperlink[];
|
|
21
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
|
|
2
|
+
import { openWorkbook, parseWorkbookRange, type WorkbookSession, type WorkbookSnapshot } from "@quirekit/workbook";
|
|
3
|
+
import { expect, it } from "vitest";
|
|
4
|
+
import { createXlsx, openXlsx } from "../../index";
|
|
5
|
+
|
|
6
|
+
const id = "text-columns";
|
|
7
|
+
const sheetPath = "xl/worksheets/sheet1.xml";
|
|
8
|
+
const relsPath = "xl/worksheets/_rels/sheet1.xml.rels";
|
|
9
|
+
const range = (sheetId: string, address: string) => parseWorkbookRange(sheetId, address);
|
|
10
|
+
const snapshot: WorkbookSnapshot = {
|
|
11
|
+
version: 1, revision: 0, id, name: "Text columns", sheets: [{ id, name: "Contacts", cells: [
|
|
12
|
+
{ row: 1, column: 0, input: { kind: "value", value: "probe+sheet@example.test" } },
|
|
13
|
+
{ row: 1, column: 1, input: { kind: "value", value: "example.test/path?x=2&y=3" } },
|
|
14
|
+
{ row: 1, column: 2, input: { kind: "value", value: "+8619900000000" } },
|
|
15
|
+
{ row: 1, column: 3, input: { kind: "value", value: "110000200001019996" } },
|
|
16
|
+
{ row: 1, column: 4, input: { kind: "value", value: 40 } }
|
|
17
|
+
], validations: [
|
|
18
|
+
{ range: range(id, "A2:A1048576"), definition: { type: "email" } },
|
|
19
|
+
{ range: range(id, "B2:B1048576"), definition: { type: "url" } },
|
|
20
|
+
{ range: range(id, "C2:C1048576"), definition: { type: "mobile" } },
|
|
21
|
+
{ range: range(id, "D2:D1048576"), definition: { type: "citizenId" } }
|
|
22
|
+
] }]
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** @param session - Live workbook. @param name - Canonical command. @param at - Its worksheet range.
|
|
26
|
+
* @param params - Command parameters. @returns Its publication receipt. */
|
|
27
|
+
async function commit(session: WorkbookSession, name: string, at: ReturnType<typeof range>, params: unknown) {
|
|
28
|
+
return session.commit(session.prepare({ operationId: name + session.revision, baseRevision: session.revision,
|
|
29
|
+
commands: [{ name, target: at, params }] }).id);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
it("exports typed text and native links with a separate chart in the same worksheet", async () => {
|
|
33
|
+
const workbook = await openWorkbook(snapshot);
|
|
34
|
+
try {
|
|
35
|
+
await commit(workbook, "createChart", range(id, "E4"), {
|
|
36
|
+
type: "column", binding: { categories: { sheetId: id, range: "A2" }, series: [{ values: { sheetId: id, range: "E2" } }] }
|
|
37
|
+
});
|
|
38
|
+
const bytes = createXlsx(workbook.snapshot());
|
|
39
|
+
const raw = unzipSync(bytes), xml = strFromU8(raw[sheetPath]!);
|
|
40
|
+
const relations = strFromU8(raw[relsPath]!);
|
|
41
|
+
for (const marker of ["Email", "Web", "Tel", "ID"]) expect(xml).toContain('IF(TRUE,TRUE,"' + marker + '")');
|
|
42
|
+
expect(xml).toContain('sqref="D2:D1048576"');
|
|
43
|
+
expect(xml).toContain("110000200001019996");
|
|
44
|
+
expect(xml.match(/<c /gu)).toHaveLength(5);
|
|
45
|
+
expect(relations).toContain('Target="mailto:probe%2Bsheet@example.test"');
|
|
46
|
+
expect(relations).toContain('Target="https://example.test/path?x=2&y=3"');
|
|
47
|
+
expect(relations).toContain("/drawing");
|
|
48
|
+
|
|
49
|
+
const source = openXlsx("Text columns", bytes);
|
|
50
|
+
const sid = source.snapshot.sheets[0]!.id;
|
|
51
|
+
expect(source.restrictions).toEqual([]);
|
|
52
|
+
expect(source.axisRestrictions.size).toBe(0);
|
|
53
|
+
expect(source.sortRestrictions.size).toBe(0);
|
|
54
|
+
expect(source.snapshot.charts).toHaveLength(1);
|
|
55
|
+
expect(source.snapshot.sheets[0]?.validations?.map(rule => rule.definition.type)).toEqual(["email", "url", "mobile", "citizenId"]);
|
|
56
|
+
expect(source.snapshot.sheets[0]?.cells).toEqual(snapshot.sheets[0]?.cells);
|
|
57
|
+
expect(source.write(source.snapshot)).toEqual(bytes);
|
|
58
|
+
const next = await openWorkbook(source.snapshot, { appearance: source.appearance });
|
|
59
|
+
try {
|
|
60
|
+
await commit(next, "insertRows", range(sid, "A2"), {});
|
|
61
|
+
const moved = unzipSync(source.write(next.snapshot()));
|
|
62
|
+
expect(strFromU8(moved[sheetPath]!)).toContain('ref="A3"');
|
|
63
|
+
expect(strFromU8(moved[sheetPath]!)).toContain('sqref="A3:A1048576"');
|
|
64
|
+
|
|
65
|
+
const copy = "00000000-0000-4000-8000-000000000042";
|
|
66
|
+
await commit(next, "duplicateWorksheet", range(sid, "A1"), { name: "Contacts copy", newSheetId: copy });
|
|
67
|
+
await commit(next, "clearDataValidation", range(sid, "B3:B1048576"), {});
|
|
68
|
+
const updated = source.write(next.snapshot());
|
|
69
|
+
const files = unzipSync(updated);
|
|
70
|
+
expect(strFromU8(files[relsPath]!)).not.toContain("https://example.test");
|
|
71
|
+
expect(strFromU8(files[relsPath]!)).toContain("/drawing");
|
|
72
|
+
expect(strFromU8(files["xl/worksheets/_rels/sheet2.xml.rels"]!)).toContain("https://example.test");
|
|
73
|
+
expect(openXlsx("Text columns", updated).restrictions).toEqual([]);
|
|
74
|
+
|
|
75
|
+
const originalChart = next.charts().find(chart => chart.anchor.sheetId === sid)!;
|
|
76
|
+
await commit(next, "deleteChart", range(sid, "A1"), { id: originalChart.id });
|
|
77
|
+
const after = unzipSync(source.write(next.snapshot()));
|
|
78
|
+
expect(strFromU8(after[relsPath]!)).toContain("mailto:");
|
|
79
|
+
expect(strFromU8(after[relsPath]!)).not.toContain("/drawing");
|
|
80
|
+
} finally { await next.close(); }
|
|
81
|
+
} finally { await workbook.close(); }
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it("imports an independent native destination and retains an opaque file link byte for byte", () => {
|
|
85
|
+
const parts = unzipSync(createXlsx(snapshot));
|
|
86
|
+
const relations = strFromU8(parts[relsPath]!);
|
|
87
|
+
parts[relsPath] = strToU8(relations.replace("https://example.test", "https://separate.example.test"));
|
|
88
|
+
const bytes = zipSync(parts);
|
|
89
|
+
const source = openXlsx("Independent links", bytes);
|
|
90
|
+
expect(source.restrictions).toEqual([]);
|
|
91
|
+
expect(source.snapshot.sheets[0]?.hyperlinks).toEqual([{
|
|
92
|
+
row: 1, column: 1, hyperlink: {
|
|
93
|
+
display: "example.test/path?x=2&y=3",
|
|
94
|
+
target: { kind: "external", href: "https://separate.example.test/path?x=2&y=3" }
|
|
95
|
+
}
|
|
96
|
+
}]);
|
|
97
|
+
expect(source.snapshot.sheets[0]?.validations?.[1]?.definition.type).toBe("url");
|
|
98
|
+
expect(source.write(source.snapshot)).toEqual(bytes);
|
|
99
|
+
|
|
100
|
+
parts[relsPath] = strToU8(relations.replace("https://example.test", "file:///external/ledger.xlsx"));
|
|
101
|
+
const opaque = zipSync(parts);
|
|
102
|
+
const retained = openXlsx("Opaque link", opaque);
|
|
103
|
+
expect(retained.restrictions).toContain("未支持的原生超链接");
|
|
104
|
+
expect(retained.write(retained.snapshot)).toEqual(opaque);
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
it("round-trips authored hyperlinks, moves their targets and drops only their own relationships", async () => {
|
|
108
|
+
const reports = "reports";
|
|
109
|
+
const previousName = "Lin's Report";
|
|
110
|
+
const workspace = await openWorkbook({ ...snapshot, sheets: [...snapshot.sheets, { id: reports, name: previousName, cells: [] }] });
|
|
111
|
+
try {
|
|
112
|
+
await commit(workspace, "setCellHyperlink", range(id, "E2"), {
|
|
113
|
+
target: { kind: "external", href: "https://example.test/doc?x=1&y=2#total" }, tooltip: "Notes & totals"
|
|
114
|
+
});
|
|
115
|
+
await commit(workspace, "setCellHyperlink", range(id, "F3"), {
|
|
116
|
+
target: { kind: "worksheet", sheetId: reports, range: "$B$2:$C$3" }, text: "Open report"
|
|
117
|
+
});
|
|
118
|
+
const bytes = createXlsx(workspace.snapshot()), parts = unzipSync(bytes);
|
|
119
|
+
const native = strFromU8(parts[sheetPath]!);
|
|
120
|
+
expect(native).toContain(`location="'Lin''s Report'!B2:C3"`);
|
|
121
|
+
expect(native).toContain('tooltip="Notes & totals"');
|
|
122
|
+
expect(strFromU8(parts[relsPath]!)).toContain('Target="https://example.test/doc?x=1&y=2#total"');
|
|
123
|
+
const file = openXlsx("Authored links", bytes);
|
|
124
|
+
expect(file.restrictions).toEqual([]);
|
|
125
|
+
const [owner, report] = file.snapshot.sheets;
|
|
126
|
+
const editor = await openWorkbook(file.snapshot, { appearance: file.appearance });
|
|
127
|
+
try {
|
|
128
|
+
const destination = { sheetId: owner!.id, row: 2, column: 5 };
|
|
129
|
+
expect(editor.readHyperlink(destination)).toEqual({ target: { kind: "worksheet", range: range(report!.id, "B2:C3") } });
|
|
130
|
+
expect(editor.readCell({ sheetId: owner!.id, row: 1, column: 4 })).toMatchObject({
|
|
131
|
+
input: { kind: "value", value: 40 },
|
|
132
|
+
hyperlink: { target: { kind: "external", href: "https://example.test/doc?x=1&y=2#total" }, tooltip: "Notes & totals" }
|
|
133
|
+
});
|
|
134
|
+
await commit(editor, "renameWorksheet", range(report!.id, "A1"), { name: "汇总" });
|
|
135
|
+
await commit(editor, "insertRows", range(report!.id, "A1"), {});
|
|
136
|
+
await commit(editor, "removeCellHyperlink", range(owner!.id, "E2"), {});
|
|
137
|
+
const changed = file.write(editor.snapshot()), next = unzipSync(changed);
|
|
138
|
+
expect(strFromU8(next[sheetPath]!)).toContain('location="汇总!B3:C4"');
|
|
139
|
+
expect(strFromU8(next[relsPath]!)).not.toContain("/doc");
|
|
140
|
+
expect(strFromU8(next[relsPath]!)).toContain("mailto:");
|
|
141
|
+
const decoded = openXlsx("Moved link", changed);
|
|
142
|
+
expect(decoded.snapshot.sheets[0]?.hyperlinks).toHaveLength(1);
|
|
143
|
+
expect(decoded.snapshot.sheets[0]?.cells.find(cell => cell.row === 1 && cell.column === 4)?.input).toEqual({ kind: "value", value: 40 });
|
|
144
|
+
} finally { await editor.close(); }
|
|
145
|
+
} finally { await workspace.close(); }
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it("removes an empty relationship part even when its source used indentation", async () => {
|
|
149
|
+
const parts = unzipSync(createXlsx(snapshot));
|
|
150
|
+
parts[relsPath] = strToU8(strFromU8(parts[relsPath]!).replaceAll("><", ">\n<"));
|
|
151
|
+
const file = openXlsx("Indented links", zipSync(parts));
|
|
152
|
+
const sid = file.snapshot.sheets[0]!.id;
|
|
153
|
+
const workbook = await openWorkbook(file.snapshot);
|
|
154
|
+
try {
|
|
155
|
+
await commit(workbook, "clearDataValidation", range(sid, "A2:B1048576"), {});
|
|
156
|
+
const bytes = file.write(workbook.snapshot());
|
|
157
|
+
expect(unzipSync(bytes)[relsPath]).toBeUndefined();
|
|
158
|
+
expect(openXlsx("Indented links", bytes).restrictions).toEqual([]);
|
|
159
|
+
} finally { await workbook.close(); }
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it("writes native workbook and worksheet name locations and updates them without editing link cells", async () => {
|
|
163
|
+
const report = "report";
|
|
164
|
+
const workbook = await openWorkbook({ ...snapshot, sheets: [...snapshot.sheets, { id: report, name: "Quarterly Report", cells: [] }] });
|
|
165
|
+
let bytes: Uint8Array;
|
|
166
|
+
try {
|
|
167
|
+
await commit(workbook, "defineWorkbookName", range(report, "B2:B4"), { id: "global-amounts", name: "Amounts" });
|
|
168
|
+
await commit(workbook, "defineWorkbookName", range(report, "D2:D4"), { id: "local-amounts", name: "Amounts", scopeSheetId: report });
|
|
169
|
+
await commit(workbook, "setCellHyperlink", range(id, "G2"), { target: { kind: "definedName", nameId: "global-amounts" } });
|
|
170
|
+
await commit(workbook, "setCellHyperlink", range(id, "G3"), { target: { kind: "definedName", nameId: "local-amounts" } });
|
|
171
|
+
bytes = createXlsx(workbook.snapshot());
|
|
172
|
+
} finally { await workbook.close(); }
|
|
173
|
+
|
|
174
|
+
const xml = strFromU8(unzipSync(bytes)[sheetPath]!);
|
|
175
|
+
expect(xml).toContain('ref="G2" location="Amounts"');
|
|
176
|
+
expect(xml).toContain(`ref="G3" location="'Quarterly Report'!Amounts"`);
|
|
177
|
+
const file = openXlsx("Named links", bytes);
|
|
178
|
+
expect(file.restrictions).toEqual([]);
|
|
179
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
180
|
+
const [owner, destination] = file.snapshot.sheets;
|
|
181
|
+
const globalName = file.snapshot.definedNames?.find(name => !name.scopeSheetId);
|
|
182
|
+
const localName = file.snapshot.definedNames?.find(name => name.scopeSheetId === destination!.id);
|
|
183
|
+
expect(globalName?.target).toEqual({ kind: "range", range: range(destination!.id, "B2:B4") });
|
|
184
|
+
expect(localName?.target).toEqual({ kind: "range", range: range(destination!.id, "D2:D4") });
|
|
185
|
+
expect(owner?.hyperlinks?.map(link => link.hyperlink.target)).toEqual([
|
|
186
|
+
{ kind: "definedName", nameId: globalName?.id }, { kind: "definedName", nameId: localName?.id }
|
|
187
|
+
]);
|
|
188
|
+
|
|
189
|
+
const reopen = await openWorkbook(file.snapshot, { appearance: file.appearance });
|
|
190
|
+
try {
|
|
191
|
+
await commit(reopen, "defineWorkbookName", range(destination!.id, "B2:B4"), { id: globalName!.id, name: "UpdatedAmounts" });
|
|
192
|
+
await commit(reopen, "renameWorksheet", range(destination!.id, "A1"), { name: "Lin's Report" });
|
|
193
|
+
const updated = file.write(reopen.snapshot());
|
|
194
|
+
const nextXml = strFromU8(unzipSync(updated)[sheetPath]!);
|
|
195
|
+
expect(nextXml).toContain('ref="G2" location="UpdatedAmounts"');
|
|
196
|
+
expect(nextXml).toContain(`ref="G3" location="'Lin''s Report'!Amounts"`);
|
|
197
|
+
const next = openXlsx("Renamed destinations", updated);
|
|
198
|
+
expect(next.restrictions).toEqual([]);
|
|
199
|
+
expect(next.snapshot.sheets[0]?.cells.filter(cell => cell.column === 6).map(cell => cell.input)).toEqual([
|
|
200
|
+
{ kind: "value", value: "Amounts" }, { kind: "value", value: "Amounts" }
|
|
201
|
+
]);
|
|
202
|
+
} finally { await reopen.close(); }
|
|
203
|
+
});
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { formatWorkbookColumn, workbookHyperlinkLimit, type WorkbookHyperlink, type WorkbookSheet } from "@quirekit/workbook";
|
|
3
|
+
import { editPartRelationships, hyperlinkRelationship } from "../../opc/relationships";
|
|
4
|
+
import { child, children, relationshipNs, spreadNs } from "../../opc/xml";
|
|
5
|
+
import { encodeXlsxText } from "../text";
|
|
6
|
+
import { xlsxTextColumnLinks } from "./model";
|
|
7
|
+
import { writeXlsxHyperlinkLocation } from "./location";
|
|
8
|
+
|
|
9
|
+
const afterHyperlinks = new Set([
|
|
10
|
+
"printOptions", "pageMargins", "pageSetup", "headerFooter", "rowBreaks", "colBreaks", "customProperties", "cellWatches",
|
|
11
|
+
"ignoredErrors", "smartTags", "drawing", "legacyDrawing", "legacyDrawingHF", "picture", "oleObjects", "controls",
|
|
12
|
+
"webPublishItems", "tableParts", "extLst"
|
|
13
|
+
]);
|
|
14
|
+
|
|
15
|
+
/** @param worksheet - Mutable native worksheet. @param path - Its OPC member. @param parts - Staged archive.
|
|
16
|
+
* @param sheet - Committed inputs, rules and explicit links. @param previous - Managed relationships in the source worksheet.
|
|
17
|
+
* @param names - Current sheet names for internal targets. @param namedLocations - Current defined-name link locations. */
|
|
18
|
+
export function writeXlsxHyperlinks(worksheet: Element, path: string, parts: Record<string, Uint8Array>, sheet: WorkbookSheet,
|
|
19
|
+
previous: ReadonlySet<string> | undefined, names: ReadonlyMap<string, string>, namedLocations: ReadonlyMap<string, string>): void {
|
|
20
|
+
const original = child(worksheet, "hyperlinks");
|
|
21
|
+
if (original && !previous) return;
|
|
22
|
+
const links = new Map<string, WorkbookHyperlink>((sheet.hyperlinks ?? []).map(({ row, column, hyperlink }) =>
|
|
23
|
+
[formatWorkbookColumn(column) + (row + 1), hyperlink]));
|
|
24
|
+
if (links.size > workbookHyperlinkLimit) throw new Error("工作表的原生超链接超过数量限制。");
|
|
25
|
+
if (links.size < workbookHyperlinkLimit) for (const link of xlsxTextColumnLinks(sheet)) {
|
|
26
|
+
if (!links.has(link.ref)) links.set(link.ref, { target: { kind: "external", href: link.href }, display: link.display });
|
|
27
|
+
if (links.size === workbookHyperlinkLimit) break;
|
|
28
|
+
}
|
|
29
|
+
if (!original && !links.size) return;
|
|
30
|
+
const relationships = editPartRelationships(parts, path);
|
|
31
|
+
for (const id of previous ?? []) relationships.remove(id);
|
|
32
|
+
if (original) worksheet.removeChild(original);
|
|
33
|
+
if (links.size) {
|
|
34
|
+
const document = worksheet.ownerDocument!;
|
|
35
|
+
const group = document.createElementNS(spreadNs, "hyperlinks");
|
|
36
|
+
for (const [ref, { target, display, tooltip }] of links) {
|
|
37
|
+
const node = document.createElementNS(spreadNs, "hyperlink");
|
|
38
|
+
node.setAttribute("ref", ref);
|
|
39
|
+
if (display !== undefined) node.setAttribute("display", encodeXlsxText(display));
|
|
40
|
+
if (tooltip !== undefined) node.setAttribute("tooltip", encodeXlsxText(tooltip));
|
|
41
|
+
if (target.kind === "external") {
|
|
42
|
+
const id = relationships.add(hyperlinkRelationship, target.href, true);
|
|
43
|
+
node.setAttributeNS(relationshipNs, "r:id", id);
|
|
44
|
+
} else node.setAttribute("location", encodeXlsxText(writeXlsxHyperlinkLocation(target, names, namedLocations)));
|
|
45
|
+
group.appendChild(node);
|
|
46
|
+
}
|
|
47
|
+
const successor = children(worksheet).find(node => afterHyperlinks.has(node.localName ?? ""));
|
|
48
|
+
worksheet.insertBefore(group, successor ?? null);
|
|
49
|
+
}
|
|
50
|
+
relationships.write();
|
|
51
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
|
|
2
|
+
import { openWorkbook, parseWorkbookRange, type WorkbookSnapshot } from "@quirekit/workbook";
|
|
3
|
+
import { expect, it } from "vitest";
|
|
4
|
+
import { createXlsx, openXlsx } from "../index";
|
|
5
|
+
|
|
6
|
+
const target = parseWorkbookRange("report", "B2:D2");
|
|
7
|
+
const seed: WorkbookSnapshot = { version: 1, id: "book", revision: 0, name: "报表", sheets: [{
|
|
8
|
+
id: "report", name: "Report", cells: [{ row: 1, column: 1, input: { kind: "value", value: "报告标题" } }],
|
|
9
|
+
formats: [{ row: 1, column: 3, format: { background: "#DFE9F2" } }], merges: [target]
|
|
10
|
+
}, { id: "notes", name: "Notes", cells: [] }] };
|
|
11
|
+
const reportPath = "xl/worksheets/sheet1.xml";
|
|
12
|
+
|
|
13
|
+
it("preserves native merged input and styled covered cells while moving and splitting the range", async () => {
|
|
14
|
+
const bytes = createXlsx(seed);
|
|
15
|
+
const native = unzipSync(bytes);
|
|
16
|
+
expect(strFromU8(native[reportPath]!)).toContain('<mergeCells count="1"><mergeCell ref="B2:D2"/></mergeCells>');
|
|
17
|
+
const file = openXlsx("报表", bytes);
|
|
18
|
+
expect(file.restrictions).toEqual([]);
|
|
19
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
20
|
+
const session = await openWorkbook(file.snapshot, { appearance: file.appearance, axisRestrictions: file.axisRestrictions });
|
|
21
|
+
try {
|
|
22
|
+
const sheetId = session.worksheets()[0]!.id;
|
|
23
|
+
const moved = session.prepare({ operationId: "insert", baseRevision: session.revision,
|
|
24
|
+
commands: [{ name: "insertColumns", target: parseWorkbookRange(sheetId, "C1"), params: {} }] });
|
|
25
|
+
await session.commit(moved.id);
|
|
26
|
+
const saved = file.write(session.snapshot());
|
|
27
|
+
const after = openXlsx("报表", saved);
|
|
28
|
+
expect(after.restrictions).toEqual([]);
|
|
29
|
+
expect(after.snapshot.sheets[0]!.merges).toEqual([parseWorkbookRange(sheetId, "B2:E2")]);
|
|
30
|
+
expect(after.appearance.sheets.get(sheetId)?.cellStyles[1]?.[4]).toBeGreaterThan(0);
|
|
31
|
+
expect(unzipSync(saved)["xl/worksheets/sheet2.xml"]).toEqual(native["xl/worksheets/sheet2.xml"]);
|
|
32
|
+
|
|
33
|
+
const split = session.prepare({ operationId: "split", baseRevision: session.revision,
|
|
34
|
+
commands: [{ name: "unmergeCells", target: parseWorkbookRange(sheetId, "D2"), params: {} }] });
|
|
35
|
+
await session.commit(split.id);
|
|
36
|
+
const output = file.write(session.snapshot());
|
|
37
|
+
const reopened = openXlsx("报表", output);
|
|
38
|
+
expect(reopened.restrictions).toEqual([]);
|
|
39
|
+
expect(strFromU8(unzipSync(output)[reportPath]!)).not.toContain("mergeCells");
|
|
40
|
+
expect(reopened.snapshot.sheets[0]!.cells).toEqual(seed.sheets[0]!.cells);
|
|
41
|
+
} finally { await session.close(); }
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it("keeps malformed merge containers and covered cell inputs in the downloaded source", () => {
|
|
45
|
+
const parts = unzipSync(createXlsx(seed));
|
|
46
|
+
const source = strFromU8(parts[reportPath]!);
|
|
47
|
+
const variants = [
|
|
48
|
+
source.replace('count="1"><mergeCell ref="B2:D2"/>', 'count="2"><mergeCell ref="B2:D2"/><mergeCell ref="C2:C3"/>'),
|
|
49
|
+
source.replace('ref="B2:D2"', 'ref="B2:D2" custom="position"'),
|
|
50
|
+
source.replace("</row>", '<c r="C2"><v>55</v></c></row>')
|
|
51
|
+
];
|
|
52
|
+
for (const worksheet of variants) {
|
|
53
|
+
const bytes = zipSync({ ...parts, [reportPath]: strToU8(worksheet) });
|
|
54
|
+
const file = openXlsx("报表", bytes);
|
|
55
|
+
expect(file.restrictions).toContain("合并单元格");
|
|
56
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
57
|
+
}
|
|
58
|
+
});
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { formatWorkbookRange, indexWorkbookMerges, parseWorkbookRange, type WorkbookRange, type WorkbookSheet, type WorkbookStoredCell } from "@quirekit/workbook";
|
|
3
|
+
import { hasKnownAttributes, hasKnownChildren } from "../opc/shape";
|
|
4
|
+
import { child, children, readIndex, spreadNs } from "../opc/xml";
|
|
5
|
+
|
|
6
|
+
const afterMerges = new Set([
|
|
7
|
+
"phoneticPr", "conditionalFormatting", "dataValidations", "hyperlinks", "printOptions", "pageMargins",
|
|
8
|
+
"pageSetup", "headerFooter", "rowBreaks", "colBreaks", "customProperties", "cellWatches", "ignoredErrors",
|
|
9
|
+
"smartTags", "drawing", "legacyDrawing", "legacyDrawingHF", "picture", "oleObjects", "controls", "webPublishItems",
|
|
10
|
+
"tableParts", "extLst"
|
|
11
|
+
]);
|
|
12
|
+
|
|
13
|
+
/** @param worksheet - Retained worksheet. @param sheetId - Owner of merge coordinates.
|
|
14
|
+
* @param cells - Authored inputs. @returns Merge geometry and whether it can be safely rewritten. */
|
|
15
|
+
export function readXlsxMerges(worksheet: Element, sheetId: string, cells: readonly WorkbookStoredCell[]) {
|
|
16
|
+
const containers = children(worksheet, "mergeCells");
|
|
17
|
+
if (!containers.length) return { writable: true };
|
|
18
|
+
const container = containers[0]!;
|
|
19
|
+
const entries = children(container);
|
|
20
|
+
try {
|
|
21
|
+
const ranges = entries.map(node => parseWorkbookRange(sheetId, node.getAttribute("ref") ?? ""));
|
|
22
|
+
const index = indexWorkbookMerges(sheetId, ranges);
|
|
23
|
+
const writable = containers.length === 1 && container.namespaceURI === spreadNs && entries.length > 0
|
|
24
|
+
&& hasKnownAttributes(container, ["count"]) && (!container.hasAttribute("count") || readIndex(container, "count") === entries.length)
|
|
25
|
+
&& entries.every(node => node.namespaceURI === spreadNs && node.localName === "mergeCell"
|
|
26
|
+
&& hasKnownAttributes(node, ["ref"]) && hasKnownChildren(node, []))
|
|
27
|
+
&& !cells.some(({ row, column }) => index.covered({ sheetId, row, column }));
|
|
28
|
+
return { writable, ranges: index.ranges };
|
|
29
|
+
} catch {
|
|
30
|
+
return { writable: false };
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** @param sheet - Final authored inputs and geometry. @returns The validated merge rectangles to serialize. */
|
|
35
|
+
export function xlsxMergesForWrite({ id: sheetId, merges, cells }: WorkbookSheet): readonly WorkbookRange[] {
|
|
36
|
+
if (!merges?.length) return [];
|
|
37
|
+
const index = indexWorkbookMerges(sheetId, merges);
|
|
38
|
+
if (cells.some(({ row, column }) => index.covered({ sheetId, row, column }))) {
|
|
39
|
+
throw new Error("合并区域的覆盖格包含输入,无法安全写入 XLSX。");
|
|
40
|
+
}
|
|
41
|
+
return index.ranges;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** @param worksheet - Final cell positions in the native sheet. @param ranges - Validated merge rectangles at the same revision. */
|
|
45
|
+
export function writeXlsxMerges(worksheet: Element, ranges: readonly WorkbookRange[]): void {
|
|
46
|
+
const original = child(worksheet, "mergeCells");
|
|
47
|
+
if (!ranges.length) {
|
|
48
|
+
if (original) worksheet.removeChild(original);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
const document = worksheet.ownerDocument!;
|
|
52
|
+
const container = document.createElementNS(spreadNs, "mergeCells");
|
|
53
|
+
container.setAttribute("count", String(ranges.length));
|
|
54
|
+
for (const range of ranges) {
|
|
55
|
+
const item = document.createElementNS(spreadNs, "mergeCell");
|
|
56
|
+
item.setAttribute("ref", formatWorkbookRange(range));
|
|
57
|
+
container.appendChild(item);
|
|
58
|
+
}
|
|
59
|
+
if (original) worksheet.replaceChild(container, original);
|
|
60
|
+
else worksheet.insertBefore(container, children(worksheet).find(node => afterMerges.has(node.localName ?? "")) ?? null);
|
|
61
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { workbookColumns, workbookOutlineHidden, workbookOutlineSpanAt, type WorkbookAxisOutline,
|
|
2
|
+
type WorkbookSheetAppearance, type WorkbookWorksheetDimensions } from "@quirekit/workbook";
|
|
3
|
+
import type { Element } from "@xmldom/xmldom";
|
|
4
|
+
import { child, children, readIndex } from "../../opc/xml";
|
|
5
|
+
import { writeXlsxColumnDimensions } from "../dimensions/columns";
|
|
6
|
+
import { xlsxOutlineMarker } from "./native";
|
|
7
|
+
import type { XlsxColumnLayoutSpan } from "./types";
|
|
8
|
+
|
|
9
|
+
/** @param appearance - Imported column geometry at the final coordinates. @param dimensions - Authoritative overrides.
|
|
10
|
+
* @returns A compact mask of manually hidden columns. */
|
|
11
|
+
export function xlsxManuallyHiddenColumns(appearance: WorkbookSheetAppearance | undefined, dimensions: WorkbookWorksheetDimensions | undefined): Uint8Array {
|
|
12
|
+
const flags = new Uint8Array(workbookColumns);
|
|
13
|
+
for (const { first, last, hidden } of appearance?.columns ?? []) flags.fill(hidden ? 1 : 0, first, last + 1);
|
|
14
|
+
for (const { first, last, hidden } of dimensions?.columns ?? []) if (hidden !== undefined) flags.fill(hidden ? 1 : 0, first, last + 1);
|
|
15
|
+
return flags;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** @param root - Worksheet with retained width and style records. @param outline - Committed column grouping.
|
|
19
|
+
* @param manual - Manually hidden positions, excluding folds. */
|
|
20
|
+
export function writeXlsxOutlineColumns(root: Element, outline: WorkbookAxisOutline | undefined, manual: Uint8Array): void {
|
|
21
|
+
const changed = new Uint8Array(workbookColumns);
|
|
22
|
+
const cols = child(root, "cols");
|
|
23
|
+
for (const node of cols ? children(cols, "col") : []) {
|
|
24
|
+
if (!node.hasAttribute("outlineLevel") && !node.hasAttribute("collapsed")) continue;
|
|
25
|
+
const min = readIndex(node, "min"), max = readIndex(node, "max");
|
|
26
|
+
if (min && max) changed.fill(1, min - 1, max);
|
|
27
|
+
}
|
|
28
|
+
for (const { first, last } of outline?.levels ?? []) changed.fill(1, first, last + 1);
|
|
29
|
+
const markers = new Set(outline?.collapsed.map(group => xlsxOutlineMarker("column", outline.summaryBefore, group)));
|
|
30
|
+
for (const marker of markers) changed[marker] = 1;
|
|
31
|
+
|
|
32
|
+
// Merge identical column settings before splitting the producer's width and style ranges.
|
|
33
|
+
const patches: XlsxColumnLayoutSpan[] = [];
|
|
34
|
+
const folded = workbookOutlineHidden(outline);
|
|
35
|
+
for (const [column, flagged] of changed.entries()) {
|
|
36
|
+
if (!flagged) continue;
|
|
37
|
+
const outlineLevel = workbookOutlineSpanAt(outline?.levels ?? [], column)?.level ?? 0;
|
|
38
|
+
const collapsed = markers.has(column);
|
|
39
|
+
const hidden = !!manual[column] || !!workbookOutlineSpanAt(folded, column);
|
|
40
|
+
const previous = patches.at(-1);
|
|
41
|
+
if (previous?.last === column - 1 && previous.outlineLevel === outlineLevel && previous.collapsed === collapsed && previous.hidden === hidden) {
|
|
42
|
+
patches[patches.length - 1] = { ...previous, last: column };
|
|
43
|
+
} else patches.push({ first: column, last: column, outlineLevel, collapsed, hidden });
|
|
44
|
+
}
|
|
45
|
+
writeXlsxColumnDimensions(root, patches);
|
|
46
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { workbookAxisLength, workbookOutlineHidden, workbookOutlineKey, workbookOutlineSpanAt, type WorkbookAxisSpan, type WorkbookDimensionAxis } from "@quirekit/workbook";
|
|
2
|
+
import type { Element } from "@xmldom/xmldom";
|
|
3
|
+
import { child, children, spreadNs } from "../../opc/xml";
|
|
4
|
+
import { xlsxNativeFoldCandidates, xlsxOutlineMarker } from "./native";
|
|
5
|
+
import type { XlsxNativeOutlineAxis, XlsxOutlineAxisMetadata } from "./types";
|
|
6
|
+
|
|
7
|
+
const namespace = "urn:quirekit:spreadsheet:outline-attribution:1";
|
|
8
|
+
|
|
9
|
+
/** @param element - Worksheet extension entry. @returns Whether it contains worksheet outline attribution. */
|
|
10
|
+
export function isXlsxOutlineMetadata(element: Element): boolean {
|
|
11
|
+
return element.localName === "ext" && element.getAttribute("uri") === namespace
|
|
12
|
+
&& child(element, "outline")?.namespaceURI === namespace;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** @param root - Source worksheet. @param axis - Grouped axis. @param native - Parsed standard worksheet attributes.
|
|
16
|
+
* @returns Additional attribution only when its folds and manually hidden spans agree with the native outline. */
|
|
17
|
+
export function readXlsxOutlineMetadata(root: Element, axis: WorkbookDimensionAxis, native: XlsxNativeOutlineAxis): XlsxOutlineAxisMetadata | undefined {
|
|
18
|
+
const ext = child(root, "extLst");
|
|
19
|
+
const record = ext && children(ext).find(isXlsxOutlineMetadata);
|
|
20
|
+
const payload = record && child(record, "outline");
|
|
21
|
+
const data = payload && child(payload, axis);
|
|
22
|
+
if (!data || data.namespaceURI !== namespace) return;
|
|
23
|
+
const serialized = data.getAttribute("folds") ?? "";
|
|
24
|
+
const requested = new Set(serialized ? serialized.split(" ") : []);
|
|
25
|
+
const folds = xlsxNativeFoldCandidates(axis, native).filter(group => requested.delete(workbookOutlineKey(group)));
|
|
26
|
+
if (requested.size || new Set(folds.map(group => xlsxOutlineMarker(axis, native.summaryBefore, group))).size !== native.markers.size) return;
|
|
27
|
+
const folded = workbookOutlineHidden({ summaryBefore: native.summaryBefore, levels: native.levels, collapsed: folds });
|
|
28
|
+
const manual: WorkbookAxisSpan[] = [];
|
|
29
|
+
const ranges = data.getAttribute("manual");
|
|
30
|
+
for (const value of ranges ? ranges.split(" ") : []) {
|
|
31
|
+
const bounds = /^(\d+)(?:-(\d+))?$/u.exec(value);
|
|
32
|
+
if (!bounds) return;
|
|
33
|
+
const first = Number(bounds[1]), last = Number(bounds[2] ?? bounds[1]);
|
|
34
|
+
if (first <= (manual.at(-1)?.last ?? -1) || last < first || last >= workbookAxisLength(axis)
|
|
35
|
+
|| (workbookOutlineSpanAt(folded, first)?.last ?? -1) < last) return;
|
|
36
|
+
manual.push({ first, last });
|
|
37
|
+
}
|
|
38
|
+
return { folds, manual };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** @param root - Mutable worksheet. @param axes - Information lost when using only native attributes. */
|
|
42
|
+
export function writeXlsxOutlineMetadata(root: Element, axes: Partial<Record<WorkbookDimensionAxis, XlsxOutlineAxisMetadata | undefined>>): void {
|
|
43
|
+
let extensions = child(root, "extLst");
|
|
44
|
+
const earlier = extensions && children(extensions).find(isXlsxOutlineMetadata);
|
|
45
|
+
if (earlier) extensions!.removeChild(earlier);
|
|
46
|
+
if (!axes.row && !axes.column) {
|
|
47
|
+
if (extensions && !children(extensions).length) root.removeChild(extensions);
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
const document = root.ownerDocument!;
|
|
51
|
+
if (!extensions) {
|
|
52
|
+
extensions = document.createElementNS(spreadNs, "extLst");
|
|
53
|
+
root.appendChild(extensions);
|
|
54
|
+
}
|
|
55
|
+
const entry = document.createElementNS(spreadNs, "ext");
|
|
56
|
+
entry.setAttribute("uri", namespace);
|
|
57
|
+
const payload = document.createElementNS(namespace, "qko:outline");
|
|
58
|
+
for (const axis of ["row", "column"] as const) {
|
|
59
|
+
const data = axes[axis];
|
|
60
|
+
if (!data) continue;
|
|
61
|
+
const node = document.createElementNS(namespace, `qko:${axis}`);
|
|
62
|
+
node.setAttribute("folds", data.folds.map(workbookOutlineKey).join(" "));
|
|
63
|
+
node.setAttribute("manual", data.manual.map(({ first, last }) => first === last ? String(first) : `${first}-${last}`).join(" "));
|
|
64
|
+
payload.appendChild(node);
|
|
65
|
+
}
|
|
66
|
+
entry.appendChild(payload);
|
|
67
|
+
extensions.appendChild(entry);
|
|
68
|
+
}
|