@nova-energy/openamx 0.11.0 → 0.14.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/README.md +42 -10
- package/dist/cli.js +5 -5
- package/dist/editor/completion.js +199 -6
- package/dist/editor/highlighting.js +63 -4
- package/dist/editor/moduleAnalysis.js +8 -2
- package/dist/editor/refactoring.js +5 -2
- package/dist/editor/sourceRanges.js +3 -1
- package/dist/editor/symbols.js +195 -30
- package/dist/formatter/formatAmx.js +83 -7
- package/dist/parser/parseExpression.js +82 -3
- package/dist/parser/parseIf.js +180 -0
- package/dist/parser/parseStatements.js +232 -7
- package/dist/renderer/diagramBrowserEntry.js +255 -0
- package/dist/renderer/diagramBrowserRuntime.js +2 -0
- package/dist/renderer/diagramHtml.js +47 -0
- package/dist/renderer/narrativeModel.js +36 -11
- package/dist/renderer/renderHtml.js +95 -41
- package/dist/renderer/reportDocx.js +38 -16
- package/dist/renderer/reportPdf.js +122 -35
- package/dist/renderer/reportPreparation.js +97 -23
- package/dist/renderer/reportSequence.js +29 -0
- package/dist/renderer/staticDiagram.js +94 -0
- package/dist/runtime/diagramModel.js +455 -0
- package/dist/runtime/environment.js +8 -0
- package/dist/runtime/evaluateExpression.js +194 -10
- package/dist/runtime/inputData.js +20 -18
- package/dist/runtime/moduleLoader.js +76 -4
- package/dist/runtime/outputData.js +18 -12
- package/dist/runtime/standardLibrary.js +208 -1
- package/dist/runtime/valueSerialization.js +12 -0
- package/dist/typechecker/checkDocument.js +496 -16
- package/package.json +1 -1
|
@@ -9,8 +9,11 @@ import { AmxError } from '../diagnostics/errors';
|
|
|
9
9
|
import { parseExpression } from '../parser/parseExpression';
|
|
10
10
|
import { evaluateExpression } from '../runtime/evaluateExpression';
|
|
11
11
|
import { evaluateDocumentEnvironment } from '../runtime/evaluateDocument';
|
|
12
|
+
import { formatAmxValue } from '../runtime/valueSerialization';
|
|
12
13
|
import { formatAmx } from '../formatter/formatAmx';
|
|
13
14
|
import { createChartViewModel } from './chartModel';
|
|
15
|
+
import diagramBrowserRuntime from './diagramBrowserRuntime';
|
|
16
|
+
import { assertDiagramHtmlSize, renderDiagramAssets, renderDiagramFigure } from './diagramHtml';
|
|
14
17
|
import { fitNarrativeImage } from './narrativeModel';
|
|
15
18
|
import { hasSymlink, isContained } from './reportPaths';
|
|
16
19
|
const REPORT_MARKDOWN_POLICY = {
|
|
@@ -46,7 +49,21 @@ export function renderHtml(doc, file, env, options) {
|
|
|
46
49
|
emissions.push(emission);
|
|
47
50
|
emissionsByNode.set(emission.documentNodeIndex, emissions);
|
|
48
51
|
}
|
|
52
|
+
const diagramsByNode = new Map();
|
|
53
|
+
const importedDiagrams = [];
|
|
54
|
+
const entryFile = file ? canonicalReportFile(file) : undefined;
|
|
55
|
+
for (const { model } of environment.diagramEmissions) {
|
|
56
|
+
if (entryFile && model.file && canonicalReportFile(model.file) !== entryFile) {
|
|
57
|
+
importedDiagrams.push(model);
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
const diagrams = diagramsByNode.get(model.documentNodeIndex) ?? [];
|
|
61
|
+
diagrams.push(model);
|
|
62
|
+
diagramsByNode.set(model.documentNodeIndex, diagrams);
|
|
63
|
+
}
|
|
49
64
|
const bodyFragments = [];
|
|
65
|
+
let diagramIndex = 0;
|
|
66
|
+
const firstExecutableNode = doc.nodes.findIndex(node => node.type === 'executableCodeBlock');
|
|
50
67
|
const sourceVisible = resolvedReport.sourceVisible !== false;
|
|
51
68
|
const header = renderReportHeader(resolvedReport, file);
|
|
52
69
|
if (header) {
|
|
@@ -63,8 +80,20 @@ export function renderHtml(doc, file, env, options) {
|
|
|
63
80
|
const formatted = formatAmx(node.content);
|
|
64
81
|
bodyFragments.push(`<pre><code class="language-amx">${escapeHtml(formatted)}</code></pre>`);
|
|
65
82
|
}
|
|
66
|
-
|
|
67
|
-
|
|
83
|
+
if (nodeIndex === firstExecutableNode) {
|
|
84
|
+
for (const model of importedDiagrams) {
|
|
85
|
+
bodyFragments.push(renderDiagramFigure(model, `openamx-diagram-${diagramIndex++}`));
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const blockEmissions = [
|
|
89
|
+
...(emissionsByNode.get(nodeIndex) ?? []).map(emission => ({ type: 'view', emission, statementIndex: emission.statementIndex })),
|
|
90
|
+
...(diagramsByNode.get(nodeIndex) ?? []).map(model => ({ type: 'diagram', model, statementIndex: model.statementIndex }))
|
|
91
|
+
].sort((left, right) => left.statementIndex - right.statementIndex);
|
|
92
|
+
for (const emission of blockEmissions) {
|
|
93
|
+
if (emission.type === 'view')
|
|
94
|
+
bodyFragments.push(renderViewEmission(emission.emission, resolvedReport));
|
|
95
|
+
else
|
|
96
|
+
bodyFragments.push(renderDiagramFigure(emission.model, `openamx-diagram-${diagramIndex++}`));
|
|
68
97
|
}
|
|
69
98
|
}
|
|
70
99
|
}
|
|
@@ -74,25 +103,30 @@ export function renderHtml(doc, file, env, options) {
|
|
|
74
103
|
const bodyHtml = bodyFragments.join('');
|
|
75
104
|
const escapedTitle = escapeHtml(title);
|
|
76
105
|
const hasViews = environment.viewEmissions.length > 0;
|
|
77
|
-
const
|
|
106
|
+
const hasDiagrams = environment.diagramEmissions.length > 0;
|
|
107
|
+
const nonce = hasViews || hasDiagrams || !!resolvedReport.accent ? randomBytes(18).toString('base64') : '';
|
|
78
108
|
const accentStyle = safeAccentStyle(resolvedReport.accent, nonce);
|
|
79
109
|
const viewAssets = hasViews ? renderViewAssets(nonce) : '';
|
|
80
|
-
|
|
110
|
+
const diagramAssets = hasDiagrams ? renderDiagramAssets(nonce, diagramBrowserRuntime) : '';
|
|
111
|
+
const html = `<!doctype html>
|
|
81
112
|
<html>
|
|
82
113
|
<head>
|
|
83
114
|
<meta charset="utf-8">
|
|
84
|
-
${renderContentSecurityPolicy(nonce, hasViews)}
|
|
85
|
-
<title>${escapedTitle}</title>${accentStyle ? `\n${accentStyle}` : ''}${viewAssets ? `\n${viewAssets}` : ''}
|
|
115
|
+
${renderContentSecurityPolicy(nonce, hasViews || hasDiagrams)}
|
|
116
|
+
<title>${escapedTitle}</title>${accentStyle ? `\n${accentStyle}` : ''}${viewAssets ? `\n${viewAssets}` : ''}${diagramAssets ? `\n${diagramAssets}` : ''}
|
|
86
117
|
</head>
|
|
87
118
|
<body>
|
|
88
119
|
${bodyHtml}</body>
|
|
89
120
|
</html>`;
|
|
121
|
+
assertDiagramHtmlSize(html, hasDiagrams);
|
|
122
|
+
return html;
|
|
90
123
|
}
|
|
91
124
|
export function renderPreparedHtml(report, options = {}) {
|
|
92
125
|
const isPreview = options.mode === 'preview';
|
|
93
126
|
const previewToken = isPreview ? randomBytes(32).toString('hex') : undefined;
|
|
94
127
|
const context = {
|
|
95
128
|
mode: isPreview ? 'preview' : 'standalone',
|
|
129
|
+
imageWidth: report.identity.imageWidth,
|
|
96
130
|
...(previewToken ? { previewToken } : {}),
|
|
97
131
|
...(!isPreview && options.sourceDocumentPath ? { sourceDocumentPath: options.sourceDocumentPath } : {}),
|
|
98
132
|
...(!isPreview && options.projectRoot ? { projectRoot: options.projectRoot } : {}),
|
|
@@ -100,6 +134,7 @@ export function renderPreparedHtml(report, options = {}) {
|
|
|
100
134
|
targets: {}
|
|
101
135
|
};
|
|
102
136
|
const bodyFragments = [];
|
|
137
|
+
let diagramIndex = 0;
|
|
103
138
|
const identity = report.identity;
|
|
104
139
|
const metadata = [
|
|
105
140
|
identity.organization,
|
|
@@ -111,37 +146,61 @@ export function renderPreparedHtml(report, options = {}) {
|
|
|
111
146
|
const logo = identity.logo ? `<img class="openamx-report-logo" src="${escapeHtml(identity.logo.dataUri)}" alt="${escapeHtml(identity.logo.alt)}" />` : '';
|
|
112
147
|
bodyFragments.push(`<header class="openamx-report-header"><div class="openamx-report-identity">${logo}<div class="openamx-report-meta">${metadata.map(value => `<div class="openamx-report-attr">${escapeHtml(value)}</div>`).join('')}</div></div></header>`);
|
|
113
148
|
}
|
|
114
|
-
|
|
149
|
+
const diagramsByPosition = new Map();
|
|
150
|
+
for (const diagram of report.diagrams ?? []) {
|
|
151
|
+
const diagrams = diagramsByPosition.get(diagram.beforeItemIndex) ?? [];
|
|
152
|
+
diagrams.push(diagram);
|
|
153
|
+
diagramsByPosition.set(diagram.beforeItemIndex, diagrams);
|
|
154
|
+
}
|
|
155
|
+
const renderDiagramsAt = (itemIndex) => {
|
|
156
|
+
for (const diagram of (diagramsByPosition.get(itemIndex) ?? []).sort((left, right) => left.order - right.order)) {
|
|
157
|
+
bodyFragments.push(renderDiagramFigure(diagram.model, `openamx-diagram-${diagramIndex++}`));
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
for (const [itemIndex, item] of report.items.entries()) {
|
|
161
|
+
renderDiagramsAt(itemIndex);
|
|
115
162
|
if (item.type === 'narrative')
|
|
116
163
|
bodyFragments.push(renderNarrativeBlocks(item.markdown, context));
|
|
117
164
|
else if (item.type === 'source')
|
|
118
165
|
bodyFragments.push(`<pre><code class="language-amx">${escapeHtml(item.text)}</code></pre>`);
|
|
119
|
-
else
|
|
166
|
+
else if (item.type === 'view')
|
|
120
167
|
bodyFragments.push(renderViewEmission(item.emission, identity));
|
|
121
168
|
}
|
|
169
|
+
renderDiagramsAt(report.items.length);
|
|
122
170
|
if (identity.footer)
|
|
123
171
|
bodyFragments.push(`<footer class="openamx-report-footer">${escapeHtml(identity.footer)}</footer>`);
|
|
124
172
|
const hasViews = report.items.some(item => item.type === 'view');
|
|
173
|
+
const hasDiagrams = !!report.diagrams?.length;
|
|
125
174
|
const hasNarrativeAssets = report.items.some(item => item.type === 'narrative' && hasHtmlAssets(item.markdown));
|
|
126
|
-
const nonce = hasViews || identity.accent !== '#146C94' || hasNarrativeAssets || isPreview ? randomBytes(18).toString('base64') : '';
|
|
175
|
+
const nonce = hasViews || hasDiagrams || identity.accent !== '#146C94' || hasNarrativeAssets || identity.stylesheetCss !== undefined || isPreview ? randomBytes(18).toString('base64') : '';
|
|
127
176
|
const accentStyle = safeAccentStyle(identity.accent, nonce);
|
|
128
177
|
const viewAssets = hasViews ? renderViewAssets(nonce) : '';
|
|
129
|
-
const
|
|
178
|
+
const diagramAssets = hasDiagrams ? renderDiagramAssets(nonce, diagramBrowserRuntime) : '';
|
|
179
|
+
const narrativeAssets = hasNarrativeAssets ? renderNarrativeAssets(nonce, identity.imageWidth) : '';
|
|
180
|
+
const stylesheet = identity.stylesheetCss === undefined ? '' : renderCustomStylesheet(identity.stylesheetCss, nonce);
|
|
130
181
|
const previewNavigation = previewToken ? renderPreviewNavigationBootstrap(nonce, previewToken) : '';
|
|
131
182
|
const html = `<!doctype html>
|
|
132
183
|
<html>
|
|
133
184
|
<head>
|
|
134
185
|
<meta charset="utf-8">
|
|
135
|
-
${renderContentSecurityPolicy(nonce, hasViews, isPreview)}
|
|
136
|
-
<title>${escapeHtml(report.title)}</title>${accentStyle ? `\n${accentStyle}` : ''}${narrativeAssets ? `\n${narrativeAssets}` : ''}${viewAssets ? `\n${viewAssets}` : ''}${previewNavigation ? `\n${previewNavigation}` : ''}
|
|
186
|
+
${renderContentSecurityPolicy(nonce, hasViews || hasDiagrams, isPreview)}
|
|
187
|
+
<title>${escapeHtml(report.title)}</title>${accentStyle ? `\n${accentStyle}` : ''}${narrativeAssets ? `\n${narrativeAssets}` : ''}${viewAssets ? `\n${viewAssets}` : ''}${diagramAssets ? `\n${diagramAssets}` : ''}${stylesheet ? `\n${stylesheet}` : ''}${previewNavigation ? `\n${previewNavigation}` : ''}
|
|
137
188
|
</head>
|
|
138
189
|
<body>
|
|
139
190
|
${bodyFragments.join('')}</body>
|
|
140
191
|
</html>`;
|
|
192
|
+
assertDiagramHtmlSize(html, hasDiagrams);
|
|
141
193
|
if (previewToken)
|
|
142
194
|
return { html, previewToken, targets: context.targets };
|
|
143
195
|
return html;
|
|
144
196
|
}
|
|
197
|
+
function renderCustomStylesheet(css, nonce) {
|
|
198
|
+
return `<style nonce="${nonce}">${css.replace(/</g, '\\3C ')}</style>`;
|
|
199
|
+
}
|
|
200
|
+
function canonicalReportFile(file) {
|
|
201
|
+
const path = existsSync(file) ? realpathSync(file) : resolve(file);
|
|
202
|
+
return process.platform === 'win32' ? path.toLowerCase() : path;
|
|
203
|
+
}
|
|
145
204
|
function renderNarrativeBlocks(blocks, context) {
|
|
146
205
|
return blocks.map(block => {
|
|
147
206
|
switch (block.type) {
|
|
@@ -173,19 +232,19 @@ function tableCellAlignment(alignment) {
|
|
|
173
232
|
function renderNarrativeInlines(inlines, context) {
|
|
174
233
|
return inlines.map(inline => {
|
|
175
234
|
switch (inline.type) {
|
|
176
|
-
case 'text': return
|
|
235
|
+
case 'text': return renderNarrativeText(inline.text);
|
|
177
236
|
case 'lineBreak': return '<br>';
|
|
178
237
|
case 'strong': return `<strong>${renderNarrativeInlines(inline.children, context)}</strong>`;
|
|
179
238
|
case 'emphasis': return `<em>${renderNarrativeInlines(inline.children, context)}</em>`;
|
|
180
239
|
case 'delete': return `<del>${renderNarrativeInlines(inline.children, context)}</del>`;
|
|
181
240
|
case 'inlineCode': return `<code>${escapeHtml(inline.text)}</code>`;
|
|
182
|
-
case 'image': return renderNarrativeImage(inline.image, inline.title);
|
|
241
|
+
case 'image': return renderNarrativeImage(inline.image, inline.title, context.imageWidth);
|
|
183
242
|
case 'link': return renderNarrativeLink(inline.link, inline.children, context);
|
|
184
243
|
}
|
|
185
244
|
}).join('');
|
|
186
245
|
}
|
|
187
|
-
function renderNarrativeImage(image, title) {
|
|
188
|
-
const dimensions = fitNarrativeImage(image, { maxWidth: 1024, maxHeight: 768 });
|
|
246
|
+
function renderNarrativeImage(image, title, imageWidth) {
|
|
247
|
+
const dimensions = fitNarrativeImage(image, { maxWidth: 1024, maxHeight: 768 }, imageWidth);
|
|
189
248
|
return `<img class="openamx-narrative-image" src="${escapeHtml(image.dataUri)}" alt="${escapeHtml(image.alt)}" width="${Math.round(dimensions.width)}" height="${Math.round(dimensions.height)}"${title === undefined ? '' : ` title="${escapeHtml(title)}"`}>`;
|
|
190
249
|
}
|
|
191
250
|
function renderNarrativeLink(link, children, context) {
|
|
@@ -193,12 +252,16 @@ function renderNarrativeLink(link, children, context) {
|
|
|
193
252
|
const title = link.title === undefined ? '' : ` title="${escapeHtml(link.title)}"`;
|
|
194
253
|
if (link.type === 'internal')
|
|
195
254
|
return `<a href="#${encodeURIComponent(link.targetId)}"${title}>${label}</a>`;
|
|
255
|
+
if (link.type === 'amx' && context.mode !== 'preview')
|
|
256
|
+
return label;
|
|
196
257
|
if (context.mode === 'preview') {
|
|
197
258
|
const targetId = addPreviewTarget(context, link);
|
|
198
259
|
return `<a href="#" data-openamx-target="${targetId}"${title}>${label}</a>`;
|
|
199
260
|
}
|
|
200
261
|
if (link.type === 'external')
|
|
201
262
|
return `<a href="${escapeHtml(link.href)}" rel="noopener noreferrer"${title}>${label}</a>`;
|
|
263
|
+
if (link.type === 'amx')
|
|
264
|
+
return label;
|
|
202
265
|
return `<a href="${escapeHtml(standaloneLocalLinkUri(link, context))}"${title}>${label}</a>`;
|
|
203
266
|
}
|
|
204
267
|
function addPreviewTarget(context, link) {
|
|
@@ -208,7 +271,7 @@ function addPreviewTarget(context, link) {
|
|
|
208
271
|
while (context.targets[targetId]);
|
|
209
272
|
context.targets[targetId] = link.type === 'external'
|
|
210
273
|
? { kind: 'external', href: link.href }
|
|
211
|
-
: { kind:
|
|
274
|
+
: { kind: link.type, path: link.path };
|
|
212
275
|
return targetId;
|
|
213
276
|
}
|
|
214
277
|
function standaloneLocalLinkUri(link, context) {
|
|
@@ -253,12 +316,17 @@ function hasInlineHtmlAssets(inlines) {
|
|
|
253
316
|
|| (inline.type === 'link' || inline.type === 'strong' || inline.type === 'emphasis' || inline.type === 'delete')
|
|
254
317
|
&& hasInlineHtmlAssets(inline.children));
|
|
255
318
|
}
|
|
256
|
-
function renderNarrativeAssets(nonce) {
|
|
257
|
-
|
|
319
|
+
function renderNarrativeAssets(nonce, imageWidth) {
|
|
320
|
+
const imageSizing = imageWidth === undefined
|
|
321
|
+
? 'max-width:100%;'
|
|
322
|
+
: imageWidth.unit === '%'
|
|
323
|
+
? `width:${imageWidth.value}%;max-width:min(100%,1024px);max-height:768px;`
|
|
324
|
+
: `width:${imageWidth.value}px;max-width:100%;max-height:768px;`;
|
|
325
|
+
return `<style nonce="${nonce}">.openamx-narrative-image{display:block;${imageSizing}height:auto}.openamx-narrative-table{border-collapse:collapse;width:100%;margin:1rem 0}.openamx-narrative-table th,.openamx-narrative-table td{border:1px solid #a8b3bd;padding:.4rem;text-align:left}.openamx-page-break{break-before:page;page-break-before:always}@media screen{.openamx-page-break{border-top:1px dashed #a8b3bd;margin:1.5rem 0}}</style>`;
|
|
258
326
|
}
|
|
259
327
|
function renderPreviewNavigationBootstrap(nonce, previewToken) {
|
|
260
328
|
const token = JSON.stringify(previewToken);
|
|
261
|
-
return `<script nonce="${nonce}">(()=>{const token=${token};let port;window.addEventListener("message",event=>{const data=event.data;if(event.source!==parent||!data||data.type!=="openamx-preview-init"||data.previewToken!==token||event.ports.length!==1)return;port=event.ports[0];port.start()},{once:true});document.addEventListener("click",event=>{const source=event.target;if(!(source instanceof Element))return;const link=source.closest("a[data-openamx-target]");if(!link)return;event.preventDefault();if(!event.isTrusted||!navigator.userActivation?.isActive||!port)return;const targetId=link.getAttribute("data-openamx-target");if(!targetId)return;port.postMessage({version:1,type:"navigate",previewToken:token,targetId})},true)})();</script>`;
|
|
329
|
+
return `<script nonce="${nonce}">(()=>{const token=${token};let port;let scheduled=false;const pending=[];const validDiagramEvent=value=>{if(!value||typeof value!=="object"||Array.isArray(value)||value.version!==1||typeof value.diagramId!=="string"||!/^openamx-diagram-[0-9]+$/.test(value.diagramId))return false;if(value.type==="diagram-recovered")return Object.keys(value).length===3;if(value.type!=="diagram-error"||typeof value.code!=="string"||value.code.length>32||typeof value.message!=="string"||value.message.length>1000)return false;return Object.keys(value).every(key=>["version","type","diagramId","code","message","file","line","column"].includes(key))&&(value.file===undefined||typeof value.file==="string"&&value.file.length<=4096)&&(value.line===undefined||Number.isSafeInteger(value.line)&&value.line>0)&&(value.column===undefined||Number.isSafeInteger(value.column)&&value.column>0)};const forwardDiagramEvent=value=>{if(!validDiagramEvent(value))return;const outgoing={...value,previewToken:token};if(port)port.postMessage(outgoing);else pending.push(outgoing)};window.addEventListener("openamx-diagram-frame",event=>forwardDiagramEvent(event.detail));const progress=()=>{const maximum=Math.max(0,document.documentElement.scrollHeight-window.innerHeight);return maximum>0?Math.max(0,Math.min(1,window.scrollY/maximum)):0};const reportScroll=()=>{if(!port||scheduled)return;scheduled=true;requestAnimationFrame(()=>{scheduled=false;if(port)port.postMessage({version:1,type:"scroll",previewToken:token,progress:progress()})})};window.addEventListener("scroll",reportScroll,{passive:true});window.addEventListener("message",event=>{const data=event.data;if(event.source!==parent||!data||data.type!=="openamx-preview-init"||data.previewToken!==token||event.ports.length!==1)return;port=event.ports[0];port.onmessage=message=>{const value=message.data;if(!value||typeof value!=="object"||Array.isArray(value)||Object.keys(value).length!==4||value.version!==1||value.type!=="set-scroll"||value.previewToken!==token||typeof value.progress!=="number"||!Number.isFinite(value.progress)||value.progress<0||value.progress>1)return;const maximum=Math.max(0,document.documentElement.scrollHeight-window.innerHeight);window.scrollTo(0,maximum*value.progress)};port.start();for(const message of pending.splice(0))port.postMessage(message)},{once:true});document.addEventListener("click",event=>{const source=event.target;if(!(source instanceof Element))return;const link=source.closest("a[data-openamx-target]");if(!link)return;event.preventDefault();if(!event.isTrusted||!navigator.userActivation?.isActive||!port)return;const targetId=link.getAttribute("data-openamx-target");if(!targetId)return;port.postMessage({version:1,type:"navigate",previewToken:token,targetId})},true)})();</script>`;
|
|
262
330
|
}
|
|
263
331
|
function renderViewEmission(emission, identity) {
|
|
264
332
|
if (emission.kind === 'table')
|
|
@@ -275,8 +343,8 @@ function renderTable(emission) {
|
|
|
275
343
|
const rows = emission.data.filter(isRecordValue);
|
|
276
344
|
const caption = title?.type === 'viewTitleOption' ? title.value : emission.name;
|
|
277
345
|
const header = columns.map(column => `<th scope="col" aria-sort="none"><button type="button" data-sort="${escapeHtml(column.field)}">${escapeHtml(column.label)}</button></th>`).join('');
|
|
278
|
-
const body = rows.map((row, index) => `<tr data-row-index="${index}">${columns.map(column => `<td>${
|
|
279
|
-
const printBody = rows.map(row => `<tr>${columns.map(column => `<td>${
|
|
346
|
+
const body = rows.map((row, index) => `<tr data-row-index="${index}">${columns.map(column => `<td>${renderNarrativeText(formatAmxValue(row[column.field]))}</td>`).join('')}</tr>`).join('');
|
|
347
|
+
const printBody = rows.map(row => `<tr>${columns.map(column => `<td>${renderNarrativeText(formatAmxValue(row[column.field]))}</td>`).join('')}</tr>`).join('');
|
|
280
348
|
const payload = safeJson({ columns: columns.map(column => ({ field: column.field, label: column.label })), rows });
|
|
281
349
|
return `<section class="openamx-view openamx-table" data-view="${id}" aria-labelledby="${id}-caption">
|
|
282
350
|
<h2 id="${id}-caption" class="sr-only">${escapeHtml(caption)}</h2>
|
|
@@ -302,7 +370,7 @@ function renderChart(emission, identity) {
|
|
|
302
370
|
const zoomControls = browserModel.zoomable
|
|
303
371
|
? `<div class="openamx-chart-controls" role="group" aria-label="Chart zoom controls"><button type="button" data-zoom="out" aria-label="Zoom out">Zoom out</button><button type="button" data-zoom="in" aria-label="Zoom in">Zoom in</button><button type="button" data-zoom="reset">Reset zoom</button></div>`
|
|
304
372
|
: '';
|
|
305
|
-
const textRows = model.table.rows.map(row => `<tr>${row.values.map(value => `<td>${
|
|
373
|
+
const textRows = model.table.rows.map(row => `<tr>${row.values.map(value => `<td>${renderNarrativeText(formatAmxValue(value))}</td>`).join('')}</tr>`).join('');
|
|
306
374
|
const data = safeJson(browserModel);
|
|
307
375
|
return `<figure class="openamx-view openamx-chart" id="${id}-figure" data-openamx-chart aria-labelledby="${titleId}" aria-describedby="${descriptionId} ${summaryId}">
|
|
308
376
|
<figcaption><strong id="${titleId}">${escapeHtml(model.title)}</strong><span id="${descriptionId}">${escapeHtml(model.description)}</span></figcaption>
|
|
@@ -492,26 +560,9 @@ function substituteInlines(content, env, file, narrativeLine) {
|
|
|
492
560
|
const source = narrativeLine !== undefined ? { line: narrativeLine, column: 1 } : undefined;
|
|
493
561
|
const exprNode = parseExpression(trimmed, source);
|
|
494
562
|
const value = evaluateExpression(exprNode, env, file);
|
|
495
|
-
return escapeHtml(
|
|
563
|
+
return escapeHtml(formatAmxValue(value));
|
|
496
564
|
});
|
|
497
565
|
}
|
|
498
|
-
function valueToString(v) {
|
|
499
|
-
if (v === null || v === undefined)
|
|
500
|
-
return '';
|
|
501
|
-
if (typeof v === 'string')
|
|
502
|
-
return v;
|
|
503
|
-
if (typeof v === 'number') {
|
|
504
|
-
// Present integers without trailing .0 for natural readability in text.
|
|
505
|
-
return Number.isInteger(v) ? String(v) : String(v);
|
|
506
|
-
}
|
|
507
|
-
if (typeof v === 'boolean')
|
|
508
|
-
return String(v); // "true" / "false"
|
|
509
|
-
if (Array.isArray(v)) {
|
|
510
|
-
// Simple deterministic representation for lists inside narrative text.
|
|
511
|
-
return v.map(valueToString).join(', ');
|
|
512
|
-
}
|
|
513
|
-
return String(v);
|
|
514
|
-
}
|
|
515
566
|
function escapeHtml(s) {
|
|
516
567
|
return s
|
|
517
568
|
.replace(/&/g, '&')
|
|
@@ -519,3 +570,6 @@ function escapeHtml(s) {
|
|
|
519
570
|
.replace(/>/g, '>')
|
|
520
571
|
.replace(/"/g, '"');
|
|
521
572
|
}
|
|
573
|
+
function renderNarrativeText(text) {
|
|
574
|
+
return escapeHtml(text).replace(/\n( *)/g, (_lineBreak, indentation) => `<br>${' '.repeat(indentation.length)}`);
|
|
575
|
+
}
|
|
@@ -2,21 +2,25 @@ import { AlignmentType, Bookmark, BorderStyle, Document, ExternalHyperlink, Head
|
|
|
2
2
|
import { ChartRun } from 'docx/charts';
|
|
3
3
|
import { realpathSync } from 'node:fs';
|
|
4
4
|
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
5
|
+
import { formatAmxValue } from '../runtime/valueSerialization';
|
|
5
6
|
import { createChartViewModel } from './chartModel';
|
|
6
7
|
import { fitNarrativeImage } from './narrativeModel';
|
|
8
|
+
import { orderedReportSequence } from './reportSequence';
|
|
9
|
+
import { rasterizeStaticDiagramSvg, renderStaticDiagramSvg } from './staticDiagram';
|
|
7
10
|
const TABLE_WIDTH_TWIPS = 9_026;
|
|
8
11
|
// ChartRun uses 15 twips per CSS pixel; leave one pixel of page-width clearance.
|
|
9
12
|
const DOCX_CHART_WIDTH_PIXELS = Math.floor(TABLE_WIDTH_TWIPS / 15) - 1;
|
|
13
|
+
const DOCX_DIAGRAM_MAX_HEIGHT_PIXELS = 700;
|
|
10
14
|
const IMAGE_WIDTH_PIXELS = 601;
|
|
11
15
|
const IMAGE_HEIGHT_PIXELS = 864;
|
|
12
16
|
const MAX_BOOKMARK_NAME_LENGTH = 40;
|
|
13
|
-
export function prepareDocxReport(report, context) {
|
|
17
|
+
export async function prepareDocxReport(report, context) {
|
|
14
18
|
return preparePreparedDocxReport(report, context);
|
|
15
19
|
}
|
|
16
20
|
export async function serializeDocxReport(report) {
|
|
17
21
|
return Uint8Array.from(await Packer.toBuffer(report.document));
|
|
18
22
|
}
|
|
19
|
-
function preparePreparedDocxReport(report, exportContext) {
|
|
23
|
+
async function preparePreparedDocxReport(report, exportContext) {
|
|
20
24
|
const children = [];
|
|
21
25
|
const identity = report.identity;
|
|
22
26
|
if (identity.logo || identity.organization || identity.author || identity.status || identity.classification) {
|
|
@@ -32,10 +36,16 @@ function preparePreparedDocxReport(report, exportContext) {
|
|
|
32
36
|
const bookmarks = headingBookmarks(report.items.flatMap(item => item.type === 'narrative' ? item.markdown : []), usedBookmarkNames);
|
|
33
37
|
const numbering = [];
|
|
34
38
|
let nextListReference = 0;
|
|
35
|
-
for (const
|
|
39
|
+
for (const entry of orderedReportSequence(report)) {
|
|
40
|
+
if (entry.type === 'diagram') {
|
|
41
|
+
children.push(...await renderDiagram(entry.diagram.model));
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
const item = entry.item;
|
|
36
45
|
if (item.type === 'narrative') {
|
|
37
46
|
const context = {
|
|
38
47
|
exportContext,
|
|
48
|
+
imageWidth: identity.imageWidth,
|
|
39
49
|
bookmarks,
|
|
40
50
|
numbering,
|
|
41
51
|
quoteDepth: 0,
|
|
@@ -58,6 +68,22 @@ function preparePreparedDocxReport(report, exportContext) {
|
|
|
58
68
|
})
|
|
59
69
|
};
|
|
60
70
|
}
|
|
71
|
+
async function renderDiagram(model) {
|
|
72
|
+
const rendered = renderStaticDiagramSvg(model);
|
|
73
|
+
const png = await rasterizeStaticDiagramSvg(rendered.svg);
|
|
74
|
+
const transformation = fitNarrativeImage({ width: png.width, height: png.height }, { maxWidth: DOCX_CHART_WIDTH_PIXELS, maxHeight: DOCX_DIAGRAM_MAX_HEIGHT_PIXELS });
|
|
75
|
+
const image = new ImageRun({
|
|
76
|
+
type: 'png',
|
|
77
|
+
data: png.bytes,
|
|
78
|
+
transformation,
|
|
79
|
+
altText: { name: model.name, title: model.title, description: model.description }
|
|
80
|
+
});
|
|
81
|
+
return [
|
|
82
|
+
new Paragraph({ text: model.title, heading: HeadingLevel.HEADING_2, keepNext: true }),
|
|
83
|
+
new Paragraph({ text: model.description, keepNext: true }),
|
|
84
|
+
new Paragraph({ children: [image], alignment: AlignmentType.CENTER, keepLines: true })
|
|
85
|
+
];
|
|
86
|
+
}
|
|
61
87
|
function renderBlocks(blocks, context, nextListReference) {
|
|
62
88
|
return blocks.flatMap(block => renderBlock(block, context, nextListReference));
|
|
63
89
|
}
|
|
@@ -210,8 +236,8 @@ function inlineChildren(inlines, context, style = {}) {
|
|
|
210
236
|
children.push(...inlineChildren(inline.children, context, nestedStyle));
|
|
211
237
|
}
|
|
212
238
|
else if (inline.type === 'link') {
|
|
213
|
-
const linkChildren = inlineChildren(inline.children, context, { ...style, color: '0563C1', underline: {} });
|
|
214
239
|
const link = inline.link;
|
|
240
|
+
const linkChildren = inlineChildren(inline.children, context, link.type === 'amx' ? style : { ...style, color: '0563C1', underline: {} });
|
|
215
241
|
if (link.type === 'external') {
|
|
216
242
|
children.push(new ExternalHyperlink({ link: link.href, children: linkChildren }));
|
|
217
243
|
}
|
|
@@ -222,12 +248,15 @@ function inlineChildren(inlines, context, style = {}) {
|
|
|
222
248
|
else
|
|
223
249
|
children.push(...linkChildren);
|
|
224
250
|
}
|
|
251
|
+
else if (link.type === 'amx') {
|
|
252
|
+
children.push(...linkChildren);
|
|
253
|
+
}
|
|
225
254
|
else {
|
|
226
255
|
children.push(new ExternalHyperlink({ link: localLinkUri(link, context.exportContext), children: linkChildren }));
|
|
227
256
|
}
|
|
228
257
|
}
|
|
229
258
|
else if (inline.type === 'image') {
|
|
230
|
-
children.push(narrativeImageRun(inline.image));
|
|
259
|
+
children.push(narrativeImageRun(inline.image, context.imageWidth));
|
|
231
260
|
}
|
|
232
261
|
}
|
|
233
262
|
return children;
|
|
@@ -248,8 +277,8 @@ function codeChildren(text) {
|
|
|
248
277
|
});
|
|
249
278
|
return runs.length > 0 ? runs : [new TextRun({ text: '', font: 'Consolas', size: 18 })];
|
|
250
279
|
}
|
|
251
|
-
function narrativeImageRun(image) {
|
|
252
|
-
const dimensions = fitNarrativeImage(image, { maxWidth: IMAGE_WIDTH_PIXELS, maxHeight: IMAGE_HEIGHT_PIXELS });
|
|
280
|
+
function narrativeImageRun(image, imageWidth) {
|
|
281
|
+
const dimensions = fitNarrativeImage(image, { maxWidth: IMAGE_WIDTH_PIXELS, maxHeight: IMAGE_HEIGHT_PIXELS }, imageWidth);
|
|
253
282
|
return new ImageRun({
|
|
254
283
|
type: image.format === 'jpeg' ? 'jpg' : 'png',
|
|
255
284
|
data: image.dataUri,
|
|
@@ -344,7 +373,7 @@ function addTable(children, emission) {
|
|
|
344
373
|
children.push(new Paragraph({ text: caption, heading: HeadingLevel.HEADING_2 }));
|
|
345
374
|
const header = new TableRow({ children: columns.map(column => tableCell(column.label, true)) });
|
|
346
375
|
const rows = emission.data.map(value => new TableRow({
|
|
347
|
-
children: columns.map(column => tableCell(isRecord(value) ?
|
|
376
|
+
children: columns.map(column => tableCell(isRecord(value) ? formatAmxValue(value[column.field], '(null)') : ''))
|
|
348
377
|
}));
|
|
349
378
|
children.push(new Table({ rows: [header, ...rows] }));
|
|
350
379
|
}
|
|
@@ -496,7 +525,7 @@ function addChartTable(children, model) {
|
|
|
496
525
|
});
|
|
497
526
|
const rows = model.table.rows.map(row => new TableRow({
|
|
498
527
|
cantSplit: true,
|
|
499
|
-
children: row.values.map(value => tableCell(
|
|
528
|
+
children: row.values.map(value => tableCell(formatAmxValue(value, '(null)')))
|
|
500
529
|
}));
|
|
501
530
|
children.push(new Paragraph({ text: model.table.caption, heading: HeadingLevel.HEADING_3 }));
|
|
502
531
|
const columnCount = Math.max(1, model.table.headings.length);
|
|
@@ -716,10 +745,3 @@ function headingLevel(level) {
|
|
|
716
745
|
function isRecord(value) {
|
|
717
746
|
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
718
747
|
}
|
|
719
|
-
function valueToString(value) {
|
|
720
|
-
if (value === null || value === undefined)
|
|
721
|
-
return '(null)';
|
|
722
|
-
if (Array.isArray(value))
|
|
723
|
-
return value.map(valueToString).join(', ');
|
|
724
|
-
return String(value);
|
|
725
|
-
}
|