@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,89 @@
|
|
|
1
|
+
import type { WorkbookShapeStyle } from "@quirekit/workbook";
|
|
2
|
+
import type { Element } from "@xmldom/xmldom";
|
|
3
|
+
import { hasKnownAttributes, hasKnownChildren } from "../../opc/shape";
|
|
4
|
+
import { child, children, readIndex } from "../../opc/xml";
|
|
5
|
+
import { drawingMainNamespace } from "../namespaces";
|
|
6
|
+
import { worksheetShapeColor } from "./paint";
|
|
7
|
+
import type { XlsxWorksheetShapeTheme } from "./types";
|
|
8
|
+
|
|
9
|
+
const horizontal = { l: "left", ctr: "center", r: "right" } as const;
|
|
10
|
+
const vertical = { t: "top", ctr: "center", b: "bottom" } as const;
|
|
11
|
+
|
|
12
|
+
/** @param node - Native uniform character properties. @param style - Paragraph's effective defaults.
|
|
13
|
+
* @param theme - Source workbook palette. @returns A uniform text style, if no rich effects would be lost. */
|
|
14
|
+
function runStyle(node: Element | undefined, style: WorkbookShapeStyle, theme: XlsxWorksheetShapeTheme): WorkbookShapeStyle | undefined {
|
|
15
|
+
if (!node) return style;
|
|
16
|
+
if (!hasKnownAttributes(node, ["lang", "altLang", "dirty", "sz", "b", "i"])
|
|
17
|
+
|| !hasKnownChildren(node, ["solidFill", "latin", "ea", "cs"])) return;
|
|
18
|
+
const authoredSize = readIndex(node, "sz"), fill = child(node, "solidFill");
|
|
19
|
+
const bold = node.getAttribute("b"), italic = node.getAttribute("i");
|
|
20
|
+
if (node.hasAttribute("sz") && authoredSize === undefined || [bold, italic].some(value => !["", null, "0", "1", "true", "false"].includes(value))) return;
|
|
21
|
+
const faces = children(node).filter(member => ["latin", "ea", "cs"].includes(member.localName ?? ""));
|
|
22
|
+
if (faces.some(member => !hasKnownAttributes(member, ["typeface"]) || !hasKnownChildren(member, []))) return;
|
|
23
|
+
const names = new Set(faces.map(member => member.getAttribute("typeface")).filter(Boolean));
|
|
24
|
+
if (names.size > 1) return;
|
|
25
|
+
const name = names.values().next().value;
|
|
26
|
+
const family = name === "+mn-lt" ? theme.fonts.minor : name === "+mj-lt" ? theme.fonts.major : name ?? style.font;
|
|
27
|
+
const color = fill ? worksheetShapeColor(fill, theme) : style.color;
|
|
28
|
+
if (!color || fill && !hasKnownAttributes(fill, [])) return;
|
|
29
|
+
return { ...style, ...(family && { font: family }), color, size: authoredSize === undefined ? style.size : authoredSize / 100,
|
|
30
|
+
...(bold && { bold: bold === "1" || bold === "true" }), ...(italic && { italic: italic === "1" || italic === "true" }) };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** @param left - First rendered span. @param right - Another span. @returns Whether both can share one uniform style. */
|
|
34
|
+
function sameTextStyle(left: WorkbookShapeStyle, right: WorkbookShapeStyle): boolean {
|
|
35
|
+
return left.color === right.color && left.font === right.font && left.size === right.size
|
|
36
|
+
&& Boolean(left.bold) === Boolean(right.bold) && Boolean(left.italic) === Boolean(right.italic) && left.horizontal === right.horizontal;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** @param body - Standard text body. @param style - Previously resolved paint and base typography. @param theme - Native color context.
|
|
40
|
+
* @returns Plain paragraphs and a uniform paint description. */
|
|
41
|
+
export function readWorksheetShapeText(body: Element | undefined, style: WorkbookShapeStyle, theme: XlsxWorksheetShapeTheme) {
|
|
42
|
+
if (!body) return { text: "", style };
|
|
43
|
+
if (!hasKnownAttributes(body, []) || children(body).some(node => node.namespaceURI !== drawingMainNamespace
|
|
44
|
+
|| !["bodyPr", "lstStyle", "p"].includes(node.localName ?? ""))) return;
|
|
45
|
+
const props = child(body, "bodyPr"), list = child(body, "lstStyle");
|
|
46
|
+
if (!props || !hasKnownAttributes(props, ["wrap", "rtlCol", "anchor", "anchorCtr", "vertOverflow", "horzOverflow"])
|
|
47
|
+
|| !hasKnownChildren(props, ["noAutofit"]) || list && (!hasKnownAttributes(list, []) || !hasKnownChildren(list, []))) return;
|
|
48
|
+
const autofit = child(props, "noAutofit");
|
|
49
|
+
if (autofit && (!hasKnownAttributes(autofit, []) || !hasKnownChildren(autofit, []))) return;
|
|
50
|
+
if (!["", "square"].includes(props.getAttribute("wrap") ?? "") || !["", "0", "false"].includes(props.getAttribute("rtlCol") ?? "")
|
|
51
|
+
|| !["", "clip"].includes(props.getAttribute("vertOverflow") ?? "") || !["", "clip"].includes(props.getAttribute("horzOverflow") ?? "")) return;
|
|
52
|
+
const anchor = props.getAttribute("anchor") || "t";
|
|
53
|
+
const centered = props.getAttribute("anchorCtr") || "0";
|
|
54
|
+
if (!Object.hasOwn(vertical, anchor) || !["0", "1", "true", "false"].includes(centered)) return;
|
|
55
|
+
const base: WorkbookShapeStyle = { ...style, vertical: vertical[anchor as keyof typeof vertical],
|
|
56
|
+
horizontal: centered === "1" || centered === "true" ? "center" : "left" };
|
|
57
|
+
let uniform: WorkbookShapeStyle | undefined, emptyStyle: WorkbookShapeStyle | undefined;
|
|
58
|
+
const paragraphs: string[] = [];
|
|
59
|
+
for (const paragraph of children(body, "p")) {
|
|
60
|
+
if (!hasKnownAttributes(paragraph, []) || children(paragraph).some(node => node.namespaceURI !== drawingMainNamespace
|
|
61
|
+
|| !["pPr", "r", "br", "endParaRPr"].includes(node.localName ?? ""))) return;
|
|
62
|
+
const paragraphProps = child(paragraph, "pPr");
|
|
63
|
+
const align = paragraphProps?.getAttribute("algn");
|
|
64
|
+
if (paragraphProps && (!hasKnownAttributes(paragraphProps, ["algn"]) || !hasKnownChildren(paragraphProps, ["defRPr"]))
|
|
65
|
+
|| align && !Object.hasOwn(horizontal, align)) return;
|
|
66
|
+
const paragraphStyle = runStyle(paragraphProps && child(paragraphProps, "defRPr"),
|
|
67
|
+
align ? { ...base, horizontal: horizontal[align as keyof typeof horizontal] } : base, theme);
|
|
68
|
+
if (!paragraphStyle) return;
|
|
69
|
+
let text = "";
|
|
70
|
+
for (const node of children(paragraph)) {
|
|
71
|
+
if (node.localName === "pPr") continue;
|
|
72
|
+
if (node.localName === "endParaRPr") {
|
|
73
|
+
emptyStyle = runStyle(node, paragraphStyle, theme);
|
|
74
|
+
if (!emptyStyle) return;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (!hasKnownAttributes(node, []) || !hasKnownChildren(node, node.localName === "br" ? ["rPr"] : ["rPr", "t"])) return;
|
|
78
|
+
const content = child(node, "t"), span = runStyle(child(node, "rPr"), paragraphStyle, theme);
|
|
79
|
+
if (!span || content && !hasKnownChildren(content, [])) return;
|
|
80
|
+
const part = node.localName === "br" ? "\n" : content?.textContent ?? "";
|
|
81
|
+
if (!part) continue;
|
|
82
|
+
if (uniform && !sameTextStyle(uniform, span)) return;
|
|
83
|
+
uniform = span;
|
|
84
|
+
text += part;
|
|
85
|
+
}
|
|
86
|
+
paragraphs.push(text);
|
|
87
|
+
}
|
|
88
|
+
return { text: paragraphs.join("\n"), style: uniform ?? emptyStyle ?? base };
|
|
89
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
|
|
3
|
+
/** Resolved palette and theme styles used by native worksheet shapes. */
|
|
4
|
+
export interface XlsxWorksheetShapeTheme {
|
|
5
|
+
/** SpreadsheetML theme colors in storage order. */
|
|
6
|
+
readonly colors: readonly string[];
|
|
7
|
+
/** Format scheme's regular fills, indexed by fillRef. */
|
|
8
|
+
readonly fills: readonly Element[];
|
|
9
|
+
/** Format scheme's outlines, indexed by lnRef. */
|
|
10
|
+
readonly lines: readonly Element[];
|
|
11
|
+
/** The optional display font of each scheme face. */
|
|
12
|
+
readonly fonts: Readonly<Partial<Record<"major" | "minor", string>>>;
|
|
13
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { strToU8 } from "fflate";
|
|
3
|
+
import { children, parsePart } from "../opc/xml";
|
|
4
|
+
import { readChartSources } from "./sources";
|
|
5
|
+
|
|
6
|
+
describe("Native chart source references", () => {
|
|
7
|
+
it("resolves quoted local worksheet names, deduplicates references and excludes external or dynamic sources", () => {
|
|
8
|
+
const chart = parsePart(strToU8(`<plot>
|
|
9
|
+
<ser>
|
|
10
|
+
<cat><strRef><f>'Q1! O''Brien'!$B$3:$B$6</f></strRef></cat>
|
|
11
|
+
<val><numRef><f>$G$3:$G$6</f></numRef></val>
|
|
12
|
+
</ser>
|
|
13
|
+
<ser>
|
|
14
|
+
<cat><strRef><f>'q1! o''brien'!B3:B6</f></strRef></cat>
|
|
15
|
+
<val><numRef><f>'[external.xlsx]Q1'!$D$3:$D$6</f></numRef></val>
|
|
16
|
+
</ser>
|
|
17
|
+
<ser>
|
|
18
|
+
<val><numRef><f>DemandRange</f></numRef></val>
|
|
19
|
+
</ser>
|
|
20
|
+
</plot>`), "chart.xml").documentElement!;
|
|
21
|
+
const sources = readChartSources(children(chart, "ser"), "current", new Map([["q1! o'brien", "quarter"]]));
|
|
22
|
+
expect(sources).toEqual([
|
|
23
|
+
{ role: "categories", range: { sheetId: "quarter", startRow: 2, endRow: 5, startColumn: 1, endColumn: 1 } },
|
|
24
|
+
{ role: "values", range: { sheetId: "current", startRow: 2, endRow: 5, startColumn: 6, endColumn: 6 } }
|
|
25
|
+
]);
|
|
26
|
+
});
|
|
27
|
+
});
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { formatWorkbookRange, parseWorkbookRange, type WorkbookDrawingSource, type WorkbookRange } from "@quirekit/workbook";
|
|
3
|
+
import { child } from "../opc/xml";
|
|
4
|
+
|
|
5
|
+
/** @param source - ChartML range formula. @param defaultSheetId - Owning sheet for unqualified ranges.
|
|
6
|
+
* @param sheets - Sheet IDs by case-insensitive workbook name. @returns Resolved local A1 rectangle. */
|
|
7
|
+
export function readChartRange(source: string, defaultSheetId: string, sheets: ReadonlyMap<string, string>): WorkbookRange | null {
|
|
8
|
+
const formula = source.trim().replace(/^=/u, "");
|
|
9
|
+
const separator = formula.lastIndexOf("!");
|
|
10
|
+
let sheetId = defaultSheetId;
|
|
11
|
+
if (separator !== -1) {
|
|
12
|
+
const qualifier = formula.slice(0, separator);
|
|
13
|
+
if (/[\[\]]/u.test(qualifier)) return null;
|
|
14
|
+
const quoted = /^'((?:[^']|'')+)'$/u.exec(qualifier);
|
|
15
|
+
const name = quoted ? quoted[1]!.replaceAll("''", "'") : qualifier;
|
|
16
|
+
const target = sheets.get(name.toLowerCase());
|
|
17
|
+
if (!target) return null;
|
|
18
|
+
sheetId = target;
|
|
19
|
+
}
|
|
20
|
+
try { return parseWorkbookRange(sheetId, formula.slice(separator + 1)); }
|
|
21
|
+
catch { return null; }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** @param series - Source series of the accepted plot. @param sheetId - Sheet owning the drawing.
|
|
25
|
+
* @param sheets - Workbook sheet IDs by name. @returns Distinct local range bindings in series order. */
|
|
26
|
+
export function readChartSources(series: readonly Element[], sheetId: string, sheets: ReadonlyMap<string, string>): readonly WorkbookDrawingSource[] {
|
|
27
|
+
const result: WorkbookDrawingSource[] = [];
|
|
28
|
+
const seen = new Set<string>();
|
|
29
|
+
for (const item of series) {
|
|
30
|
+
for (const [key, role] of [["cat", "categories"], ["val", "values"]] as const) {
|
|
31
|
+
const data = child(item, key);
|
|
32
|
+
const reference = data && (child(data, "numRef") ?? child(data, "strRef"));
|
|
33
|
+
const formula = reference && child(reference, "f")?.textContent;
|
|
34
|
+
const range = formula && readChartRange(formula, sheetId, sheets);
|
|
35
|
+
if (!range) continue;
|
|
36
|
+
const identity = JSON.stringify([role, range.sheetId, formatWorkbookRange(range)]);
|
|
37
|
+
if (seen.has(identity)) continue;
|
|
38
|
+
seen.add(identity);
|
|
39
|
+
result.push({ role, range });
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { WorkbookChart, WorkbookFloatingPicture, WorkbookFloatingShape } from "@quirekit/workbook";
|
|
2
|
+
|
|
3
|
+
/** Native part and frame identities for a chart mapped to the workbook model. */
|
|
4
|
+
export interface XlsxChartPart {
|
|
5
|
+
/** Chart definition decoded from its native structures. */
|
|
6
|
+
readonly chart: WorkbookChart;
|
|
7
|
+
/** Internal package member holding the chart. */
|
|
8
|
+
readonly path: string;
|
|
9
|
+
/** Relationship in the drawing referring to the chart part. */
|
|
10
|
+
readonly relationshipId: string;
|
|
11
|
+
/** Non-visual numeric identity local to the drawing. */
|
|
12
|
+
readonly frameId: number;
|
|
13
|
+
/** Name retained in the editing application's object list. */
|
|
14
|
+
readonly frameName: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** A floating picture and its local image relationship. */
|
|
18
|
+
export interface XlsxPicturePart {
|
|
19
|
+
/** Editable picture definition. */
|
|
20
|
+
readonly picture: WorkbookFloatingPicture;
|
|
21
|
+
/** Local raster part, potentially shared by other drawings. */
|
|
22
|
+
readonly path: string;
|
|
23
|
+
/** Drawing relationship for the asset. */
|
|
24
|
+
readonly relationshipId: string;
|
|
25
|
+
/** Non-visual numeric identity local to this drawing. */
|
|
26
|
+
readonly frameId: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Native frame for a standard shape or text box. */
|
|
30
|
+
export interface XlsxShapePart {
|
|
31
|
+
/** Editable shape with local worksheet coordinates. */
|
|
32
|
+
readonly shape: WorkbookFloatingShape;
|
|
33
|
+
/** Non-visual numeric identity local to this drawing. */
|
|
34
|
+
readonly frameId: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** One exclusively owned drawing with editable objects. */
|
|
38
|
+
export interface XlsxDrawingGraph {
|
|
39
|
+
/** Worksheet part that references the drawing. */
|
|
40
|
+
readonly worksheetPath: string;
|
|
41
|
+
/** Drawing part referenced from the worksheet. */
|
|
42
|
+
readonly drawingPath: string;
|
|
43
|
+
/** Relationship in the worksheet referring to the drawing. */
|
|
44
|
+
readonly relationshipId: string;
|
|
45
|
+
/** Chart frames in paint order. */
|
|
46
|
+
readonly parts: readonly XlsxChartPart[];
|
|
47
|
+
/** Images associated with the same drawing. */
|
|
48
|
+
readonly pictures: readonly XlsxPicturePart[];
|
|
49
|
+
/** Shapes and text boxes in native order. */
|
|
50
|
+
readonly shapes: readonly XlsxShapePart[];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Native frames which can be serialized together in one drawing. */
|
|
54
|
+
export type XlsxDrawingFrame = XlsxChartPart | XlsxPicturePart | XlsxShapePart;
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import { openWorkbook, parseWorkbookRange } from "@quirekit/workbook";
|
|
5
|
+
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
|
|
6
|
+
import { expect, test } from "vitest";
|
|
7
|
+
import { createXlsx } from "../create";
|
|
8
|
+
import { openXlsx } from "../package/read";
|
|
9
|
+
|
|
10
|
+
const drawing = "xl/drawings/drawing1.xml";
|
|
11
|
+
|
|
12
|
+
/** @param targetId - Optional native drawing identity referenced from the start.
|
|
13
|
+
* @returns A worksheet with a WPS-style themed connector. */
|
|
14
|
+
function themedConnector(targetId?: number): Uint8Array {
|
|
15
|
+
const source = readFileSync(new URL("../../test/fixtures/native-worksheet-shapes.xlsx", import.meta.url));
|
|
16
|
+
const zip = unzipSync(source);
|
|
17
|
+
const xml = strFromU8(zip[drawing]!);
|
|
18
|
+
const markers = `<xdr:from><xdr:col>2</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>4</xdr:row><xdr:rowOff>28575</xdr:rowOff></xdr:from>
|
|
19
|
+
<xdr:to><xdr:col>5</xdr:col><xdr:colOff>9525</xdr:colOff><xdr:row>4</xdr:row><xdr:rowOff>28575</xdr:rowOff></xdr:to>`;
|
|
20
|
+
const binding = targetId === undefined ? "" : `<a:stCxn id="${targetId}" idx="3"/>`;
|
|
21
|
+
const connector = `<xdr:twoCellAnchor>${markers}<xdr:cxnSp>
|
|
22
|
+
<xdr:nvCxnSpPr><xdr:cNvPr id="50" name="Review line"/><xdr:cNvCxnSpPr>${binding}</xdr:cNvCxnSpPr></xdr:nvCxnSpPr>
|
|
23
|
+
<xdr:spPr><a:xfrm flipH="1"/><a:prstGeom prst="bentConnector3"><a:avLst/></a:prstGeom>
|
|
24
|
+
<a:ln><a:headEnd type="none"/><a:tailEnd type="arrow" w="sm" len="lg"/></a:ln></xdr:spPr>
|
|
25
|
+
<xdr:style><a:lnRef idx="2"><a:srgbClr val="305080"/></a:lnRef></xdr:style>
|
|
26
|
+
</xdr:cxnSp><xdr:clientData/></xdr:twoCellAnchor>`;
|
|
27
|
+
zip[drawing] = strToU8(xml.replace(/<\/(?:\w+:)?wsDr>$/u, end => connector + end));
|
|
28
|
+
return zipSync(zip);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
test("reads a flat themed native connector, preserves its unchanged package and reopens a reversed vertical line", async () => {
|
|
32
|
+
const bytes = themedConnector(), original = openXlsx("Connector", bytes);
|
|
33
|
+
expect(original.restrictions).toEqual([]);
|
|
34
|
+
const line = original.snapshot.shapes!.find(shape => shape.connector)!;
|
|
35
|
+
expect(line).toMatchObject({ preset: "bentConnector3", style: { stroke: "#305080", strokeWidth: 8 / 3, fill: null },
|
|
36
|
+
connector: { flipHorizontal: true, tailEnd: { type: "arrow", width: "sm", length: "lg" } },
|
|
37
|
+
anchor: { from: { row: 4, column: 2, y: 3 }, to: { row: 4, column: 5, y: 3 } } });
|
|
38
|
+
expect(original.write(original.snapshot)).toEqual(bytes);
|
|
39
|
+
const workbook = await openWorkbook(original.snapshot);
|
|
40
|
+
try {
|
|
41
|
+
const target = parseWorkbookRange(line.anchor.sheetId, "F5:F10");
|
|
42
|
+
const next = workbook.prepare({ operationId: "move-native-connector", baseRevision: 0, commands: [{
|
|
43
|
+
name: "updateFloatingShape", target, params: { id: line.id,
|
|
44
|
+
endpoints: { start: { cell: "F10", y: 3 }, end: { cell: "F5", y: 3 } }, style: { stroke: "#405080" } }
|
|
45
|
+
}] });
|
|
46
|
+
await workbook.commit(next.id);
|
|
47
|
+
const saved = original.write(workbook.snapshot());
|
|
48
|
+
const xml = strFromU8(unzipSync(saved)[drawing]!);
|
|
49
|
+
expect(xml).toContain('<a:xfrm flipV="1"><a:off');
|
|
50
|
+
expect(xml).toMatch(/<a:ext cx="0" cy="[1-9]\d*"\/>/u);
|
|
51
|
+
expect(xml).toContain('<a:tailEnd type="arrow" w="sm" len="lg"/>');
|
|
52
|
+
const restored = openXlsx("Reopened", saved);
|
|
53
|
+
expect(restored.restrictions).toEqual([]);
|
|
54
|
+
expect(restored.snapshot.shapes!.find(shape => shape.id === line.id)).toMatchObject({
|
|
55
|
+
anchor: { from: { row: 4, column: 5, y: 3 }, to: { row: 9, column: 5, y: 3 } },
|
|
56
|
+
connector: { flipVertical: true, tailEnd: line.connector?.tailEnd }, style: { stroke: "#405080" }
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
const fresh = openXlsx("Fresh", createXlsx(workbook.snapshot()));
|
|
60
|
+
expect(fresh.snapshot.shapes!.find(shape => shape.id === line.id)?.anchor).toEqual(restored.snapshot.shapes!.find(shape => shape.id === line.id)?.anchor);
|
|
61
|
+
|
|
62
|
+
await workbook.commit(workbook.prepare({ operationId: "rotate-flat-connector", baseRevision: workbook.revision, commands: [{
|
|
63
|
+
name: "updateFloatingShape", target, params: { id: line.id, rotation: 90 }
|
|
64
|
+
}] }).id);
|
|
65
|
+
const turned = openXlsx("Rotated connector", original.write(workbook.snapshot()));
|
|
66
|
+
expect(turned.restrictions).toEqual([]);
|
|
67
|
+
expect(turned.snapshot.shapes!.find(shape => shape.id === line.id)).toEqual(workbook.shapes().find(shape => shape.id === line.id));
|
|
68
|
+
} finally { await workbook.close(); }
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
test("maps a native connector's forward reference to a stable target and writes it after rotation", async () => {
|
|
72
|
+
const zip = unzipSync(themedConnector(2));
|
|
73
|
+
const xml = strFromU8(zip[drawing]!);
|
|
74
|
+
const connectorFrame = xml.slice(xml.lastIndexOf("<xdr:twoCellAnchor>"), xml.lastIndexOf("</xdr:wsDr>"));
|
|
75
|
+
expect(connectorFrame).toContain("Review line");
|
|
76
|
+
zip[drawing] = strToU8(xml.replace(connectorFrame, "").replace(/(<(?:\w+:)?wsDr\b[^>]*>)/u, root => root + connectorFrame));
|
|
77
|
+
const bytes = zipSync(zip), file = openXlsx("Attached", bytes);
|
|
78
|
+
expect(file.restrictions).toEqual([]);
|
|
79
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
80
|
+
const attached = file.snapshot.shapes!.find(shape => shape.connector)!;
|
|
81
|
+
const text = file.snapshot.shapes!.find(shape => shape.preset === "textBox")!;
|
|
82
|
+
expect(attached.connector?.startConnection).toEqual({ shapeId: text.id, site: 3 });
|
|
83
|
+
expect(attached.order).toBeLessThan(text.order);
|
|
84
|
+
const workbook = await openWorkbook(file.snapshot, { appearance: file.appearance });
|
|
85
|
+
try {
|
|
86
|
+
const shapeRange = parseWorkbookRange(text.anchor.sheetId, "B2");
|
|
87
|
+
const proposal = workbook.prepare({ operationId: "turn-bound-textbox", baseRevision: 0,
|
|
88
|
+
commands: [{ name: "updateFloatingShape", target: shapeRange, params: { id: text.id, rotation: 90 } }] });
|
|
89
|
+
await workbook.commit(proposal.id);
|
|
90
|
+
const saved = file.write(workbook.snapshot());
|
|
91
|
+
const native = strFromU8(unzipSync(saved)[drawing]!);
|
|
92
|
+
expect(native).toContain('<a:stCxn id="2" idx="3"/>');
|
|
93
|
+
expect(native).toContain('<a:xfrm rot="5400000">');
|
|
94
|
+
const reopened = openXlsx("Rotated", saved);
|
|
95
|
+
expect(reopened.restrictions).toEqual([]);
|
|
96
|
+
expect(reopened.snapshot.shapes!.find(shape => shape.id === attached.id)?.connector?.startConnection).toEqual({ shapeId: text.id, site: 3 });
|
|
97
|
+
|
|
98
|
+
const detach = workbook.prepare({ operationId: "detach-bound-textbox", baseRevision: workbook.revision,
|
|
99
|
+
commands: [{ name: "updateFloatingShape", target: shapeRange, params: { id: attached.id, connector: { startConnection: null } } }] });
|
|
100
|
+
await workbook.commit(detach.id);
|
|
101
|
+
const free = file.write(workbook.snapshot());
|
|
102
|
+
expect(strFromU8(unzipSync(free)[drawing]!)).not.toContain("<a:stCxn");
|
|
103
|
+
expect(openXlsx("Detached", free).snapshot.shapes!.find(shape => shape.id === attached.id)?.connector).toBeDefined();
|
|
104
|
+
} finally { await workbook.close(); }
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
test("previews a missing target without dropping its native binding from the original package", () => {
|
|
108
|
+
const bytes = themedConnector(901), file = openXlsx("Unresolved attachment", bytes);
|
|
109
|
+
expect(file.restrictions).toContain("绘图或图表");
|
|
110
|
+
expect(file.snapshot.shapes?.some(shape => shape.connector)).not.toBe(true);
|
|
111
|
+
expect(file.shapes?.find(shape => shape.connector)).toMatchObject({ preset: "bentConnector3", connector: { flipHorizontal: true } });
|
|
112
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test("writes coincident connection sites and reopens them as an editable relation", async () => {
|
|
116
|
+
const seed = openXlsx("Bound point", themedConnector());
|
|
117
|
+
const workbook = await openWorkbook(seed.snapshot, { appearance: seed.appearance });
|
|
118
|
+
const target = workbook.shapes().find(shape => shape.preset === "textBox")!;
|
|
119
|
+
const binding = { shapeId: target.id, site: 0 };
|
|
120
|
+
try {
|
|
121
|
+
await workbook.commit(workbook.prepare({
|
|
122
|
+
operationId: "coincident-bound-endpoints", baseRevision: 0, commands: [{
|
|
123
|
+
name: "createFloatingShape", target: parseWorkbookRange(target.anchor.sheetId, "A1"), params: {
|
|
124
|
+
name: "Bound point", preset: "line", connector: { startConnection: binding, endConnection: binding }
|
|
125
|
+
}
|
|
126
|
+
}]
|
|
127
|
+
}).id);
|
|
128
|
+
const line = workbook.shapes().find(shape => shape.name === "Bound point")!;
|
|
129
|
+
expect(line.anchor.from).toEqual(line.anchor.to);
|
|
130
|
+
const saved = seed.write(workbook.snapshot());
|
|
131
|
+
const reopened = openXlsx("Bound point", saved);
|
|
132
|
+
expect(reopened.restrictions).toEqual([]);
|
|
133
|
+
expect(reopened.snapshot.shapes!.find(shape => shape.id === line.id)?.connector).toEqual({ startConnection: binding, endConnection: binding });
|
|
134
|
+
} finally { await workbook.close(); }
|
|
135
|
+
});
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import { openWorkbook, parseWorkbookRange } from "@quirekit/workbook";
|
|
5
|
+
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
|
|
6
|
+
import { expect, test } from "vitest";
|
|
7
|
+
import { openXlsx } from "../package/read";
|
|
8
|
+
|
|
9
|
+
test("keeps producer-native text boxes and themed WPS shapes editable", async () => {
|
|
10
|
+
const native = new Uint8Array(readFileSync(new URL("../../test/fixtures/native-worksheet-shapes.xlsx", import.meta.url)));
|
|
11
|
+
const parts = unzipSync(native), drawingPart = "xl/drawings/drawing1.xml";
|
|
12
|
+
parts[drawingPart] = strToU8(strFromU8(parts[drawingPart]!).replace("<a:xfrm>", '<a:xfrm rot="1350000">'));
|
|
13
|
+
const bytes = zipSync(parts);
|
|
14
|
+
const file = openXlsx("Shapes", bytes);
|
|
15
|
+
expect(file.restrictions).toEqual([]);
|
|
16
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
17
|
+
const [box, rectangle] = file.snapshot.shapes!;
|
|
18
|
+
expect(box).toMatchObject({ preset: "textBox", text: "订单说明\n本期小结", order: 0, rotation: 22.5,
|
|
19
|
+
style: { fill: "#CDEADE", stroke: "#087F66", strokeWidth: 2, color: "#243B53", font: "Arial", size: 13,
|
|
20
|
+
bold: true, horizontal: "center", vertical: "center" } });
|
|
21
|
+
expect(rectangle).toMatchObject({ name: "矩形 1", preset: "rect", order: 1, style: { fill: "#4F81BD" } });
|
|
22
|
+
const session = await openWorkbook(file.snapshot);
|
|
23
|
+
try {
|
|
24
|
+
const target = parseWorkbookRange(box!.anchor.sheetId, "E5:G9");
|
|
25
|
+
const candidate = session.prepare({ operationId: "edit-native-shape", baseRevision: 0, commands: [{
|
|
26
|
+
name: "updateFloatingShape", target, params: { id: box!.id, text: "来源:订单\n已复核", style: { italic: true }, rotation: -22.5,
|
|
27
|
+
position: { from: { cell: "E5" }, to: { cell: "G10" } } }
|
|
28
|
+
}] });
|
|
29
|
+
expect(session.shapes()[0]?.text).toBe("订单说明\n本期小结");
|
|
30
|
+
await session.commit(candidate.id);
|
|
31
|
+
const saved = openXlsx("Edited", file.write(session.snapshot()));
|
|
32
|
+
expect(saved.restrictions).toEqual([]);
|
|
33
|
+
expect(saved.snapshot.shapes?.[0]).toMatchObject({ id: box!.id, text: "来源:订单\n已复核", rotation: 337.5, style: { bold: true, italic: true },
|
|
34
|
+
anchor: { from: { row: 4, column: 4, x: 0, y: 0 }, to: { row: 9, column: 6, x: 0, y: 0 } } });
|
|
35
|
+
expect(saved.snapshot.shapes?.[1]).toMatchObject({ id: rectangle!.id, order: 1 });
|
|
36
|
+
await session.undo("undo-native-shape");
|
|
37
|
+
expect(session.shapes()).toEqual([box, rectangle]);
|
|
38
|
+
} finally { await session.close(); }
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test("shares one native drawing part with pictures and charts without changing their media or ordering", async () => {
|
|
42
|
+
const bytes = Uint8Array.from(readFileSync(new URL("../../test/fixtures/native-floating-pictures.xlsx", import.meta.url)));
|
|
43
|
+
const file = openXlsx("Mixed drawings", bytes);
|
|
44
|
+
const [sheet] = file.snapshot.sheets;
|
|
45
|
+
const session = await openWorkbook(file.snapshot);
|
|
46
|
+
try {
|
|
47
|
+
const target = parseWorkbookRange(sheet!.id, "B3:D7");
|
|
48
|
+
const candidate = session.prepare({ operationId: "mixed-drawing", baseRevision: 0, commands: [
|
|
49
|
+
{ name: "createFloatingShape", target, params: { preset: "diamond", name: "Label" } },
|
|
50
|
+
{ name: "createChart", target: parseWorkbookRange(sheet!.id, "A1:A3"), params: { type: "column", title: "Alongside shapes" } }
|
|
51
|
+
] });
|
|
52
|
+
await session.commit(candidate.id);
|
|
53
|
+
const [shape] = session.shapes();
|
|
54
|
+
const edited = openXlsx("Mixed drawings", file.write(session.snapshot()));
|
|
55
|
+
expect(edited.restrictions).toEqual([]);
|
|
56
|
+
expect(edited.snapshot.shapes?.[0]).toMatchObject({ id: shape!.id, order: shape!.order, preset: "diamond" });
|
|
57
|
+
expect(edited.snapshot.pictures).toEqual(session.pictures());
|
|
58
|
+
expect(edited.snapshot.charts).toEqual(session.charts());
|
|
59
|
+
expect(edited.snapshot.imageAssets).toEqual(file.snapshot.imageAssets);
|
|
60
|
+
} finally { await session.close(); }
|
|
61
|
+
});
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { WorkbookDrawingAnchor, WorkbookDrawingPoint } from "@quirekit/workbook";
|
|
2
|
+
import { creationIdExtension, emuPerCssPixel } from "../namespaces";
|
|
3
|
+
|
|
4
|
+
/** @param kind - Native corner name. @param point - Workbook cell and CSS offset. @returns DrawingML marker in EMU. */
|
|
5
|
+
function marker(kind: "from" | "to", { row, column, x, y }: WorkbookDrawingPoint): string {
|
|
6
|
+
return `<xdr:${kind}><xdr:col>${column}</xdr:col><xdr:colOff>${Math.round(x * emuPerCssPixel)}</xdr:colOff><xdr:row>${row}</xdr:row><xdr:rowOff>${Math.round(y * emuPerCssPixel)}</xdr:rowOff></xdr:${kind}>`;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** @param id - Persistent object ID. @returns The Office drawing creation ID extension. */
|
|
10
|
+
export function drawingCreationIdXml(id: string): string {
|
|
11
|
+
return `<a:extLst><a:ext uri="${creationIdExtension}"><a16:creationId id="{${id.toUpperCase()}}"/></a:ext></a:extLst>`;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** @param anchor - Exact cell placement. @param content - Encoded shape or graphic frame. @returns Its native two-cell anchor. */
|
|
15
|
+
export function drawingAnchorXml({ from, to }: WorkbookDrawingAnchor, content: string): string {
|
|
16
|
+
return `<xdr:twoCellAnchor>${marker("from", from)}${marker("to", to)}${content}<xdr:clientData/></xdr:twoCellAnchor>`;
|
|
17
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { WorkbookChartValueAxis, WorkbookChartValueScale } from "@quirekit/workbook";
|
|
2
|
+
import { chartValue as c } from "./text";
|
|
3
|
+
|
|
4
|
+
const axisIds = { primary: { category: 100, value: 200 }, secondary: { category: 300, value: 400 } } as const;
|
|
5
|
+
|
|
6
|
+
/** @param axis - Value scale used by the plot. @returns Native references to its category and value axes. */
|
|
7
|
+
export function chartAxisReferences(axis: WorkbookChartValueAxis): string {
|
|
8
|
+
const { category, value } = axisIds[axis];
|
|
9
|
+
return c("axId", category) + c("axId", value);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** @param axis - Value scale being written. @param horizontal - Whether the category axis runs vertically.
|
|
13
|
+
* @param scale - Authored bounds and numeric tick format. @returns Linked category and value axis declarations. */
|
|
14
|
+
export function writeChartAxes(axis: WorkbookChartValueAxis, horizontal: boolean, scale?: WorkbookChartValueScale): string {
|
|
15
|
+
const ids = axisIds[axis];
|
|
16
|
+
const secondary = axis === "secondary";
|
|
17
|
+
const orientation = c("orientation", "minMax");
|
|
18
|
+
const bounds = (scale?.max === undefined ? "" : c("max", scale.max)) + (scale?.min === undefined ? "" : c("min", scale.min));
|
|
19
|
+
const ticks = c("majorTickMark", "none") + c("minorTickMark", "none") + c("tickLblPos", "nextTo");
|
|
20
|
+
const category = `<c:catAx>${c("axId", ids.category)}<c:scaling>${orientation}</c:scaling>${c("delete", secondary)}${c("axPos", horizontal ? "l" : "b")}${ticks}${c("crossAx", ids.value)}${c("crosses", "autoZero")}${c("auto", true)}${c("lblAlgn", "ctr")}${c("lblOffset", 100)}</c:catAx>`;
|
|
21
|
+
const value = `<c:valAx>${c("axId", ids.value)}<c:scaling>${orientation}${bounds}</c:scaling>${c("delete", false)}${c("axPos", horizontal ? "b" : secondary ? "r" : "l")}${secondary ? "" : "<c:majorGridlines/>"}<c:numFmt formatCode="${scale?.format ?? "General"}" sourceLinked="0"/>${ticks}${c("crossAx", ids.category)}${c("crosses", secondary ? "max" : "autoZero")}${c("crossBetween", "between")}</c:valAx>`;
|
|
22
|
+
return category + value;
|
|
23
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { strToU8 } from "fflate";
|
|
2
|
+
import {
|
|
3
|
+
isCircularWorkbookChart, workbookCombinationPlotGroups, type WorkbookChart, type WorkbookChartData,
|
|
4
|
+
type WorkbookChartType, type WorkbookChartValueAxis
|
|
5
|
+
} from "@quirekit/workbook";
|
|
6
|
+
import { chartNamespace, drawingMainNamespace } from "../namespaces";
|
|
7
|
+
import { chartAxisReferences, writeChartAxes } from "./axes";
|
|
8
|
+
import { chartSeriesXml } from "./series";
|
|
9
|
+
import { chartValue as c, chartXmlText } from "./text";
|
|
10
|
+
|
|
11
|
+
/** @param title - Authored plain text. @returns Native rich-text title with a paragraph per line. */
|
|
12
|
+
function titleXml(title: string): string {
|
|
13
|
+
return `<c:title><c:tx><c:rich><a:bodyPr/><a:lstStyle/>${title.split("\n").map(line =>
|
|
14
|
+
`<a:p><a:r><a:t xml:space="preserve">${chartXmlText(line)}</a:t></a:r></a:p>`).join("")}</c:rich></c:tx><c:layout/>${c("overlay", false)}</c:title>`;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** @param chart - Shared chart options. @param type - Native drawing group family. @param series - Its series records.
|
|
18
|
+
* @param axis - Value scale used by the group. @returns Native plot with a reference to its axes. */
|
|
19
|
+
function plotXml(chart: WorkbookChart, type: Exclude<WorkbookChartType, "combination">, series: string, axis: WorkbookChartValueAxis): string {
|
|
20
|
+
const circular = isCircularWorkbookChart(type);
|
|
21
|
+
const bars = type === "column" || type === "bar";
|
|
22
|
+
const family = bars ? "bar" : type;
|
|
23
|
+
const grouping = bars && chart.grouping === "standard" ? "clustered" : chart.grouping;
|
|
24
|
+
const labels = chart.dataLabels ? `<c:dLbls>${c("showLegendKey", false)}${c("showVal", true)}${c("showCatName", circular)}${c("showSerName", false)}${c("showPercent", false)}</c:dLbls>` : "";
|
|
25
|
+
const kind = bars ? c("barDir", type === "bar" ? "bar" : "col") : "";
|
|
26
|
+
const options = circular ? c("firstSliceAng", 0) + (type === "doughnut" ? c("holeSize", 50) : "")
|
|
27
|
+
: bars ? c("gapWidth", 150) + (chart.grouping !== "standard" ? c("overlap", 100) : "") : "";
|
|
28
|
+
return `<c:${family}Chart>${kind}${circular ? "" : c("grouping", grouping)}${c("varyColors", circular)}${series}${labels}${options}${circular ? "" : chartAxisReferences(axis)}</c:${family}Chart>`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** @param chart - Native chart definition. @param data - Completed worksheet calculation. @param names - Sheet names.
|
|
32
|
+
* @returns Plot groups followed by their referenced axis declarations. */
|
|
33
|
+
function plotAreaXml(chart: WorkbookChart, data: WorkbookChartData, names: ReadonlyMap<string, string>): string {
|
|
34
|
+
const { type, grouping, valueAxes } = chart;
|
|
35
|
+
if (type !== "combination") {
|
|
36
|
+
const plot = plotXml(chart, type, chartSeriesXml(chart, data, names, type), "primary");
|
|
37
|
+
const scale = grouping === "percentStacked" ? { format: "0%" as const } : undefined;
|
|
38
|
+
return plot + (isCircularWorkbookChart(type) ? "" : writeChartAxes("primary", type === "bar", scale));
|
|
39
|
+
}
|
|
40
|
+
// Plot groups own the physical XML order. Series indices still address the whole chart.
|
|
41
|
+
const groups = workbookCombinationPlotGroups(chart.binding.series);
|
|
42
|
+
const plots = groups.map(({ type, axis, seriesIndices }) => plotXml(chart, type,
|
|
43
|
+
chartSeriesXml(chart, data, names, type, seriesIndices), axis)).join("");
|
|
44
|
+
const secondary = groups.some(group => group.axis === "secondary");
|
|
45
|
+
return plots + writeChartAxes("primary", false, valueAxes?.primary)
|
|
46
|
+
+ (secondary ? writeChartAxes("secondary", false, valueAxes?.secondary) : "");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** @param chart - Committed worksheet chart. @param data - Calculated chart data in the saved revision.
|
|
50
|
+
* @param names - Current worksheet names. @returns Independently editable native ChartML document. */
|
|
51
|
+
export function writeChartSpace(chart: WorkbookChart, data: WorkbookChartData, names: ReadonlyMap<string, string>): Uint8Array {
|
|
52
|
+
const plot = plotAreaXml(chart, data, names);
|
|
53
|
+
const title = chart.title ? titleXml(chart.title) : c("autoTitleDeleted", true);
|
|
54
|
+
const legend = chart.legend === "none" ? "" : `<c:legend>${c("legendPos", chart.legend[0]!)}<c:layout/>${c("overlay", false)}</c:legend>`;
|
|
55
|
+
return strToU8(`<c:chartSpace xmlns:c="${chartNamespace}" xmlns:a="${drawingMainNamespace}"><c:chart>${title}<c:plotArea><c:layout/>${plot}</c:plotArea>${legend}${c("plotVisOnly", !chart.showHidden)}${c("dispBlanksAs", chart.blankPolicy)}${c("showDLblsOverMax", false)}</c:chart></c:chartSpace>`);
|
|
56
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { strToU8 } from "fflate";
|
|
2
|
+
import { child, children, packageRelationshipNs, parsePart, relationshipNs, rootOf, spreadNs, writePart } from "../../opc/xml";
|
|
3
|
+
import { chartNamespace, creationIdNamespace, drawingMainNamespace, drawingNamespace } from "../namespaces";
|
|
4
|
+
import type { XlsxDrawingAxes } from "../placement/types";
|
|
5
|
+
import type { XlsxChartPart, XlsxDrawingFrame, XlsxPicturePart } from "../types";
|
|
6
|
+
import { drawingTransformXml, writeXlsxDrawingPlacement } from "../placement/transform";
|
|
7
|
+
import { drawingAnchorXml, drawingCreationIdXml } from "./anchor";
|
|
8
|
+
import { shapeFrame } from "./shapes";
|
|
9
|
+
import { chartXmlText } from "./text";
|
|
10
|
+
|
|
11
|
+
/** @param part - Planned native chart and its identifiers. @returns One anchored native graphic frame. */
|
|
12
|
+
function frame({ chart, frameId, frameName, relationshipId }: XlsxChartPart): string {
|
|
13
|
+
const identity = drawingCreationIdXml(chart.id);
|
|
14
|
+
const props = `<xdr:nvGraphicFramePr><xdr:cNvPr id="${frameId}" name="${chartXmlText(frameName)}">${identity}</xdr:cNvPr><xdr:cNvGraphicFramePr/></xdr:nvGraphicFramePr>`;
|
|
15
|
+
const transform = "<xdr:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"0\" cy=\"0\"/></xdr:xfrm>";
|
|
16
|
+
const content = `<a:graphic><a:graphicData uri="${chartNamespace}"><c:chart r:id="${chartXmlText(relationshipId)}"/></a:graphicData></a:graphic>`;
|
|
17
|
+
return drawingAnchorXml(chart.anchor, `<xdr:graphicFrame>${props}${transform}${content}</xdr:graphicFrame>`);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** @param part - Planned native floating picture. @param axes - Current worksheet geometry. @returns Anchored image with its internal raster relationship. */
|
|
21
|
+
function pictureFrame({ picture, frameId, relationshipId }: XlsxPicturePart, axes?: XlsxDrawingAxes): string {
|
|
22
|
+
const { id, name, alt, crop, flipHorizontal, flipVertical, anchor, rotation } = picture;
|
|
23
|
+
const description = alt ? ` descr="${chartXmlText(alt)}"` : "";
|
|
24
|
+
const props = `<xdr:nvPicPr><xdr:cNvPr id="${frameId}" name="${chartXmlText(name)}"${description}>${drawingCreationIdXml(id)}</xdr:cNvPr><xdr:cNvPicPr><a:picLocks noChangeAspect="1"/></xdr:cNvPicPr></xdr:nvPicPr>`;
|
|
25
|
+
const inset = crop ? `<a:srcRect l="${Math.round(crop.left * 100000)}" t="${Math.round(crop.top * 100000)}" r="${Math.round(crop.right * 100000)}" b="${Math.round(crop.bottom * 100000)}"/>` : "";
|
|
26
|
+
const fill = `<xdr:blipFill><a:blip r:embed="${chartXmlText(relationshipId)}"/>${inset}<a:stretch><a:fillRect/></a:stretch></xdr:blipFill>`;
|
|
27
|
+
const placement = writeXlsxDrawingPlacement(anchor, rotation, axes);
|
|
28
|
+
const guide = drawingTransformXml(rotation, placement.frame, flipHorizontal, flipVertical);
|
|
29
|
+
return drawingAnchorXml(placement.anchor, `<xdr:pic>${props}${fill}<xdr:spPr>${guide}<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></xdr:spPr></xdr:pic>`);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** @param parts - Native frames in painting order. @param axes - Saved worksheet dimensions for rotated objects. @returns The shared worksheet drawing. */
|
|
33
|
+
export function writeXlsxDrawing(parts: readonly XlsxDrawingFrame[], axes?: XlsxDrawingAxes): Uint8Array {
|
|
34
|
+
const targets = new Map(parts.flatMap(part => "shape" in part && !part.shape.connector ? [[part.shape.id, part] as const] : []));
|
|
35
|
+
return strToU8(`<xdr:wsDr xmlns:xdr="${drawingNamespace}" xmlns:a="${drawingMainNamespace}" xmlns:c="${chartNamespace}" xmlns:r="${relationshipNs}" xmlns:a16="${creationIdNamespace}">${parts.map(part => "shape" in part ? shapeFrame(part, targets, axes) : "picture" in part ? pictureFrame(part, axes) : frame(part)).join("")}</xdr:wsDr>`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** @param entries - Known chart and image relations. @returns A single OPC relationship per local ID. */
|
|
39
|
+
export function writeXlsxDrawingRelationships(entries: readonly (XlsxChartPart | XlsxPicturePart)[]): Uint8Array {
|
|
40
|
+
const links = new Map(entries.map(part => [part.relationshipId, part]));
|
|
41
|
+
return strToU8(`<Relationships xmlns="${packageRelationshipNs}">${[...links.values()].map(part =>
|
|
42
|
+
`<Relationship Id="${chartXmlText(part.relationshipId)}" Type="${relationshipNs}/${"picture" in part ? "image" : "chart"}" Target="/${chartXmlText(part.path.split("/").map(encodeURIComponent).join("/"))}"/>`
|
|
43
|
+
).join("")}</Relationships>`);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** @param parts - Staged package files. @param path - Worksheet member. @param id - Desired drawing relationship, or undefined to remove it. */
|
|
47
|
+
export function writeWorksheetDrawing(parts: Record<string, Uint8Array>, path: string, id: string | undefined): void {
|
|
48
|
+
const document = parsePart(parts[path], path);
|
|
49
|
+
const root = rootOf(document, spreadNs, "worksheet");
|
|
50
|
+
const previous = child(root, "drawing");
|
|
51
|
+
if ((previous?.getAttributeNS(relationshipNs, "id") ?? undefined) === id) return;
|
|
52
|
+
if (previous) root.removeChild(previous);
|
|
53
|
+
if (id) {
|
|
54
|
+
const member = document.createElementNS(spreadNs, "drawing");
|
|
55
|
+
member.setAttributeNS(relationshipNs, "r:id", id);
|
|
56
|
+
const after = children(root).find(node => ["legacyDrawing", "legacyDrawingHF", "picture", "oleObjects",
|
|
57
|
+
"controls", "webPublishItems", "tableParts", "extLst"].includes(node.localName ?? ""));
|
|
58
|
+
root.insertBefore(member, after ?? null);
|
|
59
|
+
}
|
|
60
|
+
parts[path] = writePart(document);
|
|
61
|
+
}
|