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.
@@ -0,0 +1,559 @@
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 { attr, childPath, cloneElement, el, elements, ensureChild, firstChild, insertOrdered, removeChildren, text, textContent, } from '../xml/dom.js';
7
+ import { NS } from '../xml/ns.js';
8
+ import { plotName, readChart, VARIATIONS } from './model.js';
9
+ import { chartRanges } from './workbook.js';
10
+ export class ChartDataError extends Error {
11
+ name = 'ChartDataError';
12
+ }
13
+ const STACKABLE = new Set(['column', 'bar', 'area']);
14
+ /**
15
+ * Check a table before it is written into a chart: every series has one value per category, all
16
+ * numbers are finite, and the shape suits the chart type (when one is given).
17
+ */
18
+ export function validateChartData(type, stacked, categories, series) {
19
+ if (series.length === 0)
20
+ throw new ChartDataError('a chart needs at least one series');
21
+ if (categories.length === 0)
22
+ throw new ChartDataError('a chart needs at least one category');
23
+ categories.forEach((c, i) => {
24
+ if (typeof c === 'number' ? !Number.isFinite(c) : c !== null && typeof c !== 'string')
25
+ throw new ChartDataError(`category ${i + 1} is not text or a finite number`);
26
+ });
27
+ for (const s of series) {
28
+ if (s.values.length !== categories.length)
29
+ throw new ChartDataError(`series "${s.name}" has ${s.values.length} values for ${categories.length} categories`);
30
+ s.values.forEach((v, i) => {
31
+ if (v !== null && !Number.isFinite(v))
32
+ throw new ChartDataError(`series "${s.name}": value ${i + 1} is not a finite number`);
33
+ });
34
+ }
35
+ if (type === undefined)
36
+ return;
37
+ if (stacked && !STACKABLE.has(type))
38
+ throw new ChartDataError(`a ${type} chart cannot be stacked; only column, bar and area charts can`);
39
+ if (type === 'pie' && series.length > 1)
40
+ throw new ChartDataError(`a pie chart has one series, not ${series.length}`);
41
+ if (type === 'scatter' && categories.some((c) => typeof c !== 'number' && c !== null))
42
+ throw new ChartDataError('a scatter chart needs numbers as its categories (the x values)');
43
+ }
44
+ // ---------------------------------------------------------------------------------------------
45
+ // Schema sequences (for inserting into existing elements)
46
+ const CHART_ORDER = ['c:title', 'c:autoTitleDeleted', 'c:pivotFmts', 'c:view3D', 'c:floor', 'c:sideWall', 'c:backWall', 'c:plotArea', 'c:legend', 'c:plotVisOnly', 'c:dispBlanksAs', 'c:showDLblsOverMax', 'c:extLst'];
47
+ const TITLE_ORDER = ['c:tx', 'c:layout', 'c:overlay', 'c:spPr', 'c:txPr', 'c:extLst'];
48
+ const LEGEND_ORDER = ['c:legendPos', 'c:legendEntry', 'c:layout', 'c:overlay', 'c:spPr', 'c:txPr', 'c:extLst'];
49
+ /** CT_CatAx, CT_ValAx, CT_DateAx and CT_SerAx merged: their orders agree. */
50
+ const AXIS_ORDER = [
51
+ 'c:axId', 'c:scaling', 'c:delete', 'c:axPos', 'c:majorGridlines', 'c:minorGridlines', 'c:title', 'c:numFmt', 'c:majorTickMark', 'c:minorTickMark', 'c:tickLblPos', 'c:spPr', 'c:txPr',
52
+ 'c:crossAx', 'c:crosses', 'c:crossesAt', 'c:crossBetween', 'c:auto', 'c:lblAlgn', 'c:lblOffset', 'c:baseTimeUnit', 'c:majorUnit', 'c:majorTimeUnit', 'c:minorUnit', 'c:minorTimeUnit',
53
+ 'c:tickLblSkip', 'c:tickMarkSkip', 'c:dispUnits', 'c:noMultiLvlLbl', 'c:extLst',
54
+ ];
55
+ /** Every series type's sequence (bar, line, area, pie, scatter, bubble, radar, surface) merged: their orders agree. */
56
+ const SER_ORDER = [
57
+ 'c:idx', 'c:order', 'c:tx', 'c:spPr', 'c:invertIfNegative', 'c:pictureOptions', 'c:marker', 'c:explosion', 'c:dPt', 'c:dLbls', 'c:trendline', 'c:errBars',
58
+ 'c:cat', 'c:xVal', 'c:val', 'c:yVal', 'c:bubbleSize', 'c:bubble3D', 'c:shape', 'c:smooth', 'c:extLst',
59
+ ];
60
+ /** Plot children that come before the series. */
61
+ const BEFORE_SER = new Set(['c:barDir', 'c:grouping', 'c:varyColors', 'c:scatterStyle', 'c:radarStyle', 'c:ofPieType', 'c:wireframe']);
62
+ const AXES = new Set(['c:catAx', 'c:valAx', 'c:dateAx', 'c:serAx']);
63
+ // ---------------------------------------------------------------------------------------------
64
+ // Small builders and readers
65
+ const v = (name, value) => el(name, { val: value });
66
+ const valOf = (parent, name) => attr(firstChild(parent, name), 'val');
67
+ /** Every plot element (c:barChart, c:pie3DChart, …) ends in "Chart". */
68
+ const isPlot = (e) => e.name.endsWith('Chart');
69
+ function numOf(parent, name) {
70
+ const s = valOf(parent, name);
71
+ if (s === undefined)
72
+ return undefined;
73
+ const n = Number.parseFloat(s);
74
+ return Number.isFinite(n) ? n : undefined;
75
+ }
76
+ /** Series colour `i` as Word picks it: the six accents, then rounds of darker and lighter variations. */
77
+ function accentColor(i) {
78
+ const [lumMod, lumOff] = VARIATIONS[Math.floor(i / 6) % VARIATIONS.length];
79
+ const mods = [];
80
+ if (lumMod !== 1)
81
+ mods.push(v('a:lumMod', Math.round(lumMod * 100000)));
82
+ if (lumOff !== 0)
83
+ mods.push(v('a:lumOff', Math.round(lumOff * 100000)));
84
+ return el('a:schemeClr', { val: `accent${(i % 6) + 1}` }, mods);
85
+ }
86
+ /** Word's light grey (text colour at 15%) for gridlines and the category axis line. */
87
+ function greyLine() {
88
+ const grey = el('a:schemeClr', { val: 'tx1' }, [v('a:lumMod', 15000), v('a:lumOff', 85000)]);
89
+ return el('a:ln', { w: 9525, cap: 'flat', cmpd: 'sng', algn: 'ctr' }, [el('a:solidFill', {}, [grey]), el('a:round')]);
90
+ }
91
+ // Data: with a formula, a reference (c:strRef, c:numRef) and its cache; without one, a literal
92
+ // (c:strLit, c:numLit, or c:v for a series name) for data that has no cells.
93
+ function strData(formula, values) {
94
+ const points = [v('c:ptCount', values.length), ...values.map((s, i) => el('c:pt', { idx: i }, [el('c:v', {}, [text(s)])]))];
95
+ return formula === undefined ? el('c:strLit', {}, points) : el('c:strRef', {}, [el('c:f', {}, [text(formula)]), el('c:strCache', {}, points)]);
96
+ }
97
+ /** A missing value has no c:pt. */
98
+ function numData(formula, values, formatCode) {
99
+ const points = [el('c:formatCode', {}, [text(formatCode)]), v('c:ptCount', values.length)];
100
+ values.forEach((n, i) => {
101
+ if (n !== null)
102
+ points.push(el('c:pt', { idx: i }, [el('c:v', {}, [text(String(n))])]));
103
+ });
104
+ return formula === undefined ? el('c:numLit', {}, points) : el('c:numRef', {}, [el('c:f', {}, [text(formula)]), el('c:numCache', {}, points)]);
105
+ }
106
+ function seriesName(formula, name) {
107
+ return el('c:tx', {}, [formula === undefined ? el('c:v', {}, [text(name)]) : strData(formula, [name])]);
108
+ }
109
+ /**
110
+ * c:cat or c:xVal: numbers when every category is a number (or null, a gap), text otherwise. Where
111
+ * the categories were numbers already (`wasNumeric`), an empty string is a gap too, so numbers and
112
+ * dates don't turn into text.
113
+ */
114
+ function categoryData(name, formula, categories, formatCode = 'General', wasNumeric = false) {
115
+ const gap = (c) => c === null || (wasNumeric && c === '');
116
+ const numeric = categories.some((c) => typeof c === 'number') && categories.every((c) => typeof c === 'number' || gap(c));
117
+ return el(name, {}, [
118
+ numeric ? numData(formula, categories.map((c) => (typeof c === 'number' ? c : null)), formatCode) : strData(formula, categories.map((c) => (c === null ? '' : String(c)))),
119
+ ]);
120
+ }
121
+ function formatCodeOf(data) {
122
+ const fc = firstChild(childPath(data, 'c:numRef', 'c:numCache') ?? firstChild(data, 'c:numLit'), 'c:formatCode');
123
+ return fc ? textContent(fc) : undefined;
124
+ }
125
+ /** Whether data (c:cat, c:xVal) holds numbers: a c:numRef or c:numLit. */
126
+ function isNumeric(data) {
127
+ return firstChild(data, 'c:numRef') !== undefined || firstChild(data, 'c:numLit') !== undefined;
128
+ }
129
+ /** The cell reference of a series name, categories or values; undefined for literal data. */
130
+ function formulaOf(data) {
131
+ const ref = firstChild(data, 'c:strRef') ?? firstChild(data, 'c:numRef') ?? firstChild(data, 'c:multiLvlStrRef');
132
+ const f = firstChild(ref, 'c:f');
133
+ return f ? textContent(f) : undefined;
134
+ }
135
+ /** Replace the text of a c:rich (or c:txPr) body, keeping its first paragraph and run formatting. */
136
+ function setRichText(rich, value) {
137
+ const paragraphs = elements(rich, 'a:p');
138
+ const pPr = firstChild(paragraphs[0], 'a:pPr');
139
+ const rPr = firstChild(paragraphs.flatMap((p) => elements(p, 'a:r'))[0], 'a:rPr');
140
+ const lines = value.split(/\r?\n/).map((line) => el('a:p', {}, [...(pPr ? [cloneElement(pPr)] : []), el('a:r', {}, [rPr ? cloneElement(rPr) : el('a:rPr', { lang: 'en-US' }), el('a:t', {}, [text(line)])])]));
141
+ rich.children = [...rich.children.filter((c) => !(c.type === 'element' && c.name === 'a:p')), ...lines];
142
+ }
143
+ function richText(rich) {
144
+ return elements(rich, 'a:p')
145
+ .map((p) => elements(p)
146
+ .filter((r) => r.name === 'a:r' || r.name === 'a:fld')
147
+ .map((r) => textContent(firstChild(r, 'a:t') ?? r))
148
+ .join(''))
149
+ .join('\n');
150
+ }
151
+ /** An empty title body: `size` in hundredths of a point, not bold; vertical titles read bottom to top. */
152
+ function newRich(size, vertical) {
153
+ return el('c:rich', {}, [
154
+ el('a:bodyPr', vertical ? { rot: -5400000, vert: 'horz' } : {}),
155
+ el('a:lstStyle'),
156
+ el('a:p', {}, [el('a:pPr', {}, [el('a:defRPr', { sz: size, b: 0 })]), el('a:r', {}, [el('a:rPr', { lang: 'en-US' })])]),
157
+ ]);
158
+ }
159
+ function newTitle(value, size, vertical) {
160
+ const rich = newRich(size, vertical);
161
+ setRichText(rich, value);
162
+ return el('c:title', {}, [el('c:tx', {}, [rich]), v('c:overlay', 0)]);
163
+ }
164
+ const LEGEND_POS = { bottom: 'b', top: 't', left: 'l', right: 'r' };
165
+ const LEGEND_NAMES = { b: 'bottom', t: 'top', l: 'left', r: 'right', tr: 'right' };
166
+ function newLegend(position) {
167
+ return el('c:legend', {}, [v('c:legendPos', LEGEND_POS[position]), v('c:overlay', 0)]);
168
+ }
169
+ const CAT_AX = '100000001';
170
+ const VAL_AX = '100000002';
171
+ function newSeries(style, i, data, chart, ranges) {
172
+ const color = accentColor(i);
173
+ const children = [v('c:idx', i), v('c:order', i), seriesName(ranges.name(i), data.name)];
174
+ switch (style) {
175
+ case 'bar':
176
+ case 'area':
177
+ children.push(el('c:spPr', {}, [el('a:solidFill', {}, [color]), el('a:ln', {}, [el('a:noFill')]), el('a:effectLst')]));
178
+ if (style === 'bar')
179
+ children.push(v('c:invertIfNegative', 0));
180
+ break;
181
+ case 'line':
182
+ children.push(el('c:spPr', {}, [el('a:ln', { w: 28575, cap: 'rnd' }, [el('a:solidFill', {}, [color]), el('a:round')]), el('a:effectLst')]), el('c:marker', {}, [v('c:symbol', 'none')]));
183
+ break;
184
+ case 'scatter':
185
+ // Markers only, as Word's default scatter chart.
186
+ children.push(el('c:spPr', {}, [el('a:ln', { w: 25400, cap: 'rnd' }, [el('a:noFill'), el('a:round')]), el('a:effectLst')]), el('c:marker', {}, [
187
+ v('c:symbol', 'circle'),
188
+ v('c:size', 5),
189
+ el('c:spPr', {}, [el('a:solidFill', {}, [color]), el('a:ln', { w: 9525 }, [el('a:solidFill', {}, [cloneElement(color)])]), el('a:effectLst')]),
190
+ ]));
191
+ break;
192
+ case 'pie':
193
+ // No series fill: the plot varies colours by point.
194
+ break;
195
+ }
196
+ const xy = style === 'scatter';
197
+ children.push(categoryData(xy ? 'c:xVal' : 'c:cat', ranges.categories, chart.categories, chart.categoryFormat));
198
+ children.push(el(xy ? 'c:yVal' : 'c:val', {}, [numData(ranges.values(i), data.values, data.formatCode || 'General')]));
199
+ if (style === 'line' || style === 'scatter')
200
+ children.push(v('c:smooth', 0));
201
+ return el('c:ser', {}, children);
202
+ }
203
+ function newAxis(kind, id, crossId, pos, opts) {
204
+ const children = [v('c:axId', id), el('c:scaling', {}, [v('c:orientation', 'minMax')]), v('c:delete', 0), v('c:axPos', pos)];
205
+ if (opts.gridlines)
206
+ children.push(el('c:majorGridlines', {}, [el('c:spPr', {}, [greyLine(), el('a:effectLst')])]));
207
+ if (opts.title)
208
+ children.push(newTitle(opts.title, 1000, pos === 'l'));
209
+ children.push(el('c:numFmt', { formatCode: 'General', sourceLinked: 1 }), v('c:majorTickMark', 'none'), v('c:minorTickMark', 'none'), v('c:tickLblPos', 'nextTo'), el('c:spPr', {}, [el('a:noFill'), opts.axisLine ? greyLine() : el('a:ln', {}, [el('a:noFill')]), el('a:effectLst')]), v('c:crossAx', crossId), v('c:crosses', 'autoZero'));
210
+ if (kind === 'c:catAx')
211
+ children.push(v('c:auto', 1), v('c:lblAlgn', 'ctr'), v('c:lblOffset', 100), v('c:noMultiLvlLbl', 0));
212
+ else
213
+ children.push(v('c:crossBetween', opts.crossBetween ?? 'between'));
214
+ return el(kind, {}, children);
215
+ }
216
+ function newPlotArea(chart) {
217
+ const ranges = chartRanges(chart.series.length, chart.categories.length);
218
+ const series = (style) => chart.series.map((s, i) => newSeries(style, i, s, chart, ranges));
219
+ const axIds = [v('c:axId', CAT_AX), v('c:axId', VAL_AX)];
220
+ const titles = chart.axisTitles ?? {};
221
+ const grouping = chart.stacked === 'stacked' ? 'stacked' : chart.stacked === 'percent' ? 'percentStacked' : undefined;
222
+ const layout = el('c:layout');
223
+ let plot;
224
+ switch (chart.type) {
225
+ case 'column':
226
+ case 'bar':
227
+ plot = el('c:barChart', {}, [
228
+ v('c:barDir', chart.type === 'bar' ? 'bar' : 'col'),
229
+ v('c:grouping', grouping ?? 'clustered'),
230
+ v('c:varyColors', 0),
231
+ ...series('bar'),
232
+ v('c:gapWidth', grouping ? 150 : 219),
233
+ v('c:overlap', grouping ? 100 : -27),
234
+ ...axIds,
235
+ ]);
236
+ break;
237
+ case 'line':
238
+ plot = el('c:lineChart', {}, [v('c:grouping', 'standard'), v('c:varyColors', 0), ...series('line'), v('c:marker', 1), ...axIds]);
239
+ break;
240
+ case 'area':
241
+ plot = el('c:areaChart', {}, [v('c:grouping', grouping ?? 'standard'), v('c:varyColors', 0), ...series('area'), ...axIds]);
242
+ break;
243
+ case 'pie':
244
+ case 'doughnut': {
245
+ const shared = [v('c:varyColors', 1), ...series('pie'), v('c:firstSliceAng', 0)];
246
+ return el('c:plotArea', {}, [layout, chart.type === 'pie' ? el('c:pieChart', {}, shared) : el('c:doughnutChart', {}, [...shared, v('c:holeSize', 75)])]);
247
+ }
248
+ case 'scatter':
249
+ return el('c:plotArea', {}, [
250
+ layout,
251
+ el('c:scatterChart', {}, [v('c:scatterStyle', 'lineMarker'), v('c:varyColors', 0), ...series('scatter'), ...axIds]),
252
+ newAxis('c:valAx', CAT_AX, VAL_AX, 'b', { title: titles.category, axisLine: true, crossBetween: 'midCat' }),
253
+ newAxis('c:valAx', VAL_AX, CAT_AX, 'l', { title: titles.value, gridlines: true, crossBetween: 'midCat' }),
254
+ ]);
255
+ }
256
+ // Columns stand on a horizontal category axis; bars lie along a vertical one.
257
+ const catPos = chart.type === 'bar' ? 'l' : 'b';
258
+ return el('c:plotArea', {}, [
259
+ layout,
260
+ plot,
261
+ newAxis('c:catAx', CAT_AX, VAL_AX, catPos, { title: titles.category, axisLine: true }),
262
+ // Areas run from edge to edge of the plot; columns, bars and lines sit between the tick marks.
263
+ newAxis('c:valAx', VAL_AX, CAT_AX, catPos === 'b' ? 'l' : 'b', { title: titles.value, gridlines: true, crossBetween: chart.type === 'area' ? 'midCat' : 'between' }),
264
+ ]);
265
+ }
266
+ /** A new chart part's root, looking like a chart Word has just inserted; its formulas point into `Sheet1` of the workbook `workbookRelId`. */
267
+ export function newChartSpace(chart, workbookRelId) {
268
+ validateChartData(chart.type, chart.stacked, chart.categories, chart.series);
269
+ const children = [];
270
+ if (chart.title)
271
+ children.push(newTitle(chart.title, 1400, false));
272
+ children.push(v('c:autoTitleDeleted', chart.title ? 0 : 1), newPlotArea(chart));
273
+ const legend = chart.legend ?? 'bottom';
274
+ if (legend !== 'none')
275
+ children.push(newLegend(legend));
276
+ children.push(v('c:plotVisOnly', 1), v('c:dispBlanksAs', 'gap'));
277
+ // Word's chart area: white with no border, and text 9 pt in the text colour at 65% (without them the
278
+ // default chart style draws a dark border and black 10 pt text).
279
+ const area = el('c:spPr', {}, [
280
+ el('a:solidFill', {}, [el('a:schemeClr', { val: 'bg1' })]),
281
+ el('a:ln', { w: 9525, cap: 'flat', cmpd: 'sng', algn: 'ctr' }, [el('a:noFill'), el('a:round')]),
282
+ el('a:effectLst'),
283
+ ]);
284
+ const textColour = el('a:schemeClr', { val: 'tx1' }, [v('a:lumMod', 65000), v('a:lumOff', 35000)]);
285
+ const text = el('c:txPr', {}, [
286
+ el('a:bodyPr'),
287
+ el('a:lstStyle'),
288
+ el('a:p', {}, [el('a:pPr', {}, [el('a:defRPr', { sz: 900 }, [el('a:solidFill', {}, [textColour])])]), el('a:endParaRPr', { lang: 'en-US' })]),
289
+ ]);
290
+ return el('c:chartSpace', { 'xmlns:c': NS.c, 'xmlns:a': NS.a, 'xmlns:r': NS.r }, [
291
+ v('c:date1904', 0),
292
+ v('c:lang', 'en-US'),
293
+ v('c:roundedCorners', 0),
294
+ el('c:chart', {}, children),
295
+ area,
296
+ text,
297
+ el('c:externalData', { 'r:id': workbookRelId }, [v('c:autoUpdate', 0)]),
298
+ ]);
299
+ }
300
+ // ---------------------------------------------------------------------------------------------
301
+ // Reading
302
+ /** The category (x) and value (y) axes of the first plot that has two. */
303
+ function chartAxes(chartSpace) {
304
+ const plotArea = childPath(chartSpace, 'c:chart', 'c:plotArea');
305
+ if (!plotArea)
306
+ return {};
307
+ const axes = elements(plotArea).filter((e) => AXES.has(e.name));
308
+ for (const plot of elements(plotArea).filter(isPlot)) {
309
+ const own = elements(plot, 'c:axId')
310
+ .map((id) => axes.find((a) => valOf(a, 'c:axId') === attr(id, 'val')))
311
+ .filter((a) => a !== undefined);
312
+ if (own.length < 2)
313
+ continue;
314
+ // Scatter and bubble charts have two value axes: x first.
315
+ if (own.every((a) => a.name === 'c:valAx'))
316
+ return { category: own[0], value: own[1] };
317
+ return { category: own.find((a) => a.name !== 'c:valAx'), value: own.find((a) => a.name === 'c:valAx') };
318
+ }
319
+ return {};
320
+ }
321
+ /** A chart's data as one table (series in the reader's order: by plot, then c:order). */
322
+ export function readChartTable(chartSpace) {
323
+ const model = readChart(chartSpace);
324
+ const all = model.plots.flatMap((p) => p.series);
325
+ const first = all[0];
326
+ // Numbers and dates stay numbers, a missing one null (not text).
327
+ const numeric = first?.categoryNumbers !== undefined;
328
+ const categories = first ? (first.categoryNumbers ? first.categoryNumbers.slice() : first.categories.slice()) : [];
329
+ const count = Math.max(categories.length, ...all.map((s) => s.values.length));
330
+ while (categories.length < count)
331
+ categories.push(numeric ? null : '');
332
+ const general = (code) => code === undefined || code === '' || code === 'General';
333
+ const table = {
334
+ kind: model.plots.map(plotName).join(' + ') || 'chart',
335
+ axisTitles: {},
336
+ legend: model.legend ? (LEGEND_NAMES[model.legend.position] ?? 'right') : 'none',
337
+ categories,
338
+ series: all.map((s) => ({
339
+ name: s.name,
340
+ values: Array.from({ length: count }, (_, i) => s.values[i] ?? null),
341
+ ...(general(s.formatCode) ? {} : { formatCode: s.formatCode }),
342
+ })),
343
+ formatCode: first?.formatCode ?? 'General',
344
+ };
345
+ if (numeric && !general(first.categoryFormat))
346
+ table.categoryFormat = first.categoryFormat;
347
+ if (model.title && !model.title.auto)
348
+ table.title = model.title.text;
349
+ const axes = chartAxes(chartSpace);
350
+ for (const key of ['category', 'value']) {
351
+ const id = valOf(axes[key], 'c:axId');
352
+ const title = id === undefined ? undefined : model.axes.find((a) => a.id === id)?.title;
353
+ if (title && !title.auto)
354
+ table.axisTitles[key] = title.text;
355
+ }
356
+ return table;
357
+ }
358
+ /** Series in the order the reader lists them: plots in document order, each sorted by c:order. */
359
+ function orderedSeries(plotArea) {
360
+ const out = [];
361
+ for (const plot of plotArea ? elements(plotArea).filter(isPlot) : []) {
362
+ const sers = elements(plot, 'c:ser').map((ser, i) => {
363
+ const idx = numOf(ser, 'c:idx') ?? i;
364
+ return { plot, ser, order: numOf(ser, 'c:order') ?? idx };
365
+ });
366
+ out.push(...sers.sort((a, b) => a.order - b.order));
367
+ }
368
+ return out;
369
+ }
370
+ function replaceChild(parent, node, order) {
371
+ const i = parent.children.findIndex((c) => c.type === 'element' && c.name === node.name);
372
+ if (i >= 0)
373
+ parent.children[i] = node;
374
+ else
375
+ insertOrdered(parent, node, order);
376
+ }
377
+ /** Fills other than none (a:noFill). */
378
+ const FILLS = ['a:solidFill', 'a:gradFill', 'a:pattFill', 'a:blipFill', 'a:grpFill'];
379
+ /** The colour element of an a:solidFill (a:schemeClr, a:srgbClr, …). */
380
+ const colourOf = (solidFill) => (solidFill ? elements(solidFill)[0] : undefined);
381
+ /** Put `color` in an a:solidFill, keeping the old colour's transforms (transparency, shade…) except the accent variation's lumMod/lumOff. */
382
+ function setColour(solidFill, color) {
383
+ const kept = elements(colourOf(solidFill) ?? el('x')).filter((t) => t.name !== 'a:lumMod' && t.name !== 'a:lumOff');
384
+ const next = cloneElement(color);
385
+ next.children.push(...kept.map(cloneElement));
386
+ solidFill.children = [next];
387
+ }
388
+ /**
389
+ * Give a series' shape properties a new colour: its solid fill, and its outline when the series has
390
+ * no fill (a line) or the outline had the fill's colour (by name, so a darker shade of it follows).
391
+ */
392
+ function recolor(spPr, color) {
393
+ const fill = firstChild(spPr, 'a:solidFill');
394
+ const line = childPath(spPr, 'a:ln', 'a:solidFill');
395
+ const filled = spPr !== undefined && elements(spPr).some((c) => FILLS.includes(c.name));
396
+ const same = (a, b) => a !== undefined && b !== undefined && a.name === b.name && attr(a, 'val') === attr(b, 'val');
397
+ const lineFollows = line !== undefined && (!filled || same(colourOf(fill), colourOf(line)));
398
+ if (fill)
399
+ setColour(fill, color);
400
+ if (line && lineFollows)
401
+ setColour(line, color);
402
+ }
403
+ /** A new series after the last one, styled like it in the next accent colour. */
404
+ function addSeries(plotArea, slots) {
405
+ const all = plotArea ? elements(plotArea).filter(isPlot).flatMap((p) => elements(p, 'c:ser')) : [];
406
+ const idx = Math.max(-1, ...all.map((s, i) => numOf(s, 'c:idx') ?? i)) + 1;
407
+ const order = Math.max(-1, ...all.map((s, i) => numOf(s, 'c:order') ?? numOf(s, 'c:idx') ?? i)) + 1;
408
+ const last = slots[slots.length - 1];
409
+ let slot;
410
+ if (last) {
411
+ const ser = cloneElement(last.ser);
412
+ // Extensions hold the original's unique id and cell-linked extras; formatting of single points,
413
+ // trendlines and error bars belong to the original's data. The series' own label settings stay.
414
+ for (const name of ['c:extLst', 'c:dPt', 'c:trendline', 'c:errBars'])
415
+ removeChildren(ser, name);
416
+ const labels = firstChild(ser, 'c:dLbls');
417
+ if (labels)
418
+ removeChildren(labels, 'c:dLbl');
419
+ const color = accentColor(idx);
420
+ recolor(firstChild(ser, 'c:spPr'), color);
421
+ recolor(childPath(ser, 'c:marker', 'c:spPr'), color);
422
+ last.plot.children.splice(last.plot.children.indexOf(last.ser) + 1, 0, ser);
423
+ slot = { plot: last.plot, ser };
424
+ }
425
+ else {
426
+ const plot = plotArea ? elements(plotArea).find(isPlot) : undefined;
427
+ if (!plot)
428
+ throw new ChartDataError('the chart has no plot to add a series to');
429
+ const ser = el('c:ser');
430
+ let at = 0;
431
+ plot.children.forEach((c, i) => {
432
+ if (c.type === 'element' && BEFORE_SER.has(c.name))
433
+ at = i + 1;
434
+ });
435
+ plot.children.splice(at, 0, ser);
436
+ slot = { plot, ser };
437
+ }
438
+ ensureChild(slot.ser, 'c:idx', SER_ORDER).attrs.val = String(idx);
439
+ ensureChild(slot.ser, 'c:order', SER_ORDER).attrs.val = String(order);
440
+ slot.added = true;
441
+ return slot;
442
+ }
443
+ function fillSeries(slot, i, data, categories, categoryFormat, ranges, keepFormulas) {
444
+ const { plot, ser } = slot;
445
+ const xy = plot.name === 'c:scatterChart' || plot.name === 'c:bubbleChart';
446
+ const tx = firstChild(ser, 'c:tx');
447
+ const cat = firstChild(ser, xy ? 'c:xVal' : 'c:cat');
448
+ const val = firstChild(ser, xy ? 'c:yVal' : 'c:val');
449
+ // With keepFormulas, existing references stay; added series have no cells, so they hold literals.
450
+ const formula = (old, fresh) => (!keepFormulas ? fresh : slot.added ? undefined : formulaOf(old));
451
+ replaceChild(ser, seriesName(formula(tx, ranges.name(i)), data.name), SER_ORDER);
452
+ // Number formats stay by position (an added series has its model's), unless new ones are given.
453
+ replaceChild(ser, categoryData(xy ? 'c:xVal' : 'c:cat', formula(cat, ranges.categories), categories, categoryFormat || formatCodeOf(cat), isNumeric(cat)), SER_ORDER);
454
+ replaceChild(ser, el(xy ? 'c:yVal' : 'c:val', {}, [numData(formula(val, ranges.values(i)), data.values, data.formatCode || formatCodeOf(val) || 'General')]), SER_ORDER);
455
+ // Formatting of points past the new last one goes.
456
+ const n = categories.length;
457
+ const pastEnd = (c, name) => c.type === 'element' && c.name === name && (numOf(c, 'c:idx') ?? -1) >= n;
458
+ ser.children = ser.children.filter((c) => !pastEnd(c, 'c:dPt'));
459
+ const labels = firstChild(ser, 'c:dLbls');
460
+ if (labels)
461
+ labels.children = labels.children.filter((c) => !pastEnd(c, 'c:dLbl'));
462
+ }
463
+ function patchData(chart, categories, categoryFormat, series, keepFormulas) {
464
+ const plotArea = firstChild(chart, 'c:plotArea');
465
+ const slots = orderedSeries(plotArea);
466
+ const removed = slots.splice(series.length);
467
+ for (const { plot, ser } of removed)
468
+ plot.children = plot.children.filter((c) => c !== ser);
469
+ // A plot left without series goes, and so do the axes only it used (a combination chart's secondary axes).
470
+ const emptied = new Set(removed.map((s) => s.plot).filter((p) => elements(p, 'c:ser').length === 0));
471
+ if (plotArea && emptied.size > 0) {
472
+ plotArea.children = plotArea.children.filter((c) => !(c.type === 'element' && emptied.has(c)));
473
+ const used = new Set(elements(plotArea).filter(isPlot).flatMap((p) => elements(p, 'c:axId').map((a) => attr(a, 'val'))));
474
+ plotArea.children = plotArea.children.filter((c) => !(c.type === 'element' && AXES.has(c.name) && !used.has(valOf(c, 'c:axId'))));
475
+ }
476
+ while (slots.length < series.length)
477
+ slots.push(addSeries(plotArea, slots));
478
+ const ranges = chartRanges(series.length, categories.length);
479
+ slots.forEach((slot, i) => fillSeries(slot, i, series[i], categories, categoryFormat, ranges, keepFormulas));
480
+ }
481
+ /** Set, replace or (with '') remove the c:title of a chart or axis, keeping the formatting it had. */
482
+ function setTitle(parent, order, value, size, vertical) {
483
+ if (value === '') {
484
+ removeChildren(parent, 'c:title');
485
+ return;
486
+ }
487
+ const title = firstChild(parent, 'c:title');
488
+ if (!title) {
489
+ insertOrdered(parent, newTitle(value, size, vertical), order);
490
+ return;
491
+ }
492
+ let rich = childPath(title, 'c:tx', 'c:rich');
493
+ if (rich && richText(rich) === value)
494
+ return;
495
+ if (!rich) {
496
+ // An automatic title or one linked to a cell: write the text in the formatting it was shown with.
497
+ const txPr = firstChild(title, 'c:txPr');
498
+ rich = txPr ? { ...cloneElement(txPr), name: 'c:rich' } : newRich(size, vertical);
499
+ removeChildren(title, 'c:tx');
500
+ insertOrdered(title, el('c:tx', {}, [rich]), TITLE_ORDER);
501
+ }
502
+ setRichText(rich, value);
503
+ }
504
+ function setLegend(chart, position) {
505
+ if (position === 'none') {
506
+ removeChildren(chart, 'c:legend');
507
+ return;
508
+ }
509
+ const legend = firstChild(chart, 'c:legend');
510
+ if (!legend) {
511
+ insertOrdered(chart, newLegend(position), CHART_ORDER);
512
+ return;
513
+ }
514
+ const pos = ensureChild(legend, 'c:legendPos', LEGEND_ORDER);
515
+ if (pos.attrs.val === LEGEND_POS[position])
516
+ return;
517
+ pos.attrs.val = LEGEND_POS[position];
518
+ // A manual layout would keep the legend where it was.
519
+ removeChildren(legend, 'c:layout');
520
+ }
521
+ /**
522
+ * Change an existing chart in place. New data rewrites every series' name, categories and values;
523
+ * series keep their formatting by position, added series copy the last one's in the next accent
524
+ * colour, and extra series are removed from the end, along with any plot (and the axes only it
525
+ * used) left without series. Formulas point into Sheet1 of the chart's own workbook (series i in
526
+ * column i + 1); with `keepFormulas`, for a chart linked to an outside workbook, existing references
527
+ * stay and only their caches change, while added series hold literal data. Categories or series
528
+ * alone are combined with the chart's current data. Throws ChartDataError (before changing
529
+ * anything) when the resulting table is invalid.
530
+ */
531
+ export function patchChartSpace(chartSpace, changes, options = {}) {
532
+ const chart = firstChild(chartSpace, 'c:chart');
533
+ if (!chart)
534
+ throw new ChartDataError('the chart part has no c:chart element');
535
+ if (changes.categories !== undefined || changes.series !== undefined) {
536
+ const current = changes.categories !== undefined && changes.series !== undefined ? undefined : readChartTable(chartSpace);
537
+ const categories = changes.categories ?? current.categories;
538
+ const series = changes.series ?? current.series;
539
+ validateChartData(undefined, undefined, categories, series);
540
+ patchData(chart, categories, changes.categoryFormat, series, options.keepFormulas === true);
541
+ }
542
+ if (changes.title !== undefined) {
543
+ setTitle(chart, CHART_ORDER, changes.title, 1400, false);
544
+ ensureChild(chart, 'c:autoTitleDeleted', CHART_ORDER).attrs.val = changes.title === '' ? '1' : '0';
545
+ }
546
+ if (changes.legend !== undefined)
547
+ setLegend(chart, changes.legend);
548
+ if (changes.axisTitles) {
549
+ const axes = chartAxes(chartSpace);
550
+ for (const key of ['category', 'value']) {
551
+ const value = changes.axisTitles[key];
552
+ const axis = axes[key];
553
+ if (value === undefined || !axis)
554
+ continue;
555
+ const pos = valOf(axis, 'c:axPos');
556
+ setTitle(axis, AXIS_ORDER, value, 1000, pos === 'l' || pos === 'r');
557
+ }
558
+ }
559
+ }
@@ -21,6 +21,8 @@ export declare const REL: {
21
21
  readonly hyperlink: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink';
22
22
  readonly image: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image';
23
23
  readonly font: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/font';
24
+ readonly chart: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart';
25
+ readonly package: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/package';
24
26
  };
25
27
  export type RelKind = keyof typeof REL;
26
28
  export declare const CONTENT_TYPE: {
@@ -47,6 +49,8 @@ export declare const CONTENT_TYPE: {
47
49
  readonly coreProperties: 'application/vnd.openxmlformats-package.core-properties+xml';
48
50
  readonly extendedProperties: 'application/vnd.openxmlformats-officedocument.extended-properties+xml';
49
51
  readonly obfuscatedFont: 'application/vnd.openxmlformats-officedocument.obfuscatedFont';
52
+ readonly chart: 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml';
53
+ readonly xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
50
54
  };
51
55
  export declare const IMAGE_CONTENT_TYPES: Record<string, string>;
52
56
  export declare function relTypeName(type: string): string;
@@ -21,6 +21,8 @@ export const REL = {
21
21
  hyperlink: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink',
22
22
  image: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image',
23
23
  font: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/font',
24
+ chart: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart',
25
+ package: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/package',
24
26
  };
25
27
  const WML = 'application/vnd.openxmlformats-officedocument.wordprocessingml';
26
28
  export const CONTENT_TYPE = {
@@ -47,6 +49,8 @@ export const CONTENT_TYPE = {
47
49
  coreProperties: 'application/vnd.openxmlformats-package.core-properties+xml',
48
50
  extendedProperties: 'application/vnd.openxmlformats-officedocument.extended-properties+xml',
49
51
  obfuscatedFont: 'application/vnd.openxmlformats-officedocument.obfuscatedFont',
52
+ chart: 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml',
53
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
50
54
  };
51
55
  export const IMAGE_CONTENT_TYPES = {
52
56
  png: 'image/png',