docxkeun 0.2.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.
- package/CHANGELOG.md +52 -0
- package/README.md +82 -3
- package/dist/api/editor.d.ts +191 -6
- package/dist/api/editor.js +780 -37
- package/dist/api/index.d.ts +4 -1
- package/dist/api/index.js +1 -0
- package/dist/api/objects.d.ts +202 -0
- package/dist/api/objects.js +574 -0
- package/dist/api/revisions.js +13 -2
- package/dist/api/tables.d.ts +60 -0
- package/dist/api/tables.js +138 -0
- package/dist/charts/index.d.ts +4 -1
- package/dist/charts/index.js +3 -1
- package/dist/charts/model.d.ts +4 -0
- package/dist/charts/model.js +3 -2
- package/dist/charts/workbook.d.ts +29 -0
- package/dist/charts/workbook.js +203 -0
- package/dist/charts/write.d.ts +91 -0
- package/dist/charts/write.js +559 -0
- package/dist/opc/constants.d.ts +4 -0
- package/dist/opc/constants.js +4 -0
- package/dist/render/activity.d.ts +58 -2
- package/dist/render/activity.js +500 -47
- package/dist/render/index.d.ts +1 -1
- package/dist/render/index.js +1 -1
- package/dist/render/viewer.js +2 -0
- package/package.json +1 -1
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Building blocks for DocxEditor's table and copy operations: a new table's XML, cleaning a copied
|
|
3
|
+
* block so it can live next to its original, and marking new content as a tracked insertion.
|
|
4
|
+
*/
|
|
5
|
+
import { el, findAll, firstChild, insertOrdered, removeChildren } from '../xml/index.js';
|
|
6
|
+
import { insertedRuns } from './revisions.js';
|
|
7
|
+
const BORDER_SIDES = ['w:top', 'w:left', 'w:bottom', 'w:right', 'w:insideH', 'w:insideV'];
|
|
8
|
+
const TRPR_ORDER = ['w:cnfStyle', 'w:divId', 'w:gridBefore', 'w:gridAfter', 'w:wBefore', 'w:wAfter', 'w:cantSplit', 'w:trHeight', 'w:tblHeader', 'w:tblCellSpacing', 'w:jc', 'w:hidden', 'w:ins', 'w:del', 'w:trPrChange'];
|
|
9
|
+
/**
|
|
10
|
+
* A new table (w:tbl). `widths` are the columns' widths in twips; `paragraph` makes a cell's
|
|
11
|
+
* paragraph for one line of text (lines come from "\n" in the cell text).
|
|
12
|
+
*/
|
|
13
|
+
export function buildTable(rows, widths, o) {
|
|
14
|
+
const total = widths.reduce((a, b) => a + b, 0);
|
|
15
|
+
const tblPr = el('w:tblPr', {}, [
|
|
16
|
+
...(o.style ? [el('w:tblStyle', { 'w:val': o.style })] : []),
|
|
17
|
+
el('w:tblW', { 'w:w': String(total), 'w:type': 'dxa' }),
|
|
18
|
+
...(o.align && o.align !== 'left' ? [el('w:jc', { 'w:val': o.align })] : []),
|
|
19
|
+
...(o.borders && !o.style ? [el('w:tblBorders', {}, BORDER_SIDES.map((n) => el(n, { 'w:val': 'single', 'w:sz': '4', 'w:space': '0', 'w:color': 'auto' })))] : []),
|
|
20
|
+
el('w:tblLayout', { 'w:type': 'fixed' }),
|
|
21
|
+
el('w:tblLook', { 'w:val': '04A0', 'w:firstRow': o.header ? '1' : '0', 'w:lastRow': '0', 'w:firstColumn': '1', 'w:lastColumn': '0', 'w:noHBand': '0', 'w:noVBand': '1' }),
|
|
22
|
+
]);
|
|
23
|
+
const grid = el('w:tblGrid', {}, widths.map((w) => el('w:gridCol', { 'w:w': String(w) })));
|
|
24
|
+
const trs = rows.map((cells, r) => {
|
|
25
|
+
const isHeader = o.header && r === 0;
|
|
26
|
+
return el('w:tr', {}, [
|
|
27
|
+
...(isHeader ? [el('w:trPr', {}, [el('w:tblHeader')])] : []),
|
|
28
|
+
...widths.map((w, c) => el('w:tc', {}, [el('w:tcPr', {}, [el('w:tcW', { 'w:w': String(w), 'w:type': 'dxa' })]), ...(cells[c] ?? '').split('\n').map((line) => o.paragraph(line, isHeader))])),
|
|
29
|
+
]);
|
|
30
|
+
});
|
|
31
|
+
return el('w:tbl', {}, [tblPr, grid, ...trs]);
|
|
32
|
+
}
|
|
33
|
+
/** Column widths in twips: `weights` (default equal) scaled to fill `total`. */
|
|
34
|
+
export function columnWidths(columns, total, weights) {
|
|
35
|
+
const w = weights ?? Array.from({ length: columns }, () => 1);
|
|
36
|
+
const sum = w.reduce((a, b) => a + b, 0);
|
|
37
|
+
const out = w.map((x) => Math.max(1, Math.floor((x / sum) * total)));
|
|
38
|
+
// Rounding: the last column takes what is left so the table is exactly `total` wide.
|
|
39
|
+
out[out.length - 1] += total - out.reduce((a, b) => a + b, 0);
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
const DROP_MARKERS = new Set(['w:bookmarkStart', 'w:bookmarkEnd', 'w:commentRangeStart', 'w:commentRangeEnd', 'w:permStart', 'w:permEnd']);
|
|
43
|
+
const REVISIONS_WITH_ID = new Set([
|
|
44
|
+
'w:ins', 'w:del', 'w:moveFrom', 'w:moveTo', 'w:moveFromRangeStart', 'w:moveFromRangeEnd', 'w:moveToRangeStart', 'w:moveToRangeEnd',
|
|
45
|
+
'w:rPrChange', 'w:pPrChange', 'w:sectPrChange', 'w:tblPrChange', 'w:tblGridChange', 'w:trPrChange', 'w:tcPrChange', 'w:tblPrExChange',
|
|
46
|
+
'w:numberingChange', 'w:cellIns', 'w:cellDel', 'w:cellMerge',
|
|
47
|
+
]);
|
|
48
|
+
/**
|
|
49
|
+
* Make a cloned block fit to sit next to its original: drop what may exist only once (bookmarks,
|
|
50
|
+
* comment anchors, note references, editable-range markers, a paragraph's section break), give
|
|
51
|
+
* drawings, content controls and tracked changes new ids, and drop Word's paragraph ids.
|
|
52
|
+
*/
|
|
53
|
+
export function cleanCopy(node, ids, dropped) {
|
|
54
|
+
delete node.attrs['w14:paraId'];
|
|
55
|
+
delete node.attrs['w14:textId'];
|
|
56
|
+
if (node.name === 'wp:docPr')
|
|
57
|
+
node.attrs.id = ids.drawing();
|
|
58
|
+
if (REVISIONS_WITH_ID.has(node.name) && node.attrs['w:id'] !== undefined)
|
|
59
|
+
node.attrs['w:id'] = ids.revision();
|
|
60
|
+
if (node.name === 'w:sdtPr') {
|
|
61
|
+
const id = firstChild(node, 'w:id');
|
|
62
|
+
if (id)
|
|
63
|
+
id.attrs['w:val'] = ids.sdt();
|
|
64
|
+
}
|
|
65
|
+
const kept = [];
|
|
66
|
+
for (const c of node.children) {
|
|
67
|
+
if (c.type === 'element') {
|
|
68
|
+
if (DROP_MARKERS.has(c.name)) {
|
|
69
|
+
if (c.name === 'w:bookmarkStart')
|
|
70
|
+
dropped.bookmarks++;
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if (node.name === 'w:pPr' && c.name === 'w:sectPr')
|
|
74
|
+
continue;
|
|
75
|
+
if (c.name === 'w:r') {
|
|
76
|
+
if (firstChild(c, 'w:commentReference')) {
|
|
77
|
+
dropped.comments++;
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (firstChild(c, 'w:footnoteReference') || firstChild(c, 'w:endnoteReference')) {
|
|
81
|
+
dropped.notes++;
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
cleanCopy(c, ids, dropped);
|
|
86
|
+
}
|
|
87
|
+
kept.push(c);
|
|
88
|
+
}
|
|
89
|
+
node.children = kept;
|
|
90
|
+
}
|
|
91
|
+
// ---- tracked insertion ----------------------------------------------------------------------------
|
|
92
|
+
const RUN_CONTAINERS = new Set(['w:hyperlink', 'w:smartTag', 'w:fldSimple', 'w:sdt', 'w:sdtContent', 'w:customXml']);
|
|
93
|
+
/** Wrap the runs of a paragraph (and of its links and fields) in w:ins, a group at a time. */
|
|
94
|
+
function wrapRuns(container, nextId, who) {
|
|
95
|
+
const out = [];
|
|
96
|
+
let group = [];
|
|
97
|
+
const flush = () => {
|
|
98
|
+
if (group.length)
|
|
99
|
+
out.push(insertedRuns(group, nextId(), who));
|
|
100
|
+
group = [];
|
|
101
|
+
};
|
|
102
|
+
for (const c of container.children) {
|
|
103
|
+
if (c.type === 'element' && c.name === 'w:r') {
|
|
104
|
+
group.push(c);
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
flush();
|
|
108
|
+
if (c.type === 'element' && RUN_CONTAINERS.has(c.name))
|
|
109
|
+
wrapRuns(c, nextId, who);
|
|
110
|
+
out.push(c);
|
|
111
|
+
}
|
|
112
|
+
flush();
|
|
113
|
+
container.children = out;
|
|
114
|
+
}
|
|
115
|
+
/** Mark a table row inserted or deleted (w:trPr/w:ins or w:del). */
|
|
116
|
+
export function markRow(row, kind, id, who) {
|
|
117
|
+
let trPr = firstChild(row, 'w:trPr');
|
|
118
|
+
if (!trPr) {
|
|
119
|
+
trPr = el('w:trPr');
|
|
120
|
+
const exceptions = firstChild(row, 'w:tblPrEx');
|
|
121
|
+
row.children.splice(exceptions ? row.children.indexOf(exceptions) + 1 : 0, 0, trPr);
|
|
122
|
+
}
|
|
123
|
+
removeChildren(trPr, 'w:ins');
|
|
124
|
+
removeChildren(trPr, 'w:del');
|
|
125
|
+
insertOrdered(trPr, el(kind === 'ins' ? 'w:ins' : 'w:del', { 'w:id': id, 'w:author': who.author, 'w:date': who.date }), TRPR_ORDER);
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Mark new content (a paragraph, a table, a row) as a tracked insertion by `who`: its runs, its
|
|
129
|
+
* paragraph marks and its table rows. `markParagraph` marks one paragraph mark.
|
|
130
|
+
*/
|
|
131
|
+
export function markInserted(node, nextId, who, markParagraph) {
|
|
132
|
+
for (const p of node.name === 'w:p' ? [node] : findAll(node, 'w:p')) {
|
|
133
|
+
wrapRuns(p, nextId, who);
|
|
134
|
+
markParagraph(p);
|
|
135
|
+
}
|
|
136
|
+
for (const row of node.name === 'w:tr' ? [node] : findAll(node, 'w:tr'))
|
|
137
|
+
markRow(row, 'ins', nextId(), who);
|
|
138
|
+
}
|
package/dist/charts/index.d.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Charts (word/charts/chartN.xml, root c:chartSpace): read the cached data into a model, describe it
|
|
3
|
-
* in one line of text, and draw it into display items for the SVG viewer and PDF export
|
|
3
|
+
* in one line of text, and draw it into display items for the SVG viewer and PDF export; write new
|
|
4
|
+
* charts from a table of data, read any chart's data as that table, and patch it with new data.
|
|
4
5
|
*/
|
|
5
6
|
export { readChart, describeChart, autoColor } from './model.js';
|
|
6
7
|
export type { ChartModel, ChartPlot, ChartSeries, ChartAxis, ChartLegend, ChartText, ChartPoint, DataLabels, DataLabelFlags, LineStyle, ManualLayout, MarkerStyle, MarkerSymbol, NumFmt, PlotType, Grouping, TextStyle, ReadChartOptions, } from './model.js';
|
|
8
|
+
export { newChartSpace, readChartTable, patchChartSpace, validateChartData, ChartDataError } from './write.js';
|
|
9
|
+
export type { NewChart, NewChartType, LegendPosition, ChartChanges, ChartTable, ChartSeriesData } from './write.js';
|
|
7
10
|
export { renderChart, drawChart } from './render.js';
|
|
8
11
|
export type { ChartFrame, RenderChartOptions } from './render.js';
|
|
9
12
|
export { formatNumber, formatGeneral, isDateCode } from './format.js';
|
package/dist/charts/index.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Charts (word/charts/chartN.xml, root c:chartSpace): read the cached data into a model, describe it
|
|
3
|
-
* in one line of text, and draw it into display items for the SVG viewer and PDF export
|
|
3
|
+
* in one line of text, and draw it into display items for the SVG viewer and PDF export; write new
|
|
4
|
+
* charts from a table of data, read any chart's data as that table, and patch it with new data.
|
|
4
5
|
*/
|
|
5
6
|
export { readChart, describeChart, autoColor } from './model.js';
|
|
7
|
+
export { newChartSpace, readChartTable, patchChartSpace, validateChartData, ChartDataError } from './write.js';
|
|
6
8
|
export { renderChart, drawChart } from './render.js';
|
|
7
9
|
export { formatNumber, formatGeneral, isDateCode } from './format.js';
|
|
8
10
|
export { resolveColorElement, colorIn, fillOf, lineOf } from './color.js';
|
package/dist/charts/model.d.ts
CHANGED
|
@@ -217,9 +217,13 @@ export interface ReadChartOptions {
|
|
|
217
217
|
/** Theme colours; Office's default theme is used for names it does not know. */
|
|
218
218
|
schemeColor?: SchemeColorFn;
|
|
219
219
|
}
|
|
220
|
+
/** The chart colour style's variations for series 7+ (Office's colors1.xml, cycling the accents). */
|
|
221
|
+
export declare const VARIATIONS: Array<[number, number]>;
|
|
220
222
|
/** Automatic colour of series (or point) `i` of `count`, for chart style `style`. */
|
|
221
223
|
export declare function autoColor(i: number, count: number, style: number, scheme: SchemeColorFn | undefined): string;
|
|
222
224
|
/** Read a c:chartSpace into a chart model. */
|
|
223
225
|
export declare function readChart(chartSpace: XmlElement, options?: ReadChartOptions): ChartModel;
|
|
226
|
+
/** A plot's plain name: "clustered column", "100% stacked bar", "line", "pie", … */
|
|
227
|
+
export declare function plotName(plot: ChartPlot): string;
|
|
224
228
|
/** One short plain-text description of the chart, for screen readers and AI tools. */
|
|
225
229
|
export declare function describeChart(model: ChartModel): string;
|
package/dist/charts/model.js
CHANGED
|
@@ -199,7 +199,7 @@ function readData(node) {
|
|
|
199
199
|
// ---------------------------------------------------------------------------------------------
|
|
200
200
|
// Automatic colours
|
|
201
201
|
/** The chart colour style's variations for series 7+ (Office's colors1.xml, cycling the accents). */
|
|
202
|
-
const VARIATIONS = [
|
|
202
|
+
export const VARIATIONS = [
|
|
203
203
|
[1, 0],
|
|
204
204
|
[0.6, 0],
|
|
205
205
|
[0.8, 0.2],
|
|
@@ -682,7 +682,8 @@ export function readChart(chartSpace, options = {}) {
|
|
|
682
682
|
}
|
|
683
683
|
// ---------------------------------------------------------------------------------------------
|
|
684
684
|
// Description
|
|
685
|
-
|
|
685
|
+
/** A plot's plain name: "clustered column", "100% stacked bar", "line", "pie", … */
|
|
686
|
+
export function plotName(plot) {
|
|
686
687
|
const dir = plot.barDir === 'bar' ? 'bar' : 'column';
|
|
687
688
|
const g = plot.grouping;
|
|
688
689
|
const prefix = g === 'stacked' ? 'stacked ' : g === 'percentStacked' ? '100% stacked ' : '';
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export interface ChartSeriesData {
|
|
2
|
+
name: string;
|
|
3
|
+
values: Array<number | null>;
|
|
4
|
+
/** Number format of the values, as Excel writes it (e.g. "0%", "#,##0.00"); General when left out. */
|
|
5
|
+
formatCode?: string;
|
|
6
|
+
}
|
|
7
|
+
/** The data a chart's workbook holds: categories down column A, a column per series, and their number formats. */
|
|
8
|
+
export interface WorkbookData {
|
|
9
|
+
categories: Array<string | number | null>;
|
|
10
|
+
series: ChartSeriesData[];
|
|
11
|
+
/** Number format of numeric categories (e.g. "mmm-yy" for dates); General when left out. */
|
|
12
|
+
categoryFormat?: string;
|
|
13
|
+
}
|
|
14
|
+
/** Zero-based column index to its letters: 0 is A, 25 is Z, 26 is AA. */
|
|
15
|
+
export declare function columnName(index: number): string;
|
|
16
|
+
/** The sheet ranges a chart's formulas point at: series i sits in column i + 1. */
|
|
17
|
+
export declare function chartRanges(_seriesCount: number, categoryCount: number): {
|
|
18
|
+
categories: string;
|
|
19
|
+
name(i: number): string;
|
|
20
|
+
values(i: number): string;
|
|
21
|
+
};
|
|
22
|
+
export declare function workbookFor(data: WorkbookData): Promise<Uint8Array>;
|
|
23
|
+
/** Whether bytes are a workbook package that can be read: a zip with a workbook or worksheet part. */
|
|
24
|
+
export declare function isWorkbook(bytes: Uint8Array): boolean;
|
|
25
|
+
/**
|
|
26
|
+
* True when the workbook holds more than the chart's own table: a second worksheet, or a
|
|
27
|
+
* non-empty cell outside A1 to the last series column and category row + 1. False when unreadable.
|
|
28
|
+
*/
|
|
29
|
+
export declare function workbookHasMore(bytes: Uint8Array, categoryCount: number, seriesCount: number): Promise<boolean>;
|
|
@@ -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;
|