@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,96 @@
|
|
|
1
|
+
import { workbookImagePresentation, type WorkbookSnapshot } from "@quirekit/workbook";
|
|
2
|
+
import { retainedXlsxRelationshipTargets } from "../../image/relationships";
|
|
3
|
+
import { editPartRelationships } from "../../opc/relationships";
|
|
4
|
+
import { child, children, contentTypeNs, parsePart, relationshipNs, rootOf, spreadNs, writePart } from "../../opc/xml";
|
|
5
|
+
import type { XlsxPackage } from "../../package/types";
|
|
6
|
+
|
|
7
|
+
const manifestPath = "[Content_Types].xml";
|
|
8
|
+
const imageRelationship = relationshipNs + "/image";
|
|
9
|
+
const afterPicture = new Set(["oleObjects", "controls", "webPublishItems", "tableParts", "extLst"]);
|
|
10
|
+
|
|
11
|
+
/** @param source - Original worksheet and media ownership. @param parts - Archive being written.
|
|
12
|
+
* @param paths - Final sheet paths. @param snapshot - Committed views and resources. */
|
|
13
|
+
export function writeWorkbookBackgrounds(source: XlsxPackage, parts: Record<string, Uint8Array>,
|
|
14
|
+
paths: ReadonlyMap<string, string>, snapshot: WorkbookSnapshot): void {
|
|
15
|
+
const priorPaths = source.backgroundPaths;
|
|
16
|
+
if (!priorPaths?.size && !snapshot.sheets.some(sheet => sheet.view?.backgroundAssetId)) return;
|
|
17
|
+
const originals = new Map(source.baseline?.sheets.map(sheet => [sheet.id, sheet.view?.backgroundAssetId]));
|
|
18
|
+
const originalAssets = new Map(source.baseline?.imageAssets?.map(asset => [asset.id, asset]));
|
|
19
|
+
const assets = new Map(snapshot.imageAssets?.map(asset => [asset.id, asset]));
|
|
20
|
+
const media = new Map<string, string>();
|
|
21
|
+
for (const [id, path] of priorPaths ?? []) {
|
|
22
|
+
const before = originalAssets.get(id), after = assets.get(id);
|
|
23
|
+
if (parts[path] && before && after && before.data === after.data && before.mimeType === after.mimeType) media.set(id, path);
|
|
24
|
+
}
|
|
25
|
+
const changed = snapshot.sheets.filter(({ id, view }) => {
|
|
26
|
+
const before = originals.get(id), after = view?.backgroundAssetId;
|
|
27
|
+
return before !== after || Boolean(after && !media.has(after));
|
|
28
|
+
});
|
|
29
|
+
const removedSheet = [...originals].some(([id, asset]) => asset && !paths.has(id));
|
|
30
|
+
if (!changed.length && !removedSheet) return;
|
|
31
|
+
|
|
32
|
+
const manifest = parsePart(parts[manifestPath], manifestPath);
|
|
33
|
+
const types = rootOf(manifest, contentTypeNs, "Types");
|
|
34
|
+
const overrides = new Map(children(types, "Override").map(node => [node.getAttribute("PartName"), node]));
|
|
35
|
+
const reserved = new Set([...Object.keys(parts), ...Array.from(overrides.keys(), path => path?.slice(1) ?? "")].map(path => path.toLowerCase()));
|
|
36
|
+
const directory = source.workbookPath.slice(0, source.workbookPath.lastIndexOf("/") + 1);
|
|
37
|
+
let serial = 1;
|
|
38
|
+
|
|
39
|
+
/** @param id - Referenced workbook raster. @returns Internal native raster URI, shared across affected worksheets. */
|
|
40
|
+
function place(id: string): string {
|
|
41
|
+
const saved = media.get(id);
|
|
42
|
+
if (saved) return saved;
|
|
43
|
+
const asset = assets.get(id);
|
|
44
|
+
if (!asset) throw new Error("工作表背景缺少对应的图片资源。");
|
|
45
|
+
const extension = asset.mimeType === "image/png" ? "png" : "jpeg";
|
|
46
|
+
let path: string;
|
|
47
|
+
do { path = `${directory}media/worksheetBackground${serial++}.${extension}`; }
|
|
48
|
+
while (reserved.has(path.toLowerCase()));
|
|
49
|
+
reserved.add(path.toLowerCase());
|
|
50
|
+
parts[path] = workbookImagePresentation(asset).bytes();
|
|
51
|
+
const override = manifest.createElementNS(contentTypeNs, "Override");
|
|
52
|
+
override.setAttribute("PartName", "/" + path);
|
|
53
|
+
override.setAttribute("ContentType", asset.mimeType);
|
|
54
|
+
types.appendChild(override);
|
|
55
|
+
media.set(id, path);
|
|
56
|
+
return path;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
for (const sheet of changed) {
|
|
60
|
+
const path = paths.get(sheet.id)!;
|
|
61
|
+
const document = parsePart(parts[path], path);
|
|
62
|
+
const worksheet = rootOf(document, spreadNs, "worksheet");
|
|
63
|
+
const picture = child(worksheet, "picture");
|
|
64
|
+
const relationships = editPartRelationships(parts, path);
|
|
65
|
+
if (picture) {
|
|
66
|
+
const id = picture.getAttributeNS(relationshipNs, "id");
|
|
67
|
+
worksheet.removeChild(picture);
|
|
68
|
+
// An existing consumer may share the relationship ID. Remove only the workbook background's reference.
|
|
69
|
+
if (id && !Array.from(worksheet.getElementsByTagName("*")).some(element =>
|
|
70
|
+
Array.from(element.attributes).some(attr => attr.namespaceURI === relationshipNs && attr.value === id))) {
|
|
71
|
+
relationships.remove(id);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
const assetId = sheet.view?.backgroundAssetId;
|
|
75
|
+
if (assetId) {
|
|
76
|
+
const element = document.createElementNS(spreadNs, "picture");
|
|
77
|
+
const target = "/" + place(assetId).split("/").map(segment => encodeURIComponent(segment)).join("/");
|
|
78
|
+
element.setAttributeNS(relationshipNs, "r:id", relationships.add(imageRelationship, target));
|
|
79
|
+
const next = children(worksheet).find(node => node.namespaceURI === spreadNs && afterPicture.has(node.localName!));
|
|
80
|
+
worksheet.insertBefore(element, next ?? null);
|
|
81
|
+
}
|
|
82
|
+
relationships.write();
|
|
83
|
+
parts[path] = writePart(document);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Media can be shared by sheets and other XLSX features. Collect only parts whose last relation disappeared.
|
|
87
|
+
if (priorPaths?.size) {
|
|
88
|
+
const targets = retainedXlsxRelationshipTargets(parts);
|
|
89
|
+
if (targets) for (const path of priorPaths.values()) if (!targets.has(path)) {
|
|
90
|
+
delete parts[path];
|
|
91
|
+
const override = overrides.get("/" + path);
|
|
92
|
+
if (override) types.removeChild(override);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
parts[manifestPath] = writePart(manifest);
|
|
96
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { Document, Element } from "@xmldom/xmldom";
|
|
2
|
+
import { formatWorkbookColumn, mapWorkbookPosition, workbookCellShiftWriteRange, type WorkbookCellShift } from "@quirekit/workbook";
|
|
3
|
+
import { spreadNs } from "../opc/xml";
|
|
4
|
+
import { appendOrdered, indexCells, indexRows } from "./positions";
|
|
5
|
+
|
|
6
|
+
/** @param document - Original worksheet XML. @param data - Worksheet sheetData. @param shift - Accepted regional cell edit. */
|
|
7
|
+
export function shiftXlsxCells(document: Document, data: Element, shift: WorkbookCellShift): void {
|
|
8
|
+
const rows = indexRows(data);
|
|
9
|
+
const scope = workbookCellShiftWriteRange(shift);
|
|
10
|
+
const affected = new Map<number, Map<number, Element>>();
|
|
11
|
+
const moved: Array<{ row: number; column: number; node: Element }> = [];
|
|
12
|
+
|
|
13
|
+
// Separate source nodes from their targets before installing any destination, including styled blanks.
|
|
14
|
+
for (const [row, element] of rows) {
|
|
15
|
+
if (row < scope.startRow || row > scope.endRow) continue;
|
|
16
|
+
const cells = indexCells(element);
|
|
17
|
+
for (const [column, node] of cells) {
|
|
18
|
+
if (column < scope.startColumn || column > scope.endColumn) continue;
|
|
19
|
+
cells.delete(column);
|
|
20
|
+
element.removeChild(node);
|
|
21
|
+
const next = mapWorkbookPosition({ sheetId: shift.sheetId, row, column }, shift);
|
|
22
|
+
if (next) moved.push({ row: next.row, column: next.column, node });
|
|
23
|
+
affected.set(row, cells);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
for (const { row, column, node } of moved) {
|
|
27
|
+
const element = rows.get(row);
|
|
28
|
+
const cells = affected.get(row) ?? (element ? indexCells(element) : new Map<number, Element>());
|
|
29
|
+
cells.set(column, node);
|
|
30
|
+
affected.set(row, cells);
|
|
31
|
+
}
|
|
32
|
+
if (!affected.size) return;
|
|
33
|
+
|
|
34
|
+
// Inserting sparse rows while keeping existing row records also preserves their physical heights.
|
|
35
|
+
for (const [row, cells] of affected) {
|
|
36
|
+
const element = rows.get(row) ?? document.createElementNS(spreadNs, "row");
|
|
37
|
+
rows.set(row, element);
|
|
38
|
+
element.removeAttribute("spans");
|
|
39
|
+
for (const [column, cell] of cells) cell.setAttribute("r", formatWorkbookColumn(column) + (row + 1));
|
|
40
|
+
appendOrdered(element, cells);
|
|
41
|
+
}
|
|
42
|
+
for (const [row, element] of rows) if (!element.hasAttribute("r")) element.setAttribute("r", String(row + 1));
|
|
43
|
+
appendOrdered(data, rows);
|
|
44
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { Document, Element } from "@xmldom/xmldom";
|
|
2
|
+
import { formatWorkbookRange, usesWorkbookExternalAiFunction, type WorkbookCell, type WorkbookCellResult, type WorkbookRange } from "@quirekit/workbook";
|
|
3
|
+
import { child, children, spreadNs } from "../opc/xml";
|
|
4
|
+
import { writeXlsxTextCell } from "./rich-text";
|
|
5
|
+
import { encodeXlsxText, insertXlsxText } from "./text";
|
|
6
|
+
import { prefixXlsxFormulaFunctions } from "./formula/prefix";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @param document - Owning worksheet.
|
|
10
|
+
* @param cell - Cell keeping its style and other unrelated source data.
|
|
11
|
+
* @param input - Updated authored data, or null to clear.
|
|
12
|
+
* @param result - Cached calculation at the written revision.
|
|
13
|
+
* @param imageIndex - One-based native value metadata reference for an image cell.
|
|
14
|
+
* @param array - Native range of a dynamic formula or one of its derived cache cells.
|
|
15
|
+
*/
|
|
16
|
+
export function writeCell(document: Document, cell: Element, input: WorkbookCell | null, result?: WorkbookCellResult, imageIndex?: number,
|
|
17
|
+
array?: WorkbookRange): void {
|
|
18
|
+
for (const part of children(cell)) {
|
|
19
|
+
if (part.namespaceURI === spreadNs && ["v", "f", "is"].includes(part.localName ?? "")) cell.removeChild(part);
|
|
20
|
+
}
|
|
21
|
+
cell.removeAttribute("t");
|
|
22
|
+
cell.removeAttribute("vm");
|
|
23
|
+
cell.removeAttribute("cm");
|
|
24
|
+
if (input === null) {
|
|
25
|
+
if (array) writeCachedValue(document, cell, result);
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
if (input.kind === "image") {
|
|
29
|
+
if (!imageIndex) throw new Error("XLSX 格内图片缺少原生索引。");
|
|
30
|
+
cell.setAttribute("t", "e");
|
|
31
|
+
cell.setAttribute("vm", String(imageIndex));
|
|
32
|
+
insertXlsxText(document, cell, "v", "#VALUE!");
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
if (input.kind === "formula") {
|
|
36
|
+
insertXlsxText(document, cell, "f", prefixXlsxFormulaFunctions(input.formula.slice(1)));
|
|
37
|
+
if (array) {
|
|
38
|
+
cell.setAttribute("cm", "1");
|
|
39
|
+
const formula = child(cell, "f")!;
|
|
40
|
+
formula.setAttribute("t", "array");
|
|
41
|
+
formula.setAttribute("ref", formatWorkbookRange(array));
|
|
42
|
+
}
|
|
43
|
+
const cached = input.externalResult ?? (usesWorkbookExternalAiFunction(input.formula) ? undefined : result);
|
|
44
|
+
writeCachedValue(document, cell, cached);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
if (input.kind === "error") {
|
|
48
|
+
writeCachedValue(document, cell, { status: "error", code: input.code });
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
const { value } = input;
|
|
52
|
+
if (typeof value === "string") {
|
|
53
|
+
cell.setAttribute("t", "inlineStr");
|
|
54
|
+
const inline = document.createElementNS(spreadNs, "is");
|
|
55
|
+
const extension = children(cell).find(item => item.localName === "extLst");
|
|
56
|
+
cell.insertBefore(inline, extension ?? null);
|
|
57
|
+
writeXlsxTextCell(inline, { ...input, value });
|
|
58
|
+
} else {
|
|
59
|
+
if (typeof value === "boolean") cell.setAttribute("t", "b");
|
|
60
|
+
insertXlsxText(document, cell, "v", typeof value === "boolean" ? (value ? "1" : "0") : String(value));
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** @param document - Owning worksheet. @param cell - Formula cell or derived output. @param result - Published native cache. */
|
|
65
|
+
function writeCachedValue(document: Document, cell: Element, result: WorkbookCellResult | undefined): void {
|
|
66
|
+
if (result?.status === "error") {
|
|
67
|
+
cell.setAttribute("t", "e");
|
|
68
|
+
insertXlsxText(document, cell, "v", result.code);
|
|
69
|
+
} else if (result?.status === "value" && result.value !== null) {
|
|
70
|
+
if (typeof result.value === "string") cell.setAttribute("t", "str");
|
|
71
|
+
if (typeof result.value === "boolean") cell.setAttribute("t", "b");
|
|
72
|
+
insertXlsxText(document, cell, "v", typeof result.value === "boolean" ? (result.value ? "1" : "0")
|
|
73
|
+
: typeof result.value === "string" ? encodeXlsxText(result.value) : String(result.value));
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { indexWorkbookCheckboxes, sourceWorkbookStyleId, workbookRangeSize, type WorkbookAppearance, type WorkbookCell,
|
|
2
|
+
type WorkbookCellFormat, type WorkbookRange, type WorkbookSheet } from "@quirekit/workbook";
|
|
3
|
+
import type { XlsxWriteOptions } from "../../types";
|
|
4
|
+
|
|
5
|
+
/** @param sheet - Final worksheet state. @param appearance - Original styles mapped to final coordinates.
|
|
6
|
+
* @param native - Styles originally carrying the native control. @param add - Registers derived styles.
|
|
7
|
+
* @param result - Optional formula results from the saved revision.
|
|
8
|
+
* @returns Exact changed styles and coverage that cannot be expressed with existing cells alone. */
|
|
9
|
+
export function xlsxCheckboxFormatting(
|
|
10
|
+
sheet: WorkbookSheet, appearance: WorkbookAppearance | undefined, native: ReadonlySet<number> | undefined,
|
|
11
|
+
add: (basis: number, patch: WorkbookCellFormat, checkbox?: boolean) => number, result?: XlsxWriteOptions["result"]
|
|
12
|
+
) {
|
|
13
|
+
const formats = new Map<number, Map<number, number>>();
|
|
14
|
+
const overrides = new Map(sheet.formats?.map(({ row, column, format }) => [`${row}:${column}`, format] as const));
|
|
15
|
+
const ranges = sheet.checkboxes ?? [];
|
|
16
|
+
const scan = indexWorkbookCheckboxes(ranges);
|
|
17
|
+
const seen = new Set<string>();
|
|
18
|
+
const counts = new Map<WorkbookRange, number>();
|
|
19
|
+
/**
|
|
20
|
+
* @param row - Stored position. @param column - Stored position. @param input - Stored value or formula.
|
|
21
|
+
* Assigns a native XF to Boolean values while preserving the cell's other formatting.
|
|
22
|
+
*/
|
|
23
|
+
function visit(row: number, column: number, input?: WorkbookCell): void {
|
|
24
|
+
const key = `${row}:${column}` as const;
|
|
25
|
+
if (seen.has(key)) return;
|
|
26
|
+
seen.add(key);
|
|
27
|
+
const address = { sheetId: sheet.id, row, column };
|
|
28
|
+
const cell = { sheetId: sheet.id, startRow: row, endRow: row, startColumn: column, endColumn: column };
|
|
29
|
+
const basis = sourceWorkbookStyleId(appearance, address);
|
|
30
|
+
const previous = native?.has(basis) ?? false;
|
|
31
|
+
const enabled = scan(cell, range => {
|
|
32
|
+
const calculated = input?.kind === "formula" ? result?.(address) : undefined;
|
|
33
|
+
const compatible = input?.kind === "value" ? typeof input.value === "boolean"
|
|
34
|
+
: calculated ? calculated.status === "value" && typeof calculated.value === "boolean" : previous;
|
|
35
|
+
if (compatible) counts.set(range, (counts.get(range) ?? 0) + 1);
|
|
36
|
+
return compatible;
|
|
37
|
+
});
|
|
38
|
+
const patch = overrides.get(key);
|
|
39
|
+
if (!patch && previous === enabled) return;
|
|
40
|
+
const styles = formats.get(row) ?? new Map<number, number>();
|
|
41
|
+
styles.set(column, add(basis, patch ?? {}, previous === enabled ? undefined : enabled));
|
|
42
|
+
formats.set(row, styles);
|
|
43
|
+
}
|
|
44
|
+
// Do not walk unstored cells, even if their rule covers the entire worksheet.
|
|
45
|
+
if (ranges.length || native?.size) {
|
|
46
|
+
for (const { row, column, input } of sheet.cells) visit(row, column, input);
|
|
47
|
+
for (const [row, cells] of Object.entries(appearance?.sheets.get(sheet.id)?.cellStyles ?? {})) {
|
|
48
|
+
for (const column of Object.keys(cells)) visit(Number(row), Number(column));
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
for (const { row, column } of sheet.formats ?? []) visit(row, column);
|
|
52
|
+
return { formats, sparse: ranges.filter(range => (counts.get(range) ?? 0) < workbookRangeSize(range)) };
|
|
53
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { copyWorkbookCheckboxes, formatWorkbookRange, parseWorkbookRange, workbookTransactionCellLimit,
|
|
3
|
+
type WorkbookRange, type WorkbookSheetAppearance } from "@quirekit/workbook";
|
|
4
|
+
import { hasKnownAttributes } from "../../opc/shape";
|
|
5
|
+
import { child, children, spreadNs } from "../../opc/xml";
|
|
6
|
+
|
|
7
|
+
const namespace = "urn:quirekit:spreadsheet:checkbox-ranges:1";
|
|
8
|
+
|
|
9
|
+
/** @param node - Worksheet extension. @returns Whether it stores sparse, authored checkbox coverage. */
|
|
10
|
+
export function isXlsxCheckboxRanges(node: Element): boolean {
|
|
11
|
+
return node.namespaceURI === spreadNs && node.localName === "ext" && node.getAttribute("uri") === namespace;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** @param root - Native worksheet. @param sheetId - Workbook sheet identity.
|
|
15
|
+
* @param appearance - Source cell and default style indexes. @param styles - Recognized checkbox style IDs.
|
|
16
|
+
* @param restrictions - Read-only diagnostics. @returns Disjoint native and sparse checkbox areas. */
|
|
17
|
+
export function readXlsxCheckboxRanges(root: Element, sheetId: string, appearance: WorkbookSheetAppearance, styles: ReadonlySet<number> | undefined,
|
|
18
|
+
restrictions: Set<string>): readonly WorkbookRange[] {
|
|
19
|
+
const list = child(root, "extLst");
|
|
20
|
+
const records = list ? children(list).filter(isXlsxCheckboxRanges) : [];
|
|
21
|
+
if (!styles?.size && records.length === 0) return [];
|
|
22
|
+
if (styles && (styles.has(0) || [...appearance.rows.values(), ...appearance.columns].some(({ style }) => style !== undefined && styles.has(style)))) {
|
|
23
|
+
restrictions.add("继承的单元格控件");
|
|
24
|
+
}
|
|
25
|
+
try {
|
|
26
|
+
const sparse = copyWorkbookCheckboxes(sheetId, decodeSparse(records, sheetId));
|
|
27
|
+
const materialized = styles?.size ? readMaterialized(sheetId, appearance.cellStyles, styles, sparse.scan) : [];
|
|
28
|
+
return copyWorkbookCheckboxes(sheetId, [...sparse.ranges, ...materialized]).ranges;
|
|
29
|
+
} catch {
|
|
30
|
+
restrictions.add("复选框范围无法读取");
|
|
31
|
+
return [];
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** @param sheetId - Worksheet identity. @param rows - Explicit cell styles.
|
|
36
|
+
* @param styles - Recognized control formats. @param sparse - Index of coverage already represented by extensions.
|
|
37
|
+
* @returns Contiguous native style runs combined into rectangles across adjacent rows. */
|
|
38
|
+
function readMaterialized(sheetId: string, rows: WorkbookSheetAppearance["cellStyles"], styles: ReadonlySet<number>,
|
|
39
|
+
sparse: ReturnType<typeof copyWorkbookCheckboxes>["scan"]): WorkbookRange[] {
|
|
40
|
+
const areas: WorkbookRange[] = [];
|
|
41
|
+
let previous = new Map<string, number>();
|
|
42
|
+
for (const [rowKey, rowStyles] of Object.entries(rows)) {
|
|
43
|
+
const row = Number(rowKey), runs: WorkbookRange[] = [];
|
|
44
|
+
for (const [colKey, style] of Object.entries(rowStyles)) {
|
|
45
|
+
if (!styles.has(style)) continue;
|
|
46
|
+
const column = Number(colKey);
|
|
47
|
+
const position = { sheetId, startRow: row, endRow: row, startColumn: column, endColumn: column };
|
|
48
|
+
if (sparse(position, () => true)) continue;
|
|
49
|
+
const last = runs.at(-1);
|
|
50
|
+
if (last && last.endColumn + 1 === column) runs[runs.length - 1] = { ...last, endColumn: column };
|
|
51
|
+
else runs.push(position);
|
|
52
|
+
}
|
|
53
|
+
// Equal column runs can extend across consecutive native rows without allocating unstored positions.
|
|
54
|
+
const next = new Map<string, number>();
|
|
55
|
+
for (const run of runs) {
|
|
56
|
+
const key = `${run.startColumn}:${run.endColumn}`;
|
|
57
|
+
const index = previous.get(key);
|
|
58
|
+
if (index !== undefined && areas[index]!.endRow + 1 === row) {
|
|
59
|
+
areas[index] = { ...areas[index]!, endRow: row };
|
|
60
|
+
next.set(key, index);
|
|
61
|
+
} else {
|
|
62
|
+
next.set(key, areas.length);
|
|
63
|
+
areas.push(run);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
previous = next;
|
|
67
|
+
}
|
|
68
|
+
return areas;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** @param records - Extension instances in the original sheet. @param sheetId - Worksheet identity.
|
|
72
|
+
* @returns Parsed coverage, rejecting duplicate or unsupported extension records. */
|
|
73
|
+
function decodeSparse(records: Element[], sheetId: string): WorkbookRange[] {
|
|
74
|
+
if (!records.length) return [];
|
|
75
|
+
const [record] = records;
|
|
76
|
+
const payload = record && child(record, "checkboxes");
|
|
77
|
+
if (records.length !== 1 || !payload || payload.namespaceURI !== namespace || !hasKnownAttributes(payload, [])
|
|
78
|
+
|| !hasKnownAttributes(record!, ["uri"]) || children(record!).length !== 1) throw new Error("Invalid checkbox coverage");
|
|
79
|
+
const ranges = children(payload);
|
|
80
|
+
if (ranges.length > workbookTransactionCellLimit) throw new Error("Too many checkbox areas");
|
|
81
|
+
return ranges.map(node => {
|
|
82
|
+
if (node.namespaceURI !== namespace || node.localName !== "range" || !hasKnownAttributes(node, ["ref"]) || children(node).length) {
|
|
83
|
+
throw new Error("Invalid checkbox coverage");
|
|
84
|
+
}
|
|
85
|
+
return parseWorkbookRange(sheetId, node.getAttribute("ref") ?? "");
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** @param root - Worksheet root. @param sparse - Checkbox rectangles with at least one unmaterialized cell. */
|
|
90
|
+
export function writeXlsxCheckboxRanges(root: Element, sparse: readonly WorkbookRange[]): void {
|
|
91
|
+
let list = child(root, "extLst");
|
|
92
|
+
if (list) for (const record of children(list).filter(isXlsxCheckboxRanges)) list.removeChild(record);
|
|
93
|
+
if (!sparse.length) {
|
|
94
|
+
if (list && !children(list).length) root.removeChild(list);
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
const document = root.ownerDocument!;
|
|
98
|
+
if (!list) {
|
|
99
|
+
list = document.createElementNS(spreadNs, "extLst");
|
|
100
|
+
root.appendChild(list);
|
|
101
|
+
}
|
|
102
|
+
const record = document.createElementNS(spreadNs, "ext");
|
|
103
|
+
record.setAttribute("uri", namespace);
|
|
104
|
+
const payload = document.createElementNS(namespace, "qkc:checkboxes");
|
|
105
|
+
for (const range of sparse) {
|
|
106
|
+
const target = document.createElementNS(namespace, "qkc:range");
|
|
107
|
+
target.setAttribute("ref", formatWorkbookRange(range));
|
|
108
|
+
payload.appendChild(target);
|
|
109
|
+
}
|
|
110
|
+
record.appendChild(payload);
|
|
111
|
+
list.appendChild(record);
|
|
112
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { openWorkbook, parseWorkbookRange, type WorkbookSnapshot } from "@quirekit/workbook";
|
|
2
|
+
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
|
|
3
|
+
import { expect, it } from "vitest";
|
|
4
|
+
import { createXlsx, openXlsx } from "../../index";
|
|
5
|
+
|
|
6
|
+
const sheetId = "orders";
|
|
7
|
+
const source: WorkbookSnapshot = { version: 1, revision: 0, id: sheetId, name: "Orders", sheets: [{
|
|
8
|
+
id: sheetId, name: "Orders", cells: [
|
|
9
|
+
{ row: 1, column: 1, input: { kind: "value", value: true } },
|
|
10
|
+
{ row: 2, column: 1, input: { kind: "value", value: false } },
|
|
11
|
+
{ row: 2, column: 2, input: { kind: "value", value: false } },
|
|
12
|
+
{ row: 3, column: 1, input: { kind: "value", value: "Already authored" } }
|
|
13
|
+
], formats: [{ row: 1, column: 1, format: { bold: true } }],
|
|
14
|
+
checkboxes: [parseWorkbookRange(sheetId, "B2:B1048576"), parseWorkbookRange(sheetId, "C3")]
|
|
15
|
+
}] };
|
|
16
|
+
const sheetPath = "xl/worksheets/sheet1.xml";
|
|
17
|
+
const featurePath = "xl/featurePropertyBag/featurePropertyBag.xml";
|
|
18
|
+
|
|
19
|
+
it("saves Boolean cell controls with native styles and keeps the rest of a column sparse", async () => {
|
|
20
|
+
const bytes = createXlsx(source);
|
|
21
|
+
const parts = unzipSync(bytes);
|
|
22
|
+
expect(strFromU8(parts["xl/_rels/workbook.xml.rels"]!)).toContain("relationships/FeaturePropertyBag");
|
|
23
|
+
expect(strFromU8(parts["[Content_Types].xml"]!)).toContain("application/vnd.ms-excel.featurepropertybag+xml");
|
|
24
|
+
expect(strFromU8(parts[featurePath]!)).toContain('<bag type="Checkbox"/>');
|
|
25
|
+
expect(strFromU8(parts["xl/styles.xml"]!)).toContain('xfComplement i="0"');
|
|
26
|
+
const native = strFromU8(parts[sheetPath]!);
|
|
27
|
+
expect(native).toMatch(/<c r="B2"[^>]*\bt="b"[^>]*><v>1<\/v><\/c>/u);
|
|
28
|
+
expect(native).toMatch(/<c r="B3"[^>]*\bt="b"[^>]*><v>0<\/v><\/c>/u);
|
|
29
|
+
expect(native).toContain('<c r="B4" t="inlineStr">');
|
|
30
|
+
expect(native.match(/<c /gu)).toHaveLength(4);
|
|
31
|
+
expect(native).toContain('ref="B2:B1048576"');
|
|
32
|
+
|
|
33
|
+
const file = openXlsx("Orders", bytes);
|
|
34
|
+
const [sheet] = file.snapshot.sheets;
|
|
35
|
+
const id = sheet!.id;
|
|
36
|
+
expect(file.restrictions).toEqual([]);
|
|
37
|
+
expect(sheet!.checkboxes).toEqual([parseWorkbookRange(id, "B2:B1048576"), parseWorkbookRange(id, "C3")]);
|
|
38
|
+
const book = await openWorkbook(file.snapshot, { appearance: file.appearance });
|
|
39
|
+
try {
|
|
40
|
+
const candidate = book.prepare({ operationId: "remove-controls", baseRevision: book.revision, commands: [
|
|
41
|
+
{ name: "setCellCheckboxes", target: parseWorkbookRange(id, "B2:B1048576"), params: { enabled: false } }
|
|
42
|
+
] });
|
|
43
|
+
await book.commit(candidate.id);
|
|
44
|
+
const saved = openXlsx("After", file.write(book.snapshot()));
|
|
45
|
+
expect(saved.snapshot.sheets[0]?.checkboxes).toEqual([parseWorkbookRange(id, "C3")]);
|
|
46
|
+
expect(saved.snapshot.sheets[0]?.cells.map(cell => cell.input)).toEqual(source.sheets[0]?.cells.map(cell => cell.input));
|
|
47
|
+
const reopened = await openWorkbook(saved.snapshot, { appearance: saved.appearance });
|
|
48
|
+
try { expect(reopened.readFormat({ sheetId: id, row: 1, column: 1 })).toMatchObject({ bold: true }); }
|
|
49
|
+
finally { await reopened.close(); }
|
|
50
|
+
await book.undo("restore-controls");
|
|
51
|
+
expect(file.write(book.snapshot())).toEqual(bytes);
|
|
52
|
+
} finally { await book.close(); }
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it("keeps unsupported feature property bags read-only and preserves the original archive", () => {
|
|
56
|
+
const parts = unzipSync(createXlsx(source));
|
|
57
|
+
parts[featurePath] = strToU8(strFromU8(parts[featurePath]!).replace('type="Checkbox"', 'type="UnknownControl"'));
|
|
58
|
+
const bytes = zipSync(parts);
|
|
59
|
+
const file = openXlsx("Orders", bytes);
|
|
60
|
+
expect(file.restrictions).toContain("暂未支持的单元格控件");
|
|
61
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
62
|
+
});
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import type { WorkbookConditionalColorScale, WorkbookConditionalColorStop } from "@quirekit/workbook";
|
|
3
|
+
import { hasKnownAttributes, hasKnownChildren } from "../../opc/shape";
|
|
4
|
+
import { children, spreadNs } from "../../opc/xml";
|
|
5
|
+
import type { styleColorReader } from "../../styles/color";
|
|
6
|
+
import { readXlsxNumericThreshold, writeXlsxThresholdOperand } from "./threshold";
|
|
7
|
+
|
|
8
|
+
const nativeTypes = { minimum: "min", maximum: "max", number: "num", percent: "percent", percentile: "percentile", formula: "formula" } as const;
|
|
9
|
+
|
|
10
|
+
/** @param threshold - First group of elements. @param ink - Paired color from the second group.
|
|
11
|
+
* @param resolve - Source theme and palette. @returns A supported stop, or undefined to retain the native rule. */
|
|
12
|
+
function readStop(threshold: Element, ink: Element, resolve: ReturnType<typeof styleColorReader>): WorkbookConditionalColorStop | undefined {
|
|
13
|
+
if (threshold.localName !== "cfvo" || threshold.namespaceURI !== spreadNs || !hasKnownAttributes(threshold, ["type", "val"])
|
|
14
|
+
|| !hasKnownChildren(threshold, []) || ink.localName !== "color" || ink.namespaceURI !== spreadNs
|
|
15
|
+
|| !hasKnownAttributes(ink, ["rgb", "theme", "indexed", "tint"]) || !hasKnownChildren(ink, [])) return;
|
|
16
|
+
const color = resolve(ink);
|
|
17
|
+
if (!color) return;
|
|
18
|
+
const type = threshold.getAttribute("type");
|
|
19
|
+
if (type === "min" || type === "max") return { type: type === "min" ? "minimum" : "maximum", color };
|
|
20
|
+
const raw = threshold.getAttribute("val")?.trim() ?? "";
|
|
21
|
+
const bound = readXlsxNumericThreshold(type, raw);
|
|
22
|
+
return bound && { ...bound, color };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** @param rule - Native color scale rule. @param resolve - Source theme and palette.
|
|
26
|
+
* @returns Editable scale when all stops and colors are represented. */
|
|
27
|
+
export function readXlsxColorScale(rule: Element, resolve: ReturnType<typeof styleColorReader>): WorkbookConditionalColorScale | undefined {
|
|
28
|
+
if (!hasKnownAttributes(rule, ["type", "priority", "stopIfTrue"])) return;
|
|
29
|
+
const [scale, extra] = children(rule);
|
|
30
|
+
if (!scale || extra || scale.localName !== "colorScale" || scale.namespaceURI !== spreadNs || !hasKnownAttributes(scale, [])) return;
|
|
31
|
+
const elements = children(scale);
|
|
32
|
+
const count = elements.length / 2;
|
|
33
|
+
if (count !== 2 && count !== 3) return;
|
|
34
|
+
const stops: WorkbookConditionalColorStop[] = [];
|
|
35
|
+
for (let index = 0; index < count; index++) {
|
|
36
|
+
const stop = readStop(elements[index]!, elements[index + count]!, resolve);
|
|
37
|
+
if (!stop) return;
|
|
38
|
+
stops.push(stop);
|
|
39
|
+
}
|
|
40
|
+
return { kind: "colorScale", stops };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** @param rule - Target native conditional rule. @param scale - Published color stops in application order. */
|
|
44
|
+
export function writeXlsxColorScale(rule: Element, scale: WorkbookConditionalColorScale): void {
|
|
45
|
+
const document = rule.ownerDocument!;
|
|
46
|
+
const colors = document.createElementNS(spreadNs, "colorScale");
|
|
47
|
+
rule.setAttribute("type", "colorScale");
|
|
48
|
+
for (const stop of scale.stops) {
|
|
49
|
+
const bound = document.createElementNS(spreadNs, "cfvo");
|
|
50
|
+
bound.setAttribute("type", nativeTypes[stop.type]);
|
|
51
|
+
const operand = writeXlsxThresholdOperand(stop);
|
|
52
|
+
if (operand !== undefined) bound.setAttribute("val", operand);
|
|
53
|
+
colors.appendChild(bound);
|
|
54
|
+
}
|
|
55
|
+
for (const { color } of scale.stops) {
|
|
56
|
+
const ink = document.createElementNS(spreadNs, "color");
|
|
57
|
+
ink.setAttribute("rgb", "FF" + color.slice(1));
|
|
58
|
+
colors.appendChild(ink);
|
|
59
|
+
}
|
|
60
|
+
rule.appendChild(colors);
|
|
61
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import type { WorkbookConditionalBarBound, WorkbookConditionalDataBar } from "@quirekit/workbook";
|
|
3
|
+
import { hasKnownAttributes, hasKnownChildren } from "../../opc/shape";
|
|
4
|
+
import { child, children, spreadNs } from "../../opc/xml";
|
|
5
|
+
import type { styleColorReader } from "../../styles/color";
|
|
6
|
+
import { xlsxConditionalNamespace, xlsxConditionalOperands, xlsxDataBarExtension } from "./extensions";
|
|
7
|
+
import { pairedXlsxThreshold, readXlsxConditionalFlag as flag, readXlsxNumericThreshold } from "./threshold";
|
|
8
|
+
|
|
9
|
+
/** @param node - Native threshold. @param first - Whether this is the lower endpoint. @param extended - Use the extended threshold grammar.
|
|
10
|
+
* @returns Typed data bar threshold without resolving it into the current cell values. */
|
|
11
|
+
function readBound(node: Element | undefined, first: boolean, extended: boolean): WorkbookConditionalBarBound {
|
|
12
|
+
const namespace = extended ? xlsxConditionalNamespace : spreadNs;
|
|
13
|
+
if (node?.namespaceURI !== namespace || node.localName !== "cfvo" || !hasKnownAttributes(node, extended ? ["type"] : ["type", "val"])
|
|
14
|
+
|| !hasKnownChildren(node, extended ? ["f"] : [], namespace, { f: xlsxConditionalOperands })) throw new Error("Unsupported data bar threshold.");
|
|
15
|
+
const type = node.getAttribute("type");
|
|
16
|
+
const expression = extended ? child(node, "f") : undefined;
|
|
17
|
+
if (expression && (children(node).length !== 1 || !hasKnownAttributes(expression, []) || !hasKnownChildren(expression, []))) {
|
|
18
|
+
throw new Error("Unsupported bar operand.");
|
|
19
|
+
}
|
|
20
|
+
if (!expression && type === (first ? "min" : "max")) return { type: "extreme" };
|
|
21
|
+
if (!expression && extended && type === (first ? "autoMin" : "autoMax")) return { type: "automatic" };
|
|
22
|
+
const text = (extended ? expression?.textContent : node.getAttribute("val"))?.trim() ?? "";
|
|
23
|
+
const bound = readXlsxNumericThreshold(type, text);
|
|
24
|
+
if (!bound) throw new Error("Unsupported data bar threshold value.");
|
|
25
|
+
return bound;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** @param node - Color to resolve from the original theme. @param resolve - Sheet palette. @returns An opaque color. */
|
|
29
|
+
function barColor(node: Element, resolve: ReturnType<typeof styleColorReader>): string {
|
|
30
|
+
if (!hasKnownAttributes(node, ["rgb", "theme", "indexed", "tint"]) || !hasKnownChildren(node, [])) throw new Error("Unsupported data bar color.");
|
|
31
|
+
const color = resolve(node);
|
|
32
|
+
if (!color) throw new Error("Invalid data bar color.");
|
|
33
|
+
return color;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** @param node - Bar settings. @param key - Minimum or maximum length. @param fallback - SpreadsheetML default percentage.
|
|
37
|
+
* @returns The numeric length, or an invalid number rejected by the canonical rule. */
|
|
38
|
+
function length(node: Element, key: "minLength" | "maxLength", fallback: number): number {
|
|
39
|
+
const text = node.getAttribute(key);
|
|
40
|
+
return !node.hasAttribute(key) ? fallback : /^\d+$/u.test(text ?? "") ? Number(text) : NaN;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** @param rule - Base data bar rule. @param sqref - Paired application ranges. @param extensions - Indexed x14 groups.
|
|
44
|
+
* @param resolve - Workbook palette. @returns Editable bar when every formatting field can be preserved. */
|
|
45
|
+
export function readXlsxConditionalBar(rule: Element, sqref: string, extensions: ReadonlyMap<string, Element>,
|
|
46
|
+
resolve: ReturnType<typeof styleColorReader>): WorkbookConditionalDataBar | undefined {
|
|
47
|
+
if (!hasKnownAttributes(rule, ["type", "priority", "stopIfTrue"]) || !hasKnownChildren(rule, ["dataBar", "extLst"])) return;
|
|
48
|
+
const base = child(rule, "dataBar");
|
|
49
|
+
if (!base || !hasKnownAttributes(base, ["minLength", "maxLength", "showValue"])) return;
|
|
50
|
+
const [lower, upper, ink, extra] = children(base);
|
|
51
|
+
if (extra || ink?.namespaceURI !== spreadNs || ink.localName !== "color") return;
|
|
52
|
+
const baseMinimum = readBound(lower, true, false), baseMaximum = readBound(upper, false, false);
|
|
53
|
+
const color = barColor(ink, resolve);
|
|
54
|
+
const showValue = flag(base, "showValue", true);
|
|
55
|
+
const baseLength = { minLength: length(base, "minLength", 10), maxLength: length(base, "maxLength", 90) };
|
|
56
|
+
if (!child(rule, "extLst")) {
|
|
57
|
+
return { kind: "dataBar", minimum: baseMinimum, maximum: baseMaximum, color, gradient: true, showValue, axis: "none", ...baseLength };
|
|
58
|
+
}
|
|
59
|
+
const enhanced = xlsxDataBarExtension(rule, sqref, extensions);
|
|
60
|
+
if (!enhanced || !hasKnownAttributes(enhanced, ["minLength", "maxLength", "gradient", "showValue", "axisPosition", "border", "direction",
|
|
61
|
+
"negativeBarColorSameAsPositive", "negativeBarBorderColorSameAsPositive"]) || flag(enhanced, "border", false)) return;
|
|
62
|
+
const direction = enhanced.getAttribute("direction") || "context";
|
|
63
|
+
const axis = enhanced.getAttribute("axisPosition") || "automatic";
|
|
64
|
+
if ((direction !== "context" && direction !== "leftToRight") || (axis !== "automatic" && axis !== "middle" && axis !== "none")) return;
|
|
65
|
+
const [first, last, ...colors] = children(enhanced);
|
|
66
|
+
if (new Set(colors.map(node => node.localName)).size !== colors.length
|
|
67
|
+
|| colors.some(node => node.namespaceURI !== xlsxConditionalNamespace || !["fillColor", "negativeFillColor", "axisColor"].includes(node.localName ?? ""))) return;
|
|
68
|
+
const fill = child(enhanced, "fillColor"), negative = child(enhanced, "negativeFillColor"), axisInk = child(enhanced, "axisColor");
|
|
69
|
+
const sameNegative = flag(enhanced, "negativeBarColorSameAsPositive", !negative);
|
|
70
|
+
if (sameNegative && negative) return;
|
|
71
|
+
return { kind: "dataBar", minimum: pairedXlsxThreshold(baseMinimum, readBound(first, true, true)),
|
|
72
|
+
maximum: pairedXlsxThreshold(baseMaximum, readBound(last, false, true)), color: fill ? barColor(fill, resolve) : color,
|
|
73
|
+
...(negative && { negativeColor: barColor(negative, resolve) }), ...(axisInk && axis !== "none" && { axisColor: barColor(axisInk, resolve) }), axis,
|
|
74
|
+
minLength: length(enhanced, "minLength", 10), maxLength: length(enhanced, "maxLength", 90),
|
|
75
|
+
gradient: flag(enhanced, "gradient", true), showValue: flag(enhanced, "showValue", showValue) };
|
|
76
|
+
}
|