@nova-energy/openamx 0.10.1 → 0.11.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.
@@ -1,11 +1,22 @@
1
- import { Document, HeadingLevel, ImageRun, Packer, Paragraph, Table, TableCell, TableRow, TextRun, Footer } from 'docx';
2
- export function prepareDocxReport(report) {
3
- return preparePreparedDocxReport(report);
1
+ import { AlignmentType, Bookmark, BorderStyle, Document, ExternalHyperlink, HeadingLevel, ImageRun, InternalHyperlink, LevelFormat, Packer, Paragraph, Tab, TableLayoutType, Table, TableCell, TableRow, TextRun, WidthType, Footer } from 'docx';
2
+ import { ChartRun } from 'docx/charts';
3
+ import { realpathSync } from 'node:fs';
4
+ import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
5
+ import { createChartViewModel } from './chartModel';
6
+ import { fitNarrativeImage } from './narrativeModel';
7
+ const TABLE_WIDTH_TWIPS = 9_026;
8
+ // ChartRun uses 15 twips per CSS pixel; leave one pixel of page-width clearance.
9
+ const DOCX_CHART_WIDTH_PIXELS = Math.floor(TABLE_WIDTH_TWIPS / 15) - 1;
10
+ const IMAGE_WIDTH_PIXELS = 601;
11
+ const IMAGE_HEIGHT_PIXELS = 864;
12
+ const MAX_BOOKMARK_NAME_LENGTH = 40;
13
+ export function prepareDocxReport(report, context) {
14
+ return preparePreparedDocxReport(report, context);
4
15
  }
5
16
  export async function serializeDocxReport(report) {
6
17
  return Uint8Array.from(await Packer.toBuffer(report.document));
7
18
  }
8
- function preparePreparedDocxReport(report) {
19
+ function preparePreparedDocxReport(report, exportContext) {
9
20
  const children = [];
10
21
  const identity = report.identity;
11
22
  if (identity.logo || identity.organization || identity.author || identity.status || identity.classification) {
@@ -17,66 +28,314 @@ function preparePreparedDocxReport(report) {
17
28
  runs.push(new TextRun({ text: `${runs.length ? '\n' : ''}${metadata.join('\n')}`, bold: true }));
18
29
  children.push(new Paragraph({ children: runs }));
19
30
  }
31
+ const usedBookmarkNames = new Set();
32
+ const bookmarks = headingBookmarks(report.items.flatMap(item => item.type === 'narrative' ? item.markdown : []), usedBookmarkNames);
33
+ const numbering = [];
34
+ let nextListReference = 0;
20
35
  for (const item of report.items) {
21
- if (item.type === 'narrative')
22
- addNarrativeText(children, item.text);
36
+ if (item.type === 'narrative') {
37
+ const context = {
38
+ exportContext,
39
+ bookmarks,
40
+ numbering,
41
+ quoteDepth: 0,
42
+ listDepth: 0
43
+ };
44
+ children.push(...renderBlocks(item.markdown, context, () => `openamx-list-${nextListReference++}`));
45
+ }
23
46
  else if (item.type === 'source')
24
47
  children.push(new Paragraph({ style: 'Normal', children: [new TextRun({ text: item.text, font: 'Courier New', size: 18 })] }));
25
48
  else
26
- addEmission(children, item.emission);
49
+ addEmission(children, item.emission, identity);
27
50
  }
28
51
  return {
29
52
  document: new Document({
30
53
  title: report.title,
31
54
  creator: identity.author ?? 'OpenAMX',
32
55
  description: 'Editable OpenAMX report',
56
+ numbering: numbering.length > 0 ? { config: numbering } : undefined,
33
57
  sections: [{ children, footers: identity.footer ? { default: new Footer({ children: [new Paragraph({ text: identity.footer })] }) } : undefined }]
34
58
  })
35
59
  };
36
60
  }
37
- function addNarrativeText(children, narrative) {
38
- let paragraphLines = [];
39
- const flushParagraph = () => {
40
- if (paragraphLines.length > 0) {
41
- children.push(new Paragraph(paragraphLines.join(' ')));
42
- paragraphLines = [];
61
+ function renderBlocks(blocks, context, nextListReference) {
62
+ return blocks.flatMap(block => renderBlock(block, context, nextListReference));
63
+ }
64
+ function renderBlock(block, context, nextListReference) {
65
+ if (block.type === 'heading') {
66
+ const runs = inlineChildren(block.children, context);
67
+ const bookmark = context.bookmarks.get(block.id);
68
+ const children = bookmark ? [new Bookmark({ id: bookmark, children: runs })] : runs;
69
+ return [new Paragraph(paragraphOptions(context, { heading: headingLevel(block.depth), children }))];
70
+ }
71
+ if (block.type === 'paragraph') {
72
+ return [new Paragraph(paragraphOptions(context, { children: inlineChildren(block.children, context) }))];
73
+ }
74
+ if (block.type === 'code') {
75
+ return [new Paragraph(paragraphOptions(context, {
76
+ children: codeChildren(block.text),
77
+ shading: { fill: 'F1F4F5' },
78
+ indent: { left: 180, right: 180 },
79
+ spacing: { before: 80, after: 80 }
80
+ }))];
81
+ }
82
+ if (block.type === 'list') {
83
+ const parentItem = context.listItem;
84
+ const prefix = parentItem && !parentItem.applied ? [listMarkerParagraph(context)] : [];
85
+ return [...prefix, ...renderList(block, {
86
+ ...context,
87
+ listItem: undefined,
88
+ listDepth: context.listDepth + (parentItem ? 1 : 0)
89
+ }, nextListReference)];
90
+ }
91
+ if (block.type === 'blockquote') {
92
+ const nestedContext = {
93
+ ...context,
94
+ quoteDepth: context.quoteDepth + 1,
95
+ listItem: context.listItem
96
+ };
97
+ return renderBlocks(block.blocks, nestedContext, nextListReference);
98
+ }
99
+ if (block.type === 'table') {
100
+ const widths = tableColumnWidths(block.header.length);
101
+ const header = new TableRow({
102
+ tableHeader: true,
103
+ cantSplit: true,
104
+ children: block.header.map((cell, index) => narrativeTableCell(cell, context, widths[index], index, block.align, true))
105
+ });
106
+ const rows = block.rows.map(row => new TableRow({
107
+ cantSplit: true,
108
+ children: block.header.map((_headerCell, index) => narrativeTableCell(row[index] ?? [], context, widths[index], index, block.align, false))
109
+ }));
110
+ const table = new Table({
111
+ rows: [header, ...rows],
112
+ width: { size: 200, type: WidthType.PERCENTAGE },
113
+ columnWidths: widths,
114
+ layout: TableLayoutType.FIXED,
115
+ margins: { top: 80, bottom: 80, left: 100, right: 100 }
116
+ });
117
+ if (context.listItem && !context.listItem.applied) {
118
+ return [listMarkerParagraph(context), table];
43
119
  }
44
- };
45
- for (const line of narrative.split(/\r?\n/)) {
46
- const trimmed = line.trim();
47
- if (trimmed === '<!-- page-break -->') {
48
- flushParagraph();
49
- children.push(new Paragraph({ text: '', pageBreakBefore: true }));
50
- }
51
- else if (/^#{1,6}\s+/.test(trimmed)) {
52
- flushParagraph();
53
- const level = Math.min(6, (trimmed.match(/^#+/) ?? ['#'])[0].length);
54
- children.push(new Paragraph({
55
- text: trimmed.replace(/^#+\s+/, ''),
56
- heading: headingLevel(level)
57
- }));
120
+ return [table];
121
+ }
122
+ if (block.type === 'horizontalRule') {
123
+ return [new Paragraph(paragraphOptions(context, {
124
+ children: [new TextRun({ text: ' ' })],
125
+ border: { bottom: { style: BorderStyle.SINGLE, size: 6, color: '8A969C', space: 1 } },
126
+ spacing: { before: 120, after: 120 }
127
+ }))];
128
+ }
129
+ return [new Paragraph(paragraphOptions(context, { children: [], includeIfEmpty: true, pageBreakBefore: true }))];
130
+ }
131
+ function paragraphOptions(context, options) {
132
+ const quoteIndent = context.quoteDepth * 360;
133
+ const listItem = context.listItem;
134
+ const listIndent = listItem ? (listItem.level + 1) * 720 : 0;
135
+ const children = [...(options.children ?? [])];
136
+ if (listItem && !listItem.applied) {
137
+ if (listItem.checked !== undefined) {
138
+ children.unshift(new TextRun({ text: listItem.checked ? '[x] ' : '[ ] ' }));
139
+ }
140
+ listItem.applied = true;
141
+ return {
142
+ ...options,
143
+ children,
144
+ numbering: { reference: listItem.reference, level: listItem.level },
145
+ ...(quoteIndent > 0 ? { indent: { left: quoteIndent } } : {})
146
+ };
147
+ }
148
+ if (listItem || quoteIndent > 0) {
149
+ return {
150
+ ...options,
151
+ children,
152
+ indent: { left: listIndent + quoteIndent }
153
+ };
154
+ }
155
+ return { ...options, children };
156
+ }
157
+ function renderList(block, context, nextListReference) {
158
+ const reference = nextListReference();
159
+ const level = Math.min(context.listDepth, 8);
160
+ context.numbering.push({
161
+ reference,
162
+ levels: Array.from({ length: 9 }, (_value, index) => ({
163
+ level: index,
164
+ format: block.ordered ? LevelFormat.DECIMAL : LevelFormat.BULLET,
165
+ text: block.ordered ? `%${index + 1}.` : ['•', '◦', '▪'][index % 3],
166
+ ...(block.ordered && index === level && block.start !== undefined ? { start: block.start } : {}),
167
+ style: { paragraph: { indent: { left: (index + 1) * 720, hanging: 360 } } }
168
+ }))
169
+ });
170
+ const output = [];
171
+ for (const item of block.items) {
172
+ const listItem = { reference, level, checked: item.checked, applied: false };
173
+ const itemContext = { ...context, listItem };
174
+ for (const child of item.blocks) {
175
+ output.push(...renderBlock(child, itemContext, nextListReference));
176
+ }
177
+ if (!listItem.applied)
178
+ output.push(listMarkerParagraph(itemContext));
179
+ }
180
+ return output;
181
+ }
182
+ function listMarkerParagraph(context) {
183
+ return new Paragraph(paragraphOptions(context, { children: [], includeIfEmpty: true }));
184
+ }
185
+ function inlineChildren(inlines, context, style = {}) {
186
+ const children = [];
187
+ for (const inline of inlines) {
188
+ if (inline.type === 'text') {
189
+ if (inline.text)
190
+ children.push(new TextRun({ text: inline.text, ...style }));
191
+ }
192
+ else if (inline.type === 'lineBreak') {
193
+ children.push(new TextRun({ break: 1, ...style }));
58
194
  }
59
- else if (/^[-*]\s+/.test(trimmed)) {
60
- flushParagraph();
61
- children.push(new Paragraph({
62
- text: trimmed.replace(/^[-*]\s+/, ''),
63
- bullet: { level: 0 }
195
+ else if (inline.type === 'inlineCode') {
196
+ children.push(new TextRun({
197
+ text: inline.text,
198
+ font: 'Consolas',
199
+ size: 18,
200
+ shading: { fill: 'F1F4F5' },
201
+ ...style
64
202
  }));
65
203
  }
66
- else if (trimmed === '') {
67
- flushParagraph();
204
+ else if (inline.type === 'strong' || inline.type === 'emphasis' || inline.type === 'delete') {
205
+ const nestedStyle = inline.type === 'strong'
206
+ ? { ...style, bold: true }
207
+ : inline.type === 'emphasis'
208
+ ? { ...style, italics: true }
209
+ : { ...style, strike: true };
210
+ children.push(...inlineChildren(inline.children, context, nestedStyle));
68
211
  }
69
- else {
70
- paragraphLines.push(line.trim());
212
+ else if (inline.type === 'link') {
213
+ const linkChildren = inlineChildren(inline.children, context, { ...style, color: '0563C1', underline: {} });
214
+ const link = inline.link;
215
+ if (link.type === 'external') {
216
+ children.push(new ExternalHyperlink({ link: link.href, children: linkChildren }));
217
+ }
218
+ else if (link.type === 'internal') {
219
+ const anchor = context.bookmarks.get(link.targetId);
220
+ if (anchor)
221
+ children.push(new InternalHyperlink({ anchor, children: linkChildren }));
222
+ else
223
+ children.push(...linkChildren);
224
+ }
225
+ else {
226
+ children.push(new ExternalHyperlink({ link: localLinkUri(link, context.exportContext), children: linkChildren }));
227
+ }
228
+ }
229
+ else if (inline.type === 'image') {
230
+ children.push(narrativeImageRun(inline.image));
71
231
  }
72
232
  }
73
- flushParagraph();
233
+ return children;
234
+ }
235
+ function codeChildren(text) {
236
+ const runs = [];
237
+ const lines = text.split('\n');
238
+ lines.forEach((line, lineIndex) => {
239
+ if (lineIndex > 0)
240
+ runs.push(new TextRun({ break: 1, font: 'Consolas', size: 18 }));
241
+ const pieces = line.split('\t');
242
+ pieces.forEach((piece, pieceIndex) => {
243
+ if (pieceIndex > 0)
244
+ runs.push(new TextRun({ children: [new Tab()], font: 'Consolas', size: 18 }));
245
+ if (piece)
246
+ runs.push(new TextRun({ text: piece, font: 'Consolas', size: 18 }));
247
+ });
248
+ });
249
+ return runs.length > 0 ? runs : [new TextRun({ text: '', font: 'Consolas', size: 18 })];
250
+ }
251
+ function narrativeImageRun(image) {
252
+ const dimensions = fitNarrativeImage(image, { maxWidth: IMAGE_WIDTH_PIXELS, maxHeight: IMAGE_HEIGHT_PIXELS });
253
+ return new ImageRun({
254
+ type: image.format === 'jpeg' ? 'jpg' : 'png',
255
+ data: image.dataUri,
256
+ transformation: dimensions,
257
+ altText: { title: image.alt, description: image.alt, name: image.alt }
258
+ });
259
+ }
260
+ function narrativeTableCell(inlines, context, width, index, align, header) {
261
+ const children = inlineChildren(inlines, context, header ? { bold: true } : {});
262
+ return new TableCell({
263
+ children: [new Paragraph({
264
+ children,
265
+ alignment: tableAlignment(align[index])
266
+ })],
267
+ width: { size: width, type: WidthType.DXA },
268
+ verticalAlign: 'center',
269
+ ...(header ? { shading: { fill: 'E7EEE8' } } : {})
270
+ });
271
+ }
272
+ function tableAlignment(align) {
273
+ if (align === 'center')
274
+ return AlignmentType.CENTER;
275
+ if (align === 'right')
276
+ return AlignmentType.RIGHT;
277
+ if (align === 'left')
278
+ return AlignmentType.LEFT;
279
+ return undefined;
280
+ }
281
+ function tableColumnWidths(count) {
282
+ if (count === 0)
283
+ throw new Error('Narrative table must contain at least one column.');
284
+ const width = Math.floor(TABLE_WIDTH_TWIPS / count);
285
+ const remainder = TABLE_WIDTH_TWIPS - width * count;
286
+ return Array.from({ length: count }, (_value, index) => width + (index === 0 ? remainder : 0));
287
+ }
288
+ function headingBookmarks(blocks, usedNames) {
289
+ const bookmarks = new Map();
290
+ const visit = (items) => {
291
+ for (const block of items) {
292
+ if (block.type === 'heading') {
293
+ if (!bookmarks.has(block.id))
294
+ bookmarks.set(block.id, uniqueBookmarkName(block.id, usedNames));
295
+ }
296
+ else if (block.type === 'blockquote') {
297
+ visit(block.blocks);
298
+ }
299
+ else if (block.type === 'list') {
300
+ for (const item of block.items)
301
+ visit(item.blocks);
302
+ }
303
+ }
304
+ };
305
+ visit(blocks);
306
+ return bookmarks;
74
307
  }
75
- function addEmission(children, emission) {
308
+ function uniqueBookmarkName(id, usedNames) {
309
+ const normalized = `amx_${id.replace(/[^A-Za-z0-9_]/g, '_')}`.slice(0, MAX_BOOKMARK_NAME_LENGTH);
310
+ let suffix = 0;
311
+ let candidate = normalized || 'amx_section';
312
+ while (usedNames.has(candidate)) {
313
+ suffix++;
314
+ const ending = `_${suffix}`;
315
+ candidate = `${normalized.slice(0, MAX_BOOKMARK_NAME_LENGTH - ending.length)}${ending}`;
316
+ }
317
+ usedNames.add(candidate);
318
+ return candidate;
319
+ }
320
+ function localLinkUri(link, context) {
321
+ if (!context)
322
+ throw new Error('DOCX local links require validated source-document and final-destination context.');
323
+ if (link.sourceBase !== 'document-directory')
324
+ throw new Error('DOCX local link has an unsupported source base.');
325
+ const sourceDirectory = realpathSync(dirname(resolve(context.sourceDocumentPath)));
326
+ const outputDirectory = dirname(resolve(context.destinationPath));
327
+ const sourceTarget = resolve(sourceDirectory, ...link.path.split('/'));
328
+ const relativePath = relative(outputDirectory, sourceTarget);
329
+ if (!relativePath || isAbsolute(relativePath))
330
+ throw new Error('DOCX local link target cannot be represented relative to the final DOCX destination.');
331
+ const encodedPath = relativePath.split(sep).map(segment => encodeURIComponent(segment)).join('/');
332
+ return `${encodedPath}${link.query === undefined ? '' : `?${link.query}`}${link.fragment === undefined ? '' : `#${link.fragment}`}`;
333
+ }
334
+ function addEmission(children, emission, identity) {
76
335
  if (emission.kind === 'table')
77
336
  addTable(children, emission);
78
337
  else
79
- addChart(children, emission);
338
+ addChart(children, emission, identity);
80
339
  }
81
340
  function addTable(children, emission) {
82
341
  const title = emission.declaration.options.find(option => option.type === 'viewTitleOption');
@@ -89,65 +348,368 @@ function addTable(children, emission) {
89
348
  }));
90
349
  children.push(new Table({ rows: [header, ...rows] }));
91
350
  }
92
- function addChart(children, emission) {
93
- const title = emission.declaration.options.find(option => option.type === 'viewTitleOption');
94
- const description = emission.declaration.options.find(option => option.type === 'viewDescriptionOption');
95
- const caption = title?.type === 'viewTitleOption' ? title.value : emission.name;
96
- const detail = description?.type === 'viewDescriptionOption' ? description.value : `${emission.kind} chart`;
97
- const rows = chartRows(emission);
98
- children.push(new Paragraph({ text: caption, heading: HeadingLevel.HEADING_2 }));
99
- children.push(new Paragraph(detail));
100
- if (rows.length > 0) {
101
- children.push(new Paragraph({
102
- children: [new ImageRun({
103
- type: 'svg',
104
- data: new TextEncoder().encode(chartSvg(rows)),
105
- transformation: { width: 480, height: 180 },
106
- fallback: { type: 'png', data: transparentPng }
107
- })]
108
- }));
351
+ function addChart(children, emission, identity) {
352
+ const model = createChartViewModel(emission, identity);
353
+ children.push(new Paragraph({ text: model.title, heading: HeadingLevel.HEADING_2 }));
354
+ children.push(new Paragraph(model.description));
355
+ if (model.plottedPointCount === 0) {
356
+ addNoChartAlternative(children, model, 'Chart not shown: no plottable data.');
357
+ return;
358
+ }
359
+ if (model.kind === 'scatter') {
360
+ const chartSeries = scatterChartSeries(model);
361
+ if (chartSeries.some(series => series.points.length === 0)) {
362
+ addNoChartAlternative(children, model, 'Chart not shown: Word cannot represent a scatter group with no plottable points.');
363
+ return;
364
+ }
365
+ const run = new ChartRun({
366
+ type: 'scatter',
367
+ title: chartTitle(model, identity.accent),
368
+ altText: chartAltText(model),
369
+ series: chartSeries,
370
+ markers: true,
371
+ lines: 'none',
372
+ legend: chartSeries.length > 1 ? {} : false,
373
+ xAxis: chartValueAxis(model.axes.find(axis => axis.role === 'x')),
374
+ yAxis: chartValueAxis(model.axes.find(axis => axis.role === 'y')),
375
+ transformation: docxChartDimensions(model)
376
+ });
377
+ children.push(new Paragraph({ children: [run] }));
378
+ addChartTable(children, model);
379
+ return;
380
+ }
381
+ if (model.kind === 'line' && numericXAxis(model)) {
382
+ const plotted = numericLineScatterSeries(model);
383
+ if (plotted.series.length === 0) {
384
+ addNoChartAlternative(children, model, 'Chart not shown: no plottable data.');
385
+ return;
386
+ }
387
+ const valueAxes = activeNumericLineAxes(model, plotted.activeAxisIds);
388
+ if (valueAxes.length > 1) {
389
+ addNoChartAlternative(children, model, 'Chart not shown: Word cannot represent all measurement axes without changing their meaning.');
390
+ return;
391
+ }
392
+ const description = [
393
+ ...plotted.omittedSeries.map(name => `Series "${name}" has no plottable coordinates and is listed only in the complete data table.`),
394
+ ...(plotted.hasGaps ? ['Null gaps break the line; continued segments are hidden from the legend.'] : [])
395
+ ];
396
+ const run = new ChartRun({
397
+ type: 'scatter',
398
+ title: chartTitle(model, identity.accent),
399
+ altText: chartAltText(model, description),
400
+ series: plotted.series,
401
+ markers: true,
402
+ lines: 'straight',
403
+ legend: model.series.length > 1
404
+ ? { hiddenEntries: plotted.hiddenLegendEntries }
405
+ : false,
406
+ xAxis: chartValueAxis(model.axes.find(axis => axis.role === 'x')),
407
+ yAxis: chartValueAxis(valueAxes[0]),
408
+ transformation: docxChartDimensions(model)
409
+ });
410
+ children.push(new Paragraph({ children: [run] }));
411
+ if (plotted.omittedSeries.length > 0) {
412
+ children.push(new Paragraph(`Series with no plottable coordinates, shown only in the complete table: ${plotted.omittedSeries.join(', ')}.`));
413
+ }
414
+ addChartTable(children, model);
415
+ return;
416
+ }
417
+ if (model.kind === 'line' && model.dateTimePresentation === 'UTC ISO 8601') {
418
+ const plotted = dateTimeLineSeries(model);
419
+ if (plotted.categories.length === 0 || !plotted.hasPlottablePoints) {
420
+ addNoChartAlternative(children, model, 'Chart not shown: no plottable data.');
421
+ return;
422
+ }
423
+ const valueAxes = model.axes.filter(axis => axis.role === 'y');
424
+ if (valueAxes.length > 2) {
425
+ addNoChartAlternative(children, model, 'Chart not shown: Word cannot represent all measurement axes without changing their meaning.');
426
+ return;
427
+ }
428
+ const run = new ChartRun({
429
+ type: 'line',
430
+ title: chartTitle(model, identity.accent),
431
+ altText: chartAltText(model, plotted.hasGaps ? ['DateTime rows with null x coordinates break the line; continued segments are hidden from the legend.'] : []),
432
+ categories: plotted.categories,
433
+ series: plotted.series,
434
+ markers: true,
435
+ emptyValues: 'gap',
436
+ legend: model.series.length > 1 ? { hiddenEntries: plotted.hiddenLegendEntries } : false,
437
+ valueAxis: chartValueAxis(valueAxes[0]),
438
+ ...(valueAxes.length > 1 ? { secondaryValueAxis: chartValueAxis(valueAxes[1]) } : {}),
439
+ transformation: docxChartDimensions(model)
440
+ });
441
+ children.push(new Paragraph({ children: [run] }));
442
+ addChartTable(children, model);
443
+ return;
109
444
  }
110
- else {
111
- children.push(new Paragraph('No data'));
445
+ const valueAxisRole = model.kind === 'bar' ? 'x' : 'y';
446
+ const valueAxes = model.axes.filter(axis => axis.role === valueAxisRole);
447
+ if (valueAxes.length > 2) {
448
+ addNoChartAlternative(children, model, 'Chart not shown: Word cannot represent all measurement axes without changing their meaning.');
449
+ return;
112
450
  }
113
- const headings = emission.headings ? [...emission.headings] : emission.declaration.kind === 'scatter'
114
- ? ['x', 'y', 'group']
115
- : ['label', ...emission.declaration.options.filter(option => option.type === 'chartSeriesOption').map(option => option.label)];
116
- const tableRows = [
117
- new TableRow({ children: headings.map(heading => tableCell(heading, true)) }),
118
- ...rows.map(row => new TableRow({ children: row.map(value => tableCell(valueToString(value))) }))
119
- ];
120
- children.push(new Table({ rows: tableRows }));
451
+ const categories = model.table.rows.map(row => chartCategory(row.values[0], model.dateTimePresentation === 'UTC ISO 8601'));
452
+ const series = model.series.map((item, seriesIndex) => {
453
+ const axisIndex = valueAxes.findIndex(axis => axis.id === item.axisId);
454
+ if (axisIndex < 0)
455
+ throw new Error(`DOCX chart series "${item.name}" has no matching value axis.`);
456
+ return {
457
+ name: item.name,
458
+ color: chartColorForDocx(item.color),
459
+ values: model.table.rows.map(row => chartNumber(row.values[seriesIndex + 1])),
460
+ ...(valueAxes.length > 1 ? { axis: axisIndex === 0 ? 'primary' : 'secondary' } : {}),
461
+ ...(model.kind === 'line' ? { markers: true } : {})
462
+ };
463
+ });
464
+ const run = new ChartRun({
465
+ type: model.kind,
466
+ title: chartTitle(model, identity.accent),
467
+ altText: chartAltText(model),
468
+ categories,
469
+ series,
470
+ legend: model.series.length > 1 ? {} : false,
471
+ ...(model.kind === 'bar' ? { categoryAxis: { reverseOrder: true } } : {}),
472
+ ...(model.kind === 'line' ? { emptyValues: 'gap' } : {}),
473
+ valueAxis: chartValueAxis(valueAxes[0]),
474
+ ...(valueAxes.length > 1 ? { secondaryValueAxis: chartValueAxis(valueAxes[1]) } : {}),
475
+ transformation: docxChartDimensions(model)
476
+ });
477
+ children.push(new Paragraph({ children: [run] }));
478
+ addChartTable(children, model);
121
479
  }
122
- function tableCell(value, bold = false) {
123
- return new TableCell({ children: [new Paragraph({ children: [new TextRun({ text: value, bold })] })] });
480
+ function docxChartDimensions(model) {
481
+ const width = Math.min(model.dimensions.width, DOCX_CHART_WIDTH_PIXELS);
482
+ return {
483
+ width,
484
+ height: Math.round(model.dimensions.height * width / model.dimensions.width)
485
+ };
486
+ }
487
+ function addNoChartAlternative(children, model, notice) {
488
+ children.push(new Paragraph(notice));
489
+ addChartTable(children, model);
124
490
  }
125
- function chartRows(emission) {
126
- const options = emission.declaration.options;
127
- const category = options.find(option => option.type === 'chartFieldOption' && option.role === 'category');
128
- const x = options.find(option => option.type === 'chartFieldOption' && option.role === 'x');
129
- const y = options.find(option => option.type === 'chartFieldOption' && option.role === 'y');
130
- const group = options.find(option => option.type === 'chartFieldOption' && option.role === 'group');
131
- const series = options.filter(option => option.type === 'chartSeriesOption');
132
- const labels = emission.labels ?? emission.data.map((_value, index) => String(index + 1));
133
- return emission.data.map((value, index) => {
134
- if (isRecord(value)) {
135
- if (emission.declaration.kind === 'scatter')
136
- return [value[x?.type === 'chartFieldOption' ? x.field : 'x'], value[y?.type === 'chartFieldOption' ? y.field : 'y'], group?.type === 'chartFieldOption' ? value[group.field] : ''];
137
- return [category?.type === 'chartFieldOption' ? value[category.field] : labels[index], ...series.map(option => option.type === 'chartSeriesOption' && option.field ? value[option.field] : null)];
138
- }
139
- return [labels[index], value];
491
+ function addChartTable(children, model) {
492
+ const header = new TableRow({
493
+ tableHeader: true,
494
+ cantSplit: true,
495
+ children: model.table.headings.map(heading => tableCell(heading, true))
140
496
  });
497
+ const rows = model.table.rows.map(row => new TableRow({
498
+ cantSplit: true,
499
+ children: row.values.map(value => tableCell(valueToString(value)))
500
+ }));
501
+ children.push(new Paragraph({ text: model.table.caption, heading: HeadingLevel.HEADING_3 }));
502
+ const columnCount = Math.max(1, model.table.headings.length);
503
+ const baseColumnWidth = Math.floor(TABLE_WIDTH_TWIPS / columnCount);
504
+ children.push(new Table({
505
+ rows: [header, ...rows],
506
+ width: { size: 200, type: WidthType.PERCENTAGE },
507
+ columnWidths: model.table.headings.map((_heading, index) => index === columnCount - 1 ? TABLE_WIDTH_TWIPS - baseColumnWidth * (columnCount - 1) : baseColumnWidth),
508
+ layout: TableLayoutType.FIXED,
509
+ margins: { top: 80, bottom: 80, left: 100, right: 100 }
510
+ }));
511
+ }
512
+ function chartAltText(model, details = []) {
513
+ return {
514
+ name: model.accessibility.tableId,
515
+ title: model.accessibility.title,
516
+ description: [model.accessibility.description, model.accessibility.summary, ...details].join(' ')
517
+ };
518
+ }
519
+ function chartTitle(model, accent) {
520
+ return { text: model.title, font: { color: chartColorForDocx(accent) } };
141
521
  }
142
- function chartSvg(rows) {
143
- const values = rows.flatMap(row => row.slice(1)).filter((value) => typeof value === 'number' && Number.isFinite(value));
144
- const max = Math.max(1, ...values.map(value => Math.abs(value)));
145
- const bars = rows.flatMap((row, rowIndex) => row.slice(1).map((value, seriesIndex) => typeof value === 'number'
146
- ? `<rect x="${40 + rowIndex * 560 / Math.max(1, rows.length) + seriesIndex * 14}" y="${145 - value / max * 105}" width="12" height="${Math.max(0, value / max * 105)}" fill="${['#146c94', '#d97706', '#15803d'][seriesIndex % 3]}"/>`
147
- : '')).join('');
148
- return `<svg width="600" height="160" viewBox="0 0 600 160" xmlns="http://www.w3.org/2000/svg"><line x1="40" y1="145" x2="580" y2="145" stroke="#58675d"/>${bars}</svg>`;
522
+ function chartValueAxis(axis) {
523
+ return axis?.name ? { title: axis.name } : undefined;
524
+ }
525
+ function chartCategory(value, dateTime) {
526
+ if (dateTime) {
527
+ if (typeof value !== 'string' || Number.isNaN(Date.parse(value))) {
528
+ throw new Error('DOCX DateTime chart categories must contain valid date-time values.');
529
+ }
530
+ return new Date(value);
531
+ }
532
+ if (value === null || value === undefined)
533
+ return '';
534
+ if (typeof value === 'string' || typeof value === 'number')
535
+ return value;
536
+ throw new Error('DOCX chart categories must be strings, numbers, or DateTime values.');
537
+ }
538
+ function chartNumber(value) {
539
+ if (value === null || value === undefined)
540
+ return null;
541
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
542
+ throw new Error('DOCX chart values must be finite numbers or null.');
543
+ }
544
+ return value;
545
+ }
546
+ function chartColorForDocx(color) {
547
+ return color.replace(/^#/, '');
548
+ }
549
+ function numericXAxis(model) {
550
+ const axis = Array.isArray(model.option.xAxis) ? model.option.xAxis[0] : model.option.xAxis;
551
+ return axis?.type === 'value';
552
+ }
553
+ function scatterChartSeries(model) {
554
+ const grouped = model.table.headings.length > 2;
555
+ const indices = new Map();
556
+ const points = model.series.map(() => []);
557
+ for (const row of model.table.rows) {
558
+ const groupValue = grouped ? row.values[2] ?? null : null;
559
+ const key = groupValue === null ? '__ungrouped__' : `${typeof groupValue}:${String(groupValue)}`;
560
+ let index = indices.get(key);
561
+ if (index === undefined) {
562
+ index = indices.size;
563
+ if (index >= points.length)
564
+ throw new Error('DOCX scatter table groups do not match the chart model series.');
565
+ indices.set(key, index);
566
+ }
567
+ const x = row.values[0];
568
+ const y = row.values[1];
569
+ if (x === null || y === null)
570
+ continue;
571
+ if (typeof x !== 'number' || !Number.isFinite(x) || typeof y !== 'number' || !Number.isFinite(y)) {
572
+ throw new Error('DOCX scatter coordinates must be finite numbers or null.');
573
+ }
574
+ points[index].push({ x, y });
575
+ }
576
+ return model.series.map((series, index) => ({
577
+ name: series.name,
578
+ color: chartColorForDocx(series.color),
579
+ points: points[index]
580
+ }));
581
+ }
582
+ function numericLineScatterSeries(model) {
583
+ const series = [];
584
+ const omittedSeries = [];
585
+ const hiddenLegendEntries = [];
586
+ const activeAxisIds = new Set();
587
+ const occupiedNames = new Set(model.series.map(item => item.name));
588
+ let hasGaps = false;
589
+ for (let seriesIndex = 0; seriesIndex < model.series.length; seriesIndex++) {
590
+ const item = model.series[seriesIndex];
591
+ const segments = [];
592
+ let current = [];
593
+ const finishSegment = () => {
594
+ if (current.length > 0)
595
+ segments.push(current);
596
+ current = [];
597
+ };
598
+ for (const row of model.table.rows) {
599
+ const x = row.values[0];
600
+ const y = row.values[seriesIndex + 1];
601
+ if (x === null || y === null) {
602
+ if (current.length > 0)
603
+ hasGaps = true;
604
+ finishSegment();
605
+ continue;
606
+ }
607
+ if (typeof x !== 'number' || !Number.isFinite(x) || typeof y !== 'number' || !Number.isFinite(y)) {
608
+ throw new Error('Numeric-X line chart coordinates must be finite numbers or null.');
609
+ }
610
+ current.push({ x, y });
611
+ }
612
+ finishSegment();
613
+ if (segments.length === 0) {
614
+ omittedSeries.push(item.name);
615
+ continue;
616
+ }
617
+ if (item.axisId)
618
+ activeAxisIds.add(item.axisId);
619
+ segments.forEach((segment, segmentIndex) => {
620
+ let name = item.name;
621
+ if (segmentIndex > 0) {
622
+ let suffix = segmentIndex + 1;
623
+ name = `${item.name} (OpenAMX segment ${suffix})`;
624
+ while (occupiedNames.has(name))
625
+ name = `${item.name} (OpenAMX segment ${++suffix})`;
626
+ occupiedNames.add(name);
627
+ hiddenLegendEntries.push(name);
628
+ }
629
+ series.push({
630
+ name,
631
+ color: chartColorForDocx(item.color),
632
+ points: segment
633
+ });
634
+ });
635
+ }
636
+ return { series, omittedSeries, hiddenLegendEntries, activeAxisIds: [...activeAxisIds], hasGaps };
637
+ }
638
+ function dateTimeLineSeries(model) {
639
+ const categories = [];
640
+ const rowCategoryIndices = [];
641
+ for (const row of model.table.rows) {
642
+ const value = row.values[0];
643
+ if (value === null) {
644
+ rowCategoryIndices.push(undefined);
645
+ continue;
646
+ }
647
+ if (typeof value !== 'string' || Number.isNaN(Date.parse(value))) {
648
+ throw new Error('DOCX DateTime chart categories must contain valid date-time values or null.');
649
+ }
650
+ rowCategoryIndices.push(categories.length);
651
+ categories.push(new Date(value));
652
+ }
653
+ const series = [];
654
+ const hiddenLegendEntries = [];
655
+ const occupiedNames = new Set(model.series.map(item => item.name));
656
+ let hasPlottablePoints = false;
657
+ let hasGaps = false;
658
+ for (let seriesIndex = 0; seriesIndex < model.series.length; seriesIndex++) {
659
+ const item = model.series[seriesIndex];
660
+ const segments = [];
661
+ let current = Array(categories.length).fill(null);
662
+ let hasCategory = false;
663
+ const finishSegment = () => {
664
+ if (hasCategory)
665
+ segments.push(current);
666
+ current = Array(categories.length).fill(null);
667
+ hasCategory = false;
668
+ };
669
+ for (let rowIndex = 0; rowIndex < model.table.rows.length; rowIndex++) {
670
+ const categoryIndex = rowCategoryIndices[rowIndex];
671
+ if (categoryIndex === undefined) {
672
+ if (hasCategory)
673
+ hasGaps = true;
674
+ finishSegment();
675
+ continue;
676
+ }
677
+ hasCategory = true;
678
+ const value = chartNumber(model.table.rows[rowIndex].values[seriesIndex + 1]);
679
+ current[categoryIndex] = value;
680
+ if (value !== null)
681
+ hasPlottablePoints = true;
682
+ }
683
+ finishSegment();
684
+ if (segments.length === 0 && categories.length > 0) {
685
+ segments.push(Array(categories.length).fill(null));
686
+ }
687
+ segments.forEach((values, segmentIndex) => {
688
+ let name = item.name;
689
+ if (segmentIndex > 0) {
690
+ let suffix = segmentIndex + 1;
691
+ name = `${item.name} (OpenAMX segment ${suffix})`;
692
+ while (occupiedNames.has(name))
693
+ name = `${item.name} (OpenAMX segment ${++suffix})`;
694
+ occupiedNames.add(name);
695
+ hiddenLegendEntries.push(name);
696
+ }
697
+ series.push({
698
+ name,
699
+ color: chartColorForDocx(item.color),
700
+ values
701
+ });
702
+ });
703
+ }
704
+ return { categories, series, hiddenLegendEntries, hasPlottablePoints, hasGaps };
705
+ }
706
+ function activeNumericLineAxes(model, activeAxisIds) {
707
+ const activeIds = new Set(activeAxisIds);
708
+ return model.axes.filter(axis => axis.role === 'y' && activeIds.has(axis.id));
709
+ }
710
+ function tableCell(value, bold = false) {
711
+ return new TableCell({ children: [new Paragraph({ children: [new TextRun({ text: value, bold })] })] });
149
712
  }
150
- const transparentPng = Uint8Array.from(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=', 'base64'));
151
713
  function headingLevel(level) {
152
714
  return [HeadingLevel.HEADING_1, HeadingLevel.HEADING_2, HeadingLevel.HEADING_3, HeadingLevel.HEADING_4, HeadingLevel.HEADING_5, HeadingLevel.HEADING_6][level - 1];
153
715
  }