docxkeun 0.3.0 → 0.4.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.
@@ -0,0 +1,203 @@
1
+ /** The small Excel workbook a Word chart embeds, so "Edit Data" works. */
2
+ import { readZip, writeZip } from '../zip/zip.js';
3
+ import { DEFAULT_DECLARATION, el, localName, parseXml, serializeNode, text } from '../xml/index.js';
4
+ const SHEET = 'Sheet1';
5
+ const MAIN = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main';
6
+ const REL_NS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
7
+ const PKG_REL = 'http://schemas.openxmlformats.org/package/2006/relationships';
8
+ const CT = 'http://schemas.openxmlformats.org/package/2006/content-types';
9
+ const SML = 'application/vnd.openxmlformats-officedocument.spreadsheetml';
10
+ /** Zero-based column index to its letters: 0 is A, 25 is Z, 26 is AA. */
11
+ export function columnName(index) {
12
+ let n = index + 1;
13
+ let out = '';
14
+ while (n > 0) {
15
+ const rem = (n - 1) % 26;
16
+ out = String.fromCharCode(65 + rem) + out;
17
+ n = Math.floor((n - 1) / 26);
18
+ }
19
+ return out;
20
+ }
21
+ /** The sheet ranges a chart's formulas point at: series i sits in column i + 1. */
22
+ export function chartRanges(_seriesCount, categoryCount) {
23
+ const last = categoryCount + 1;
24
+ return {
25
+ categories: `${SHEET}!$A$2:$A$${last}`,
26
+ name: (i) => `${SHEET}!$${columnName(i + 1)}$1`,
27
+ values: (i) => `${SHEET}!$${columnName(i + 1)}$2:$${columnName(i + 1)}$${last}`,
28
+ };
29
+ }
30
+ function xml(root) {
31
+ return new TextEncoder().encode(`<?xml ${DEFAULT_DECLARATION}?>\r\n${serializeNode(root)}`);
32
+ }
33
+ function stringCell(ref, value) {
34
+ return el('c', { r: ref, t: 'inlineStr' }, [el('is', {}, [el('t', { 'xml:space': 'preserve' }, [text(value)])])]);
35
+ }
36
+ function numberCell(ref, value, style) {
37
+ return el('c', { r: ref, s: style || undefined }, [el('v', {}, [text(String(value))])]);
38
+ }
39
+ /** Excel's built-in number formats (ECMA-376 18.8.30) by format code; other codes get custom ids from 164. */
40
+ const BUILT_IN_FORMATS = {
41
+ General: 0, '0': 1, '0.00': 2, '#,##0': 3, '#,##0.00': 4, '0%': 9, '0.00%': 10, '0.00E+00': 11, '# ?/?': 12, '# ??/??': 13,
42
+ 'mm-dd-yy': 14, 'd-mmm-yy': 15, 'd-mmm': 16, 'mmm-yy': 17, 'h:mm AM/PM': 18, 'h:mm:ss AM/PM': 19, 'h:mm': 20, 'h:mm:ss': 21, 'm/d/yy h:mm': 22,
43
+ '#,##0 ;(#,##0)': 37, '#,##0 ;[Red](#,##0)': 38, '#,##0.00;(#,##0.00)': 39, '#,##0.00;[Red](#,##0.00)': 40, 'mm:ss': 45, '[h]:mm:ss': 46, 'mmss.0': 47,
44
+ '##0.0E+0': 48, '@': 49,
45
+ };
46
+ /** The number formats of a workbook: a cell style (index into cellXfs) per format code, and the custom formats they need. */
47
+ class NumberFormats {
48
+ /** numFmtId of each cell style after the default one (style 0, General). */
49
+ styles = [];
50
+ custom = [];
51
+ byCode = new Map();
52
+ /** The cell style for a format code (0 for General or none). */
53
+ style(code) {
54
+ if (code === undefined || code === '' || code === 'General')
55
+ return 0;
56
+ let style = this.byCode.get(code);
57
+ if (style === undefined) {
58
+ let id = BUILT_IN_FORMATS[code];
59
+ if (id === undefined) {
60
+ id = 164 + this.custom.length;
61
+ this.custom.push({ id, code });
62
+ }
63
+ this.styles.push(id);
64
+ style = this.styles.length;
65
+ this.byCode.set(code, style);
66
+ }
67
+ return style;
68
+ }
69
+ }
70
+ export async function workbookFor(data) {
71
+ const formats = new NumberFormats();
72
+ const categoryStyle = formats.style(data.categoryFormat);
73
+ const valueStyles = data.series.map((s) => formats.style(s.formatCode));
74
+ const rows = [];
75
+ const header = data.series.map((s, i) => stringCell(`${columnName(i + 1)}1`, s.name));
76
+ rows.push(el('row', { r: 1 }, header));
77
+ data.categories.forEach((category, r) => {
78
+ const row = r + 2;
79
+ const cells = [];
80
+ // A missing category (a gap in numbers or dates) has no cell.
81
+ if (typeof category === 'number')
82
+ cells.push(numberCell(`A${row}`, category, categoryStyle));
83
+ else if (category !== null)
84
+ cells.push(stringCell(`A${row}`, category));
85
+ data.series.forEach((s, i) => {
86
+ const v = s.values[r];
87
+ if (v !== null && v !== undefined)
88
+ cells.push(numberCell(`${columnName(i + 1)}${row}`, v, valueStyles[i]));
89
+ });
90
+ rows.push(el('row', { r: row }, cells));
91
+ });
92
+ const last = `${columnName(data.series.length)}${data.categories.length + 1}`;
93
+ const sheet = el('worksheet', { xmlns: MAIN }, [el('dimension', { ref: `A1:${last}` }), el('sheetData', {}, rows)]);
94
+ const workbook = el('workbook', { xmlns: MAIN, 'xmlns:r': REL_NS }, [
95
+ el('sheets', {}, [el('sheet', { name: SHEET, sheetId: 1, 'r:id': 'rId1' })]),
96
+ ]);
97
+ const styles = el('styleSheet', { xmlns: MAIN }, [
98
+ ...(formats.custom.length ? [el('numFmts', { count: formats.custom.length }, formats.custom.map((f) => el('numFmt', { numFmtId: f.id, formatCode: f.code })))] : []),
99
+ el('fonts', { count: 1 }, [el('font', {}, [el('sz', { val: 11 }), el('name', { val: 'Calibri' })])]),
100
+ el('fills', { count: 2 }, [
101
+ el('fill', {}, [el('patternFill', { patternType: 'none' })]),
102
+ el('fill', {}, [el('patternFill', { patternType: 'gray125' })]),
103
+ ]),
104
+ el('borders', { count: 1 }, [
105
+ el('border', {}, [el('left'), el('right'), el('top'), el('bottom'), el('diagonal')]),
106
+ ]),
107
+ el('cellStyleXfs', { count: 1 }, [el('xf', { numFmtId: 0, fontId: 0, fillId: 0, borderId: 0 })]),
108
+ el('cellXfs', { count: 1 + formats.styles.length }, [
109
+ el('xf', { numFmtId: 0, fontId: 0, fillId: 0, borderId: 0, xfId: 0 }),
110
+ ...formats.styles.map((id) => el('xf', { numFmtId: id, fontId: 0, fillId: 0, borderId: 0, xfId: 0, applyNumberFormat: 1 })),
111
+ ]),
112
+ ]);
113
+ const rootRels = el('Relationships', { xmlns: PKG_REL }, [
114
+ el('Relationship', { Id: 'rId1', Type: `${REL_NS}/officeDocument`, Target: 'xl/workbook.xml' }),
115
+ ]);
116
+ const workbookRels = el('Relationships', { xmlns: PKG_REL }, [
117
+ el('Relationship', { Id: 'rId1', Type: `${REL_NS}/worksheet`, Target: 'worksheets/sheet1.xml' }),
118
+ el('Relationship', { Id: 'rId2', Type: `${REL_NS}/styles`, Target: 'styles.xml' }),
119
+ ]);
120
+ const types = el('Types', { xmlns: CT }, [
121
+ el('Default', { Extension: 'rels', ContentType: 'application/vnd.openxmlformats-package.relationships+xml' }),
122
+ el('Default', { Extension: 'xml', ContentType: 'application/xml' }),
123
+ el('Override', { PartName: '/xl/workbook.xml', ContentType: `${SML}.sheet.main+xml` }),
124
+ el('Override', { PartName: '/xl/worksheets/sheet1.xml', ContentType: `${SML}.worksheet+xml` }),
125
+ el('Override', { PartName: '/xl/styles.xml', ContentType: `${SML}.styles+xml` }),
126
+ ]);
127
+ return writeZip([
128
+ { name: '[Content_Types].xml', data: xml(types) },
129
+ { name: '_rels/.rels', data: xml(rootRels) },
130
+ { name: 'xl/workbook.xml', data: xml(workbook) },
131
+ { name: 'xl/_rels/workbook.xml.rels', data: xml(workbookRels) },
132
+ { name: 'xl/styles.xml', data: xml(styles) },
133
+ { name: 'xl/worksheets/sheet1.xml', data: xml(sheet) },
134
+ ], { modified: new Date(Date.UTC(2026, 0, 1)) });
135
+ }
136
+ function walk(node, visit) {
137
+ visit(node);
138
+ for (const c of node.children)
139
+ if (c.type === 'element')
140
+ walk(c, visit);
141
+ }
142
+ function columnIndex(letters) {
143
+ let n = 0;
144
+ for (const ch of letters)
145
+ n = n * 26 + (ch.charCodeAt(0) - 64);
146
+ return n - 1;
147
+ }
148
+ /** Whether bytes are a workbook package that can be read: a zip with a workbook or worksheet part. */
149
+ export function isWorkbook(bytes) {
150
+ try {
151
+ return readZip(bytes).some((e) => e.name === 'xl/workbook.xml' || /^xl\/worksheets\/[^/]+\.xml$/.test(e.name));
152
+ }
153
+ catch {
154
+ return false;
155
+ }
156
+ }
157
+ /**
158
+ * True when the workbook holds more than the chart's own table: a second worksheet, or a
159
+ * non-empty cell outside A1 to the last series column and category row + 1. False when unreadable.
160
+ */
161
+ export async function workbookHasMore(bytes, categoryCount, seriesCount) {
162
+ try {
163
+ const entries = readZip(bytes);
164
+ const decode = async (name) => {
165
+ const e = entries.find((x) => x.name === name);
166
+ return e ? new TextDecoder().decode(await e.read()) : undefined;
167
+ };
168
+ const sheets = entries.filter((e) => /^xl\/worksheets\/[^/]+\.xml$/.test(e.name));
169
+ if (sheets.length > 1)
170
+ return true;
171
+ const book = await decode('xl/workbook.xml');
172
+ if (book !== undefined) {
173
+ let count = 0;
174
+ walk(parseXml(book).root, (e) => {
175
+ if (localName(e.name) === 'sheet')
176
+ count++;
177
+ });
178
+ if (count > 1)
179
+ return true;
180
+ }
181
+ const maxCol = seriesCount;
182
+ const maxRow = categoryCount + 1;
183
+ for (const sheet of sheets) {
184
+ let more = false;
185
+ walk(parseXml(new TextDecoder().decode(await sheet.read())).root, (e) => {
186
+ if (localName(e.name) !== 'c')
187
+ return;
188
+ const filled = e.children.some((c) => c.type === 'element' && ['v', 'is', 'f'].includes(localName(c.name)));
189
+ if (!filled)
190
+ return;
191
+ const m = /^([A-Z]+)(\d+)$/.exec(e.attrs.r ?? '');
192
+ if (!m || columnIndex(m[1]) > maxCol || Number(m[2]) > maxRow)
193
+ more = true;
194
+ });
195
+ if (more)
196
+ return true;
197
+ }
198
+ return false;
199
+ }
200
+ catch {
201
+ return false;
202
+ }
203
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Writing chart parts: a new c:chartSpace built from a table of data (as Word writes a chart it has
3
+ * just inserted), any chart's data read back as that table, and an existing chart patched with new
4
+ * data while its formatting stays. Element order follows the DrawingML chart schema throughout.
5
+ */
6
+ import { type XmlElement } from '../xml/dom.js';
7
+ import { type ChartSeriesData } from './workbook.js';
8
+ export type { ChartSeriesData } from './workbook.js';
9
+ export type NewChartType = 'column' | 'bar' | 'line' | 'area' | 'pie' | 'doughnut' | 'scatter';
10
+ export type LegendPosition = 'bottom' | 'top' | 'left' | 'right' | 'none';
11
+ export interface NewChart {
12
+ type: NewChartType;
13
+ /** Column, bar and area charts only. */
14
+ stacked?: 'stacked' | 'percent';
15
+ title?: string;
16
+ /**
17
+ * Category labels; for scatter charts the x values (numbers). Numbers (dates are Excel serial
18
+ * numbers) stay numbers in the chart and its workbook, with null for a missing one.
19
+ */
20
+ categories: Array<string | number | null>;
21
+ /** Number format of numeric categories, as Excel writes it (e.g. "mmm-yy" for dates); General when left out. */
22
+ categoryFormat?: string;
23
+ series: ChartSeriesData[];
24
+ /** Default bottom. */
25
+ legend?: LegendPosition;
26
+ axisTitles?: {
27
+ category?: string;
28
+ value?: string;
29
+ };
30
+ }
31
+ /**
32
+ * What to change in an existing chart; an empty string removes a title. Series keep their number
33
+ * format by position unless they give one; numeric categories keep theirs unless `categoryFormat`
34
+ * is given.
35
+ */
36
+ export interface ChartChanges {
37
+ title?: string;
38
+ axisTitles?: {
39
+ category?: string;
40
+ value?: string;
41
+ };
42
+ legend?: LegendPosition;
43
+ /** Where the chart's categories are numbers or dates, null or '' leaves a gap and keeps them numbers. */
44
+ categories?: Array<string | number | null>;
45
+ categoryFormat?: string;
46
+ series?: ChartSeriesData[];
47
+ }
48
+ /** A chart's data as one table: categories down the side, one column per series. */
49
+ export interface ChartTable {
50
+ /** "clustered column", "stacked bar", "line", "pie", …; several plots joined with " + ". */
51
+ kind: string;
52
+ title?: string;
53
+ axisTitles: {
54
+ category?: string;
55
+ value?: string;
56
+ };
57
+ legend: LegendPosition;
58
+ /** Text labels, or numbers (dates are Excel serial numbers) with null for a missing one. */
59
+ categories: Array<string | number | null>;
60
+ /** Number format of numeric categories, when it is not General. */
61
+ categoryFormat?: string;
62
+ /** Each series' values, with their number format (`formatCode`) when it is not General. */
63
+ series: ChartSeriesData[];
64
+ /** Number format of the first series' values. */
65
+ formatCode: string;
66
+ }
67
+ export declare class ChartDataError extends Error {
68
+ name: string;
69
+ }
70
+ /**
71
+ * Check a table before it is written into a chart: every series has one value per category, all
72
+ * numbers are finite, and the shape suits the chart type (when one is given).
73
+ */
74
+ export declare function validateChartData(type: NewChartType | undefined, stacked: NewChart['stacked'], categories: Array<string | number | null>, series: ChartSeriesData[]): void;
75
+ /** A new chart part's root, looking like a chart Word has just inserted; its formulas point into `Sheet1` of the workbook `workbookRelId`. */
76
+ export declare function newChartSpace(chart: NewChart, workbookRelId: string): XmlElement;
77
+ /** A chart's data as one table (series in the reader's order: by plot, then c:order). */
78
+ export declare function readChartTable(chartSpace: XmlElement): ChartTable;
79
+ /**
80
+ * Change an existing chart in place. New data rewrites every series' name, categories and values;
81
+ * series keep their formatting by position, added series copy the last one's in the next accent
82
+ * colour, and extra series are removed from the end, along with any plot (and the axes only it
83
+ * used) left without series. Formulas point into Sheet1 of the chart's own workbook (series i in
84
+ * column i + 1); with `keepFormulas`, for a chart linked to an outside workbook, existing references
85
+ * stay and only their caches change, while added series hold literal data. Categories or series
86
+ * alone are combined with the chart's current data. Throws ChartDataError (before changing
87
+ * anything) when the resulting table is invalid.
88
+ */
89
+ export declare function patchChartSpace(chartSpace: XmlElement, changes: ChartChanges, options?: {
90
+ keepFormulas?: boolean;
91
+ }): void;