@memberjunction/ng-react 6.2.1 → 6.3.0-edge.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 +12 -0
- package/dist/__tests__/component-pdf-export.test.d.ts +1 -0
- package/dist/__tests__/component-pdf-export.test.js +265 -0
- package/dist/__tests__/component-pdf-export.test.js.map +1 -0
- package/dist/__tests__/image-pdf-writer.test.d.ts +1 -0
- package/dist/__tests__/image-pdf-writer.test.js +45 -0
- package/dist/__tests__/image-pdf-writer.test.js.map +1 -0
- package/dist/lib/components/mj-react-component.component.d.ts +10 -0
- package/dist/lib/components/mj-react-component.component.js +14 -1
- package/dist/lib/components/mj-react-component.component.js.map +1 -1
- package/dist/lib/export/component-pdf-export.d.ts +115 -0
- package/dist/lib/export/component-pdf-export.js +686 -0
- package/dist/lib/export/component-pdf-export.js.map +1 -0
- package/dist/lib/export/image-pdf-writer.d.ts +25 -0
- package/dist/lib/export/image-pdf-writer.js +82 -0
- package/dist/lib/export/image-pdf-writer.js.map +1 -0
- package/dist/public-api.d.ts +2 -0
- package/dist/public-api.js +3 -0
- package/dist/public-api.js.map +1 -1
- package/package.json +11 -10
|
@@ -0,0 +1,686 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Whole-component PDF export for rendered React components.
|
|
3
|
+
*
|
|
4
|
+
* The host captures the component's root element as it is currently shown (filters, selections and
|
|
5
|
+
* grid pages kept) and lays it onto A4 pages. Content the user would have to scroll to see is
|
|
6
|
+
* included. The root is laid out at the page's printable width (portrait or landscape), so the PDF
|
|
7
|
+
* is the same whatever the viewer's size, then a "print mode" grows it to its content's height and expands
|
|
8
|
+
* only the elements that actually clip their content, because a blanket height:auto stylesheet breaks
|
|
9
|
+
* charts that size themselves to their container. The host page around the root is never changed.
|
|
10
|
+
* Everything is restored afterwards.
|
|
11
|
+
*
|
|
12
|
+
* Content rendered in portals (antd modals, drawers, dropdowns) lives outside the root and is not
|
|
13
|
+
* part of the PDF.
|
|
14
|
+
* @module @memberjunction/ng-react
|
|
15
|
+
*/
|
|
16
|
+
import { BuildImagePdf } from './image-pdf-writer';
|
|
17
|
+
/** Inline style properties print mode sets; each touched element gets its original style text back on exit. */
|
|
18
|
+
const PRINT_STYLE_PROPERTIES = ['position', 'top', 'left', 'width', 'height', 'max-height', 'overflow', 'overflow-x', 'overflow-y', 'contain', 'flex'];
|
|
19
|
+
/** Upper bound on expand passes: each pass can make a new ancestor spill, so it runs to a fixed point. */
|
|
20
|
+
const MAX_EXPAND_PASSES = 12;
|
|
21
|
+
/** Chart.js re-renders at this pixel ratio for the capture, so canvases stay sharp next to text. */
|
|
22
|
+
const CAPTURE_CHART_PIXEL_RATIO = 3;
|
|
23
|
+
/** html-to-image renders the element at this pixel ratio. */
|
|
24
|
+
const CAPTURE_PIXEL_RATIO = 2;
|
|
25
|
+
/** Elements that never need expanding: their size is their drawing, not a scroll box. */
|
|
26
|
+
const NON_EXPANDING_TAGS = new Set(['CANVAS', 'svg', 'IMG', 'VIDEO', 'IFRAME']);
|
|
27
|
+
/**
|
|
28
|
+
* Elements a page break never splits when they fit on a page: drawings, rows, form fields and text
|
|
29
|
+
* blocks. Elements with no child elements count too, and so does any container shorter than
|
|
30
|
+
* {@link SMALL_BLOCK_PAGE_SHARE} of a page (a KPI tile, a bar row).
|
|
31
|
+
*/
|
|
32
|
+
const ATOMIC_TAGS = new Set(['svg', 'CANVAS', 'IMG', 'VIDEO', 'TR', 'INPUT', 'BUTTON', 'SELECT', 'TEXTAREA', 'LI', 'P', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'LABEL', 'PRE']);
|
|
33
|
+
const SMALL_BLOCK_PAGE_SHARE = 0.15;
|
|
34
|
+
/** A container cut with less than this share of a page above the cut moves whole (keeps a card's header with it). */
|
|
35
|
+
const ORPHAN_PAGE_SHARE = 0.15;
|
|
36
|
+
/** A container that fits a page moves whole when less than this share of a page would carry over past the cut. */
|
|
37
|
+
const WIDOW_PAGE_SHARE = 0.15;
|
|
38
|
+
/** A break within this share of a page below a table header row or heading moves above it (keep with next). */
|
|
39
|
+
const KEEP_WITH_NEXT_PAGE_SHARE = 0.1;
|
|
40
|
+
/** A table's lead-in (section title, search box, header row) through its first row stays together within this share of a page. */
|
|
41
|
+
const TABLE_LEAD_PAGE_SHARE = 0.35;
|
|
42
|
+
/** Tags whose element must stay on the same page as what follows it. */
|
|
43
|
+
const KEEP_WITH_NEXT_TAGS = new Set(['THEAD', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6']);
|
|
44
|
+
/** A break that would leave a page less full than this is not moved; the page is cut where it falls. */
|
|
45
|
+
const MIN_PAGE_FILL_SHARE = 0.1;
|
|
46
|
+
/**
|
|
47
|
+
* Shrink-to-fit: when keeping a chart or block together leaves a page less than {@link SHRINK_WHEN_FILL_BELOW}
|
|
48
|
+
* full, the page may hold up to this much more content, scaled down to fit the paper.
|
|
49
|
+
*/
|
|
50
|
+
const MAX_SHRINK_EXTRA_SHARE = 0.2;
|
|
51
|
+
const SHRINK_WHEN_FILL_BELOW = 0.8;
|
|
52
|
+
/** Content wider than the page layout is laid out at its own width, up to this many page widths. */
|
|
53
|
+
const MAX_LAYOUT_WIDTH_FACTOR = 2;
|
|
54
|
+
/** Widening rounds: each adds the overflow that remains once the card padding is accounted for. */
|
|
55
|
+
const MAX_WIDEN_ROUNDS = 4;
|
|
56
|
+
/** Marks controls (such as ExportableData's export buttons) that are left out of captures. */
|
|
57
|
+
const EXPORT_CONTROL_ATTRIBUTE = 'data-export-control';
|
|
58
|
+
/** A4 in millimetres, and the page margin. */
|
|
59
|
+
const A4_SHORT_MM = 210;
|
|
60
|
+
const A4_LONG_MM = 297;
|
|
61
|
+
const PAGE_MARGIN_MM = 10;
|
|
62
|
+
/** CSS pixels per millimetre (96 per inch): laying out at the page width prints CSS sizes at true size. */
|
|
63
|
+
const CSS_PX_PER_MM = 96 / 25.4;
|
|
64
|
+
function pageSize(orientation) {
|
|
65
|
+
return orientation === 'portrait'
|
|
66
|
+
? { WidthMM: A4_SHORT_MM, HeightMM: A4_LONG_MM }
|
|
67
|
+
: { WidthMM: A4_LONG_MM, HeightMM: A4_SHORT_MM };
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The width, in CSS pixels, the component is laid out at for a page: the printable width at 96 dpi
|
|
71
|
+
* (718 portrait, 1047 landscape), so 14px text prints at about 10.5pt whatever the viewer's size.
|
|
72
|
+
*/
|
|
73
|
+
export function PageLayoutWidth(orientation) {
|
|
74
|
+
return Math.round((pageSize(orientation).WidthMM - 2 * PAGE_MARGIN_MM) * CSS_PX_PER_MM);
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Where a break inside `block` should go instead: its top, or `cut` when the block may be split
|
|
78
|
+
* there. Atomic blocks are never split (when they fit a page); with `layoutRules` on, small
|
|
79
|
+
* containers are kept together and containers are not left with only their first or last lines.
|
|
80
|
+
*/
|
|
81
|
+
function breakFor(block, cut, pageHeight, layoutRules) {
|
|
82
|
+
const height = block.Bottom - block.Top;
|
|
83
|
+
if (height > pageHeight) {
|
|
84
|
+
return cut; // too tall for any page: it has to split
|
|
85
|
+
}
|
|
86
|
+
if (block.Atomic) {
|
|
87
|
+
return block.Top;
|
|
88
|
+
}
|
|
89
|
+
const small = height < pageHeight * SMALL_BLOCK_PAGE_SHARE;
|
|
90
|
+
const orphanedStart = cut - block.Top < pageHeight * ORPHAN_PAGE_SHARE;
|
|
91
|
+
const widowedEnd = block.Bottom - cut < pageHeight * WIDOW_PAGE_SHARE;
|
|
92
|
+
return layoutRules && (small || orphanedStart || widowedEnd) ? block.Top : cut;
|
|
93
|
+
}
|
|
94
|
+
/** A header row or heading the cut falls just below: it moves to the next page with what follows it. */
|
|
95
|
+
function keptWithNext(block, cut, pageHeight) {
|
|
96
|
+
return !!block.KeepWithNext && block.Bottom <= cut && cut - block.Bottom < pageHeight * KEEP_WITH_NEXT_PAGE_SHARE;
|
|
97
|
+
}
|
|
98
|
+
/** The cut moved up until no block (and, with `layoutRules`, no header-row or heading rule) objects to it. */
|
|
99
|
+
function settleCut(limit, blocks, pageHeight, layoutRules) {
|
|
100
|
+
let cut = limit;
|
|
101
|
+
for (let moved = true; moved;) {
|
|
102
|
+
moved = false;
|
|
103
|
+
for (const block of blocks) {
|
|
104
|
+
if (layoutRules && keptWithNext(block, cut, pageHeight) && block.Top < cut) {
|
|
105
|
+
cut = block.Top;
|
|
106
|
+
moved = true;
|
|
107
|
+
}
|
|
108
|
+
else if (block.Top < cut && cut < block.Bottom) {
|
|
109
|
+
const next = breakFor(block, cut, pageHeight, layoutRules);
|
|
110
|
+
if (next < cut) {
|
|
111
|
+
cut = next;
|
|
112
|
+
moved = true;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return cut;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* The page break at or above `limit` for a page starting at `pageTop`. First with every rule (no
|
|
121
|
+
* split rows or drawings, no stranded first or last lines, header rows and headings kept with what
|
|
122
|
+
* follows); when that would leave the page nearly empty, with only the never-split rule; and when
|
|
123
|
+
* even that would, the page is cut at `limit`.
|
|
124
|
+
*/
|
|
125
|
+
function pageBreak(pageTop, limit, blocks, pageHeight) {
|
|
126
|
+
const minimumEnd = pageTop + pageHeight * MIN_PAGE_FILL_SHARE;
|
|
127
|
+
for (const layoutRules of [true, false]) {
|
|
128
|
+
const cut = settleCut(limit, blocks, pageHeight, layoutRules);
|
|
129
|
+
if (cut >= minimumEnd) {
|
|
130
|
+
// Whole pixels: element positions are fractional, and a page image must be a whole number of rows.
|
|
131
|
+
return Math.floor(cut);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return limit;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Lays a captured image of `imageWidth` by `imageHeight` pixels onto A4 pages in the given
|
|
138
|
+
* orientation: scaled to the page width inside the margins and cut into page-height bands. Each
|
|
139
|
+
* cut moves up so it does not split a drawing, row or other small element in `blocks`, and does not
|
|
140
|
+
* strand a card's first or last lines; a page left mostly empty by that may be shrunk to fit.
|
|
141
|
+
*/
|
|
142
|
+
export function PlanPdfPages(imageWidth, imageHeight, orientation = 'portrait', blocks = []) {
|
|
143
|
+
const page = pageSize(orientation);
|
|
144
|
+
const drawWidthMM = page.WidthMM - 2 * PAGE_MARGIN_MM;
|
|
145
|
+
const mmPerPixel = drawWidthMM / Math.max(imageWidth, 1);
|
|
146
|
+
const pageHeightPx = Math.max(1, Math.floor((page.HeightMM - 2 * PAGE_MARGIN_MM) / mmPerPixel));
|
|
147
|
+
const slices = [];
|
|
148
|
+
for (let sourceY = 0; sourceY < imageHeight;) {
|
|
149
|
+
const end = pageEnd(sourceY, imageHeight, blocks, pageHeightPx);
|
|
150
|
+
slices.push(placeSlice(sourceY, end - sourceY, pageHeightPx, mmPerPixel, drawWidthMM));
|
|
151
|
+
sourceY = end;
|
|
152
|
+
}
|
|
153
|
+
return { Orientation: orientation, PageWidthMM: page.WidthMM, PageHeightMM: page.HeightMM, DrawWidthMM: drawWidthMM, Slices: slices };
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Where the page starting at `pageTop` ends. When keeping a block together leaves the page less than
|
|
157
|
+
* {@link SHRINK_WHEN_FILL_BELOW} full, a page up to {@link MAX_SHRINK_EXTRA_SHARE} taller is tried, and
|
|
158
|
+
* kept when it holds meaningfully more: that page is then shrunk to fit (shrink-to-fit). A sliver
|
|
159
|
+
* that would be alone on the last page is folded into this page the same way.
|
|
160
|
+
*/
|
|
161
|
+
function pageEnd(pageTop, imageHeight, blocks, pageHeightPx) {
|
|
162
|
+
const limit = pageTop + pageHeightPx;
|
|
163
|
+
if (limit >= imageHeight) {
|
|
164
|
+
return imageHeight;
|
|
165
|
+
}
|
|
166
|
+
const normal = pageBreak(pageTop, limit, blocks, pageHeightPx);
|
|
167
|
+
const tallerHeight = Math.floor(pageHeightPx * (1 + MAX_SHRINK_EXTRA_SHARE));
|
|
168
|
+
// A last page holding only a sliver (a row or two) is folded into this one when a shrunk page reaches the end.
|
|
169
|
+
if (imageHeight - normal < pageHeightPx * WIDOW_PAGE_SHARE && imageHeight - pageTop <= tallerHeight) {
|
|
170
|
+
return imageHeight;
|
|
171
|
+
}
|
|
172
|
+
if (normal - pageTop >= pageHeightPx * SHRINK_WHEN_FILL_BELOW) {
|
|
173
|
+
return normal;
|
|
174
|
+
}
|
|
175
|
+
const tallerLimit = pageTop + tallerHeight;
|
|
176
|
+
const taller = tallerLimit >= imageHeight ? imageHeight : pageBreak(pageTop, tallerLimit, blocks, tallerHeight);
|
|
177
|
+
return taller - normal > pageHeightPx * SHRINK_WHEN_FILL_BELOW * MAX_SHRINK_EXTRA_SHARE ? taller : normal;
|
|
178
|
+
}
|
|
179
|
+
/** A slice drawn at the page width, or scaled down and centred when it is taller than a page. */
|
|
180
|
+
function placeSlice(sourceY, sourceHeight, pageHeightPx, mmPerPixel, drawWidthMM) {
|
|
181
|
+
const scale = Math.min(1, pageHeightPx / Math.max(sourceHeight, 1));
|
|
182
|
+
const width = drawWidthMM * scale;
|
|
183
|
+
return {
|
|
184
|
+
SourceY: sourceY,
|
|
185
|
+
SourceHeight: sourceHeight,
|
|
186
|
+
DrawHeightMM: sourceHeight * mmPerPixel * scale,
|
|
187
|
+
DrawWidthMM: width,
|
|
188
|
+
XMM: PAGE_MARGIN_MM + (drawWidthMM - width) / 2,
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
/** `<title>_<YYYY-MM-DD>.pdf`, with anything outside letters, digits, space, - and _ replaced by _. */
|
|
192
|
+
export function PdfFileName(title, now = new Date()) {
|
|
193
|
+
const pad = (value) => String(value).padStart(2, '0');
|
|
194
|
+
const stamp = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
|
|
195
|
+
const base = (title || '').trim().replace(/[^A-Za-z0-9 _-]/g, '_') || 'component';
|
|
196
|
+
return `${base}_${stamp}.pdf`;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Records each element's inline style text the first time print mode touches it, and puts it back
|
|
200
|
+
* exactly. Saving the whole text (not single properties) also restores shorthands such as `flex`,
|
|
201
|
+
* which browsers split into longhands.
|
|
202
|
+
*/
|
|
203
|
+
class InlineStyleJournal {
|
|
204
|
+
constructor() {
|
|
205
|
+
this.saved = new Map();
|
|
206
|
+
}
|
|
207
|
+
Set(element, property, value) {
|
|
208
|
+
if (!this.saved.has(element)) {
|
|
209
|
+
this.saved.set(element, element.style.cssText);
|
|
210
|
+
}
|
|
211
|
+
element.style.setProperty(property, value);
|
|
212
|
+
}
|
|
213
|
+
RestoreAll() {
|
|
214
|
+
for (const [element, cssText] of this.saved) {
|
|
215
|
+
element.style.cssText = cssText;
|
|
216
|
+
}
|
|
217
|
+
this.saved.clear();
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
const CLIPPING_OVERFLOW = new Set(['auto', 'scroll', 'hidden', 'clip']);
|
|
221
|
+
/** True when the element's content is taller than the box it holds. */
|
|
222
|
+
function overflowsVertically(element) {
|
|
223
|
+
return element.scrollHeight > element.clientHeight + 1;
|
|
224
|
+
}
|
|
225
|
+
/** True when the element hides vertical content behind a scrollbar or a clip. */
|
|
226
|
+
function clipsVertically(element) {
|
|
227
|
+
return CLIPPING_OVERFLOW.has(getComputedStyle(element).overflowY) && overflowsVertically(element);
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* True when the element is a sideways scroller hiding columns (a table too wide for the page).
|
|
231
|
+
* Only scrolling containers count: `overflow: hidden` on purpose (an ellipsis cell) stays clipped.
|
|
232
|
+
*/
|
|
233
|
+
function scrollsHorizontally(element) {
|
|
234
|
+
const overflowX = getComputedStyle(element).overflowX;
|
|
235
|
+
return (overflowX === 'auto' || overflowX === 'scroll') && element.scrollWidth > element.clientWidth + 1;
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Shows a sideways scroller's full width, so no column is lost: the content then runs past the page
|
|
239
|
+
* width and the capture is scaled down to fit. Also drops `contain`, which would keep it narrow.
|
|
240
|
+
*/
|
|
241
|
+
function releaseHorizontally(journal, element) {
|
|
242
|
+
journal.Set(element, 'overflow-x', 'visible');
|
|
243
|
+
journal.Set(element, 'contain', 'none');
|
|
244
|
+
}
|
|
245
|
+
/** True when the element's content now spills past a height the element still holds, without clipping it. */
|
|
246
|
+
function spillsOutOfFixedHeight(element) {
|
|
247
|
+
return !CLIPPING_OVERFLOW.has(getComputedStyle(element).overflowY) && overflowsVertically(element);
|
|
248
|
+
}
|
|
249
|
+
/** True when the element sits in a top-to-bottom flex layout, where `flex: none` stops it being squeezed. */
|
|
250
|
+
function isInColumnFlex(element) {
|
|
251
|
+
const parent = element.parentElement;
|
|
252
|
+
if (!parent) {
|
|
253
|
+
return false;
|
|
254
|
+
}
|
|
255
|
+
const style = getComputedStyle(parent);
|
|
256
|
+
return style.display.includes('flex') && style.flexDirection.startsWith('column');
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Lets the element grow to its content's height. `flex: none` is applied only in a column flex
|
|
260
|
+
* layout: in a row layout it would let the element widen to its content and rescale everything
|
|
261
|
+
* that sizes itself to the width (an svg chart with `width: 100%`).
|
|
262
|
+
*/
|
|
263
|
+
function expandElement(journal, element) {
|
|
264
|
+
journal.Set(element, 'height', 'auto');
|
|
265
|
+
journal.Set(element, 'max-height', 'none');
|
|
266
|
+
journal.Set(element, 'overflow-y', 'visible');
|
|
267
|
+
if (isInColumnFlex(element)) {
|
|
268
|
+
journal.Set(element, 'flex', 'none');
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* The root grows to its content's height at its current width. Its ancestors (the host's panes)
|
|
273
|
+
* are left alone: the capture clones only the root, so their clipping does not matter, and
|
|
274
|
+
* changing them reflows the host page around the component.
|
|
275
|
+
*/
|
|
276
|
+
function expandRoot(journal, root) {
|
|
277
|
+
journal.Set(root, 'width', `${root.getBoundingClientRect().width}px`);
|
|
278
|
+
journal.Set(root, 'height', 'auto');
|
|
279
|
+
journal.Set(root, 'max-height', 'none');
|
|
280
|
+
journal.Set(root, 'overflow', 'visible');
|
|
281
|
+
}
|
|
282
|
+
function isExpandable(element) {
|
|
283
|
+
return !NON_EXPANDING_TAGS.has(element.tagName) && !element.closest('svg');
|
|
284
|
+
}
|
|
285
|
+
/** Ancestors (up to the root) that hold a fixed height the expanded element now spills out of. */
|
|
286
|
+
function expandSpillingAncestors(journal, element, root) {
|
|
287
|
+
for (let ancestor = element.parentElement; ancestor && ancestor !== root; ancestor = ancestor.parentElement) {
|
|
288
|
+
if (spillsOutOfFixedHeight(ancestor)) {
|
|
289
|
+
expandElement(journal, ancestor);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* One pass over the root's elements; true when anything was expanded. Only elements that clip are
|
|
295
|
+
* expanded, plus the ancestors they then spill out of: an element whose absolutely positioned
|
|
296
|
+
* overlay pokes out (a chart legend, a tooltip) is left alone.
|
|
297
|
+
*/
|
|
298
|
+
function expandClippingPass(journal, root) {
|
|
299
|
+
let changed = false;
|
|
300
|
+
for (const element of Array.from(root.querySelectorAll('*'))) {
|
|
301
|
+
if (!isExpandable(element)) {
|
|
302
|
+
continue;
|
|
303
|
+
}
|
|
304
|
+
if (clipsVertically(element)) {
|
|
305
|
+
expandElement(journal, element);
|
|
306
|
+
expandSpillingAncestors(journal, element, root);
|
|
307
|
+
changed = true;
|
|
308
|
+
}
|
|
309
|
+
if (scrollsHorizontally(element)) {
|
|
310
|
+
releaseHorizontally(journal, element);
|
|
311
|
+
changed = true;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return changed;
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Expands `root` (at its current width) and every element inside it that clips its content,
|
|
318
|
+
* repeating until nothing changes. Returns a function that restores every inline style it touched.
|
|
319
|
+
*/
|
|
320
|
+
export function EnterPrintMode(root) {
|
|
321
|
+
const journal = new InlineStyleJournal();
|
|
322
|
+
expandRoot(journal, root);
|
|
323
|
+
for (let pass = 0; pass < MAX_EXPAND_PASSES && expandClippingPass(journal, root); pass++) {
|
|
324
|
+
// each pass can reveal a new clipping ancestor
|
|
325
|
+
}
|
|
326
|
+
return () => journal.RestoreAll();
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* How far the widest content inside `root` runs past its container, in CSS pixels: a table wider
|
|
330
|
+
* than its card overflows into the card's padding and border even when the root itself is not
|
|
331
|
+
* wider. Elements that clip on purpose (`overflow: hidden`, an ellipsis cell) and svg internals
|
|
332
|
+
* are ignored.
|
|
333
|
+
*/
|
|
334
|
+
export function HorizontalOverflow(root) {
|
|
335
|
+
let widest = Math.max(0, root.scrollWidth - root.clientWidth);
|
|
336
|
+
for (const element of Array.from(root.querySelectorAll('*'))) {
|
|
337
|
+
const style = getComputedStyle(element);
|
|
338
|
+
if (element.closest('svg') || element.childElementCount === 0 || CLIPPING_OVERFLOW.has(style.overflowX || style.overflow)) {
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
widest = Math.max(widest, element.scrollWidth - element.clientWidth);
|
|
342
|
+
}
|
|
343
|
+
return widest;
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Lays `root` out at `widthPx` (the page's printable width), whatever its container's width. The
|
|
347
|
+
* root is taken out of the page's flow (absolutely positioned at its container's top left) so its
|
|
348
|
+
* page width cannot widen the host's flex panes and reflow the page around it. Returns a function
|
|
349
|
+
* that restores its inline style.
|
|
350
|
+
*/
|
|
351
|
+
export function PinLayoutWidth(root, widthPx) {
|
|
352
|
+
const journal = new InlineStyleJournal();
|
|
353
|
+
journal.Set(root, 'position', 'absolute');
|
|
354
|
+
journal.Set(root, 'top', '0');
|
|
355
|
+
journal.Set(root, 'left', '0');
|
|
356
|
+
journal.Set(root, 'width', `${widthPx}px`);
|
|
357
|
+
return () => journal.RestoreAll();
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Re-renders every Chart.js chart on the page at a capture pixel ratio with animation off, so
|
|
361
|
+
* canvases are sharp and never caught mid-animation. Returns a function that restores them.
|
|
362
|
+
*/
|
|
363
|
+
export function SharpenCharts(win = window) {
|
|
364
|
+
const instances = Object.values(win.Chart?.instances ?? {});
|
|
365
|
+
const originals = instances.map(chart => ({ chart, ratio: chart.options.devicePixelRatio, animation: chart.options.animation }));
|
|
366
|
+
for (const { chart } of originals) {
|
|
367
|
+
chart.options.devicePixelRatio = CAPTURE_CHART_PIXEL_RATIO;
|
|
368
|
+
chart.options.animation = false;
|
|
369
|
+
chart.resize();
|
|
370
|
+
chart.update('none');
|
|
371
|
+
}
|
|
372
|
+
return () => {
|
|
373
|
+
for (const { chart, ratio, animation } of originals) {
|
|
374
|
+
chart.options.devicePixelRatio = ratio;
|
|
375
|
+
chart.options.animation = animation;
|
|
376
|
+
chart.resize();
|
|
377
|
+
chart.update('none');
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
/** Lets layout, ResizeObservers and Chart.js resizes settle after print mode changes sizes. */
|
|
382
|
+
async function settleLayout() {
|
|
383
|
+
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
|
|
384
|
+
await new Promise(resolve => setTimeout(resolve, 250));
|
|
385
|
+
}
|
|
386
|
+
/** Leaves export controls (ExportableData's buttons) out of the capture. */
|
|
387
|
+
function isCapturedNode(node) {
|
|
388
|
+
return !(node.getAttribute && node.getAttribute(EXPORT_CONTROL_ATTRIBUTE) === 'true');
|
|
389
|
+
}
|
|
390
|
+
/** The nearest ancestor that scrolls (the viewer pane), whose visible box the cover hides. */
|
|
391
|
+
function scrollingAncestor(element) {
|
|
392
|
+
for (let node = element.parentElement; node && node !== document.body; node = node.parentElement) {
|
|
393
|
+
if (CLIPPING_OVERFLOW.has(getComputedStyle(node).overflowY)) {
|
|
394
|
+
return node;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
return null;
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Covers the component's on-screen area with a "Preparing PDF…" panel while it is laid out at page
|
|
401
|
+
* width, so the user does not watch it reflow. The cover sits outside the root, so it is not captured.
|
|
402
|
+
*/
|
|
403
|
+
function showPreparingCover(root) {
|
|
404
|
+
const box = (scrollingAncestor(root) ?? root).getBoundingClientRect();
|
|
405
|
+
const cover = document.createElement('div');
|
|
406
|
+
cover.setAttribute('role', 'status');
|
|
407
|
+
cover.textContent = 'Preparing PDF…';
|
|
408
|
+
Object.assign(cover.style, {
|
|
409
|
+
position: 'fixed', left: `${box.left}px`, top: `${box.top}px`, width: `${box.width}px`, height: `${box.height}px`,
|
|
410
|
+
zIndex: '10000', display: 'flex', alignItems: 'center', justifyContent: 'center',
|
|
411
|
+
background: 'var(--mj-bg-surface, #ffffff)', color: 'var(--mj-text-secondary, #555555)', fontSize: '14px',
|
|
412
|
+
});
|
|
413
|
+
document.body.appendChild(cover);
|
|
414
|
+
return () => cover.remove();
|
|
415
|
+
}
|
|
416
|
+
/** The capture background when nothing behind the component paints one. */
|
|
417
|
+
const WHITE = { R: 255, G: 255, B: 255, A: 255 };
|
|
418
|
+
/** A band pixel within this distance of the background, on every channel, counts as background. */
|
|
419
|
+
const BLANK_PIXEL_TOLERANCE = 10;
|
|
420
|
+
/**
|
|
421
|
+
* Resolves a CSS colour to channels by painting it on a 1×1 canvas, so every syntax a computed style
|
|
422
|
+
* can hold (`rgb()`, `color(srgb …)` from `color-mix()`, `oklch()`) comes out the same way. An
|
|
423
|
+
* unparseable colour, or no canvas, reads as transparent.
|
|
424
|
+
*/
|
|
425
|
+
function resolveCssColor(css) {
|
|
426
|
+
const canvas = document.createElement('canvas');
|
|
427
|
+
canvas.width = 1;
|
|
428
|
+
canvas.height = 1;
|
|
429
|
+
const context = canvas.getContext('2d', { willReadFrequently: true });
|
|
430
|
+
if (!context) {
|
|
431
|
+
return { R: 0, G: 0, B: 0, A: 0 };
|
|
432
|
+
}
|
|
433
|
+
context.fillStyle = 'transparent';
|
|
434
|
+
context.fillStyle = css;
|
|
435
|
+
context.fillRect(0, 0, 1, 1);
|
|
436
|
+
const [R, G, B, A] = context.getImageData(0, 0, 1, 1).data;
|
|
437
|
+
return { R, G, B, A };
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* The colour a stack of backgrounds shows, nearest first: each translucent layer is blended over the
|
|
441
|
+
* ones behind it, down to the first opaque layer, or over white when none is opaque.
|
|
442
|
+
*/
|
|
443
|
+
export function BlendBackgrounds(layers) {
|
|
444
|
+
const opaqueIndex = layers.findIndex(layer => layer.A >= 255);
|
|
445
|
+
const visible = opaqueIndex >= 0 ? layers.slice(0, opaqueIndex + 1) : [...layers, WHITE];
|
|
446
|
+
return visible.reduceRight((behind, layer) => {
|
|
447
|
+
const alpha = layer.A / 255;
|
|
448
|
+
const mix = (front, back) => Math.round(front * alpha + back * (1 - alpha));
|
|
449
|
+
return { R: mix(layer.R, behind.R), G: mix(layer.G, behind.G), B: mix(layer.B, behind.B), A: 255 };
|
|
450
|
+
}, WHITE);
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* The background the component is seen on. Its root is often transparent and shows an ancestor's
|
|
454
|
+
* surface, which in a dark theme is dark under light text; capturing on white would lose that text.
|
|
455
|
+
*/
|
|
456
|
+
function captureBackground(root) {
|
|
457
|
+
const layers = [];
|
|
458
|
+
for (let element = root; element; element = element.parentElement) {
|
|
459
|
+
const layer = resolveCssColor(getComputedStyle(element).backgroundColor);
|
|
460
|
+
if (layer.A > 0) {
|
|
461
|
+
layers.push(layer);
|
|
462
|
+
}
|
|
463
|
+
if (layer.A >= 255) {
|
|
464
|
+
break;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
return BlendBackgrounds(layers);
|
|
468
|
+
}
|
|
469
|
+
function cssColor(color) {
|
|
470
|
+
return `rgb(${color.R}, ${color.G}, ${color.B})`;
|
|
471
|
+
}
|
|
472
|
+
/**
|
|
473
|
+
* Where every element of `root` sits vertically, in captured-image pixels. Svg internals are left out
|
|
474
|
+
* (the svg itself counts), and so are export controls.
|
|
475
|
+
*/
|
|
476
|
+
/**
|
|
477
|
+
* An svg's vertical extent including what it draws past its own box (ribbons or labels outside its
|
|
478
|
+
* viewBox with `overflow: visible`), within its container, so a page break never cuts the drawing.
|
|
479
|
+
*/
|
|
480
|
+
function svgDrawingBox(svg) {
|
|
481
|
+
const own = svg.getBoundingClientRect();
|
|
482
|
+
// Overshoot is counted only within the svg's container: a chart drawing over the next card is the
|
|
483
|
+
// chart's own defect, and counting it would weld that card to the chart.
|
|
484
|
+
const container = svg.parentElement?.getBoundingClientRect() ?? own;
|
|
485
|
+
let top = own.top;
|
|
486
|
+
let bottom = own.bottom;
|
|
487
|
+
for (const shape of Array.from(svg.querySelectorAll('*'))) {
|
|
488
|
+
const box = shape.getBoundingClientRect();
|
|
489
|
+
if (box.height > 0) {
|
|
490
|
+
top = Math.min(top, box.top);
|
|
491
|
+
bottom = Math.max(bottom, box.bottom);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
return { top: Math.max(top, container.top), bottom: Math.min(bottom, container.bottom) };
|
|
495
|
+
}
|
|
496
|
+
/**
|
|
497
|
+
* A table's lead-in, kept on one page: from where its section starts (a card's title, subtitle and
|
|
498
|
+
* search box) through its header row to its first data row. The section start is the highest
|
|
499
|
+
* enclosing container that begins at most `maxLeadPx` above the table, so the lead-in never reaches
|
|
500
|
+
* back to unrelated content. Null when the table has no visible data row.
|
|
501
|
+
*/
|
|
502
|
+
export function TableLeadBlock(table, root, maxLeadPx) {
|
|
503
|
+
const firstRow = Array.from(table.querySelectorAll('tbody tr')).find(row => row.getBoundingClientRect().height > 0);
|
|
504
|
+
if (!firstRow) {
|
|
505
|
+
return null;
|
|
506
|
+
}
|
|
507
|
+
const tableTop = table.getBoundingClientRect().top;
|
|
508
|
+
let top = tableTop;
|
|
509
|
+
for (let node = table.parentElement; node && node !== root; node = node.parentElement) {
|
|
510
|
+
const box = node.getBoundingClientRect();
|
|
511
|
+
if (box.width === 0 && box.height === 0) {
|
|
512
|
+
continue; // a box-less wrapper (`display: contents`, as the MJ runtime puts around each component)
|
|
513
|
+
}
|
|
514
|
+
if (tableTop - box.top > maxLeadPx) {
|
|
515
|
+
break;
|
|
516
|
+
}
|
|
517
|
+
top = Math.min(top, box.top);
|
|
518
|
+
}
|
|
519
|
+
return { top, bottom: firstRow.getBoundingClientRect().bottom };
|
|
520
|
+
}
|
|
521
|
+
function captureBlocks(root, scale, orientation) {
|
|
522
|
+
const top = root.getBoundingClientRect().top;
|
|
523
|
+
const blocks = [];
|
|
524
|
+
// A page is this many CSS pixels tall at the capture's width; a table's lead-in may span about a third of it.
|
|
525
|
+
const page = pageSize(orientation);
|
|
526
|
+
const pageHeightCss = root.scrollWidth * (page.HeightMM - 2 * PAGE_MARGIN_MM) / (page.WidthMM - 2 * PAGE_MARGIN_MM);
|
|
527
|
+
for (const table of Array.from(root.querySelectorAll('table'))) {
|
|
528
|
+
const lead = TableLeadBlock(table, root, pageHeightCss * TABLE_LEAD_PAGE_SHARE);
|
|
529
|
+
if (lead) {
|
|
530
|
+
blocks.push({ Top: (lead.top - top) * scale, Bottom: (lead.bottom - top) * scale, Atomic: true });
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
for (const element of Array.from(root.querySelectorAll('*'))) {
|
|
534
|
+
if ((element.parentElement && element.parentElement.closest('svg')) || element.closest(`[${EXPORT_CONTROL_ATTRIBUTE}="true"]`)) {
|
|
535
|
+
continue;
|
|
536
|
+
}
|
|
537
|
+
const box = element.tagName === 'svg' ? svgDrawingBox(element) : element.getBoundingClientRect();
|
|
538
|
+
if (box.bottom > box.top) {
|
|
539
|
+
const atomic = ATOMIC_TAGS.has(element.tagName) || element.childElementCount === 0;
|
|
540
|
+
const keepWithNext = KEEP_WITH_NEXT_TAGS.has(element.tagName) || element.getAttribute('role') === 'heading';
|
|
541
|
+
blocks.push({ Top: (box.top - top) * scale, Bottom: (box.bottom - top) * scale, Atomic: atomic, KeepWithNext: keepWithNext });
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
return blocks;
|
|
545
|
+
}
|
|
546
|
+
let htmlToImage = null;
|
|
547
|
+
/**
|
|
548
|
+
* Loads `html-to-image` the first time a PDF is captured. A dynamic import is correct here (MJ allows one
|
|
549
|
+
* for a measured bundle-size deferral): this package is bundled into hosts that never export a PDF, such
|
|
550
|
+
* as the realtime widget's call, and a static import puts the rasterizer (about 15 KB minified) on their
|
|
551
|
+
* start-up path. Loaded here, the bundler keeps it in a chunk only an export downloads.
|
|
552
|
+
*/
|
|
553
|
+
function loadHtmlToImage() {
|
|
554
|
+
htmlToImage ??= import('html-to-image');
|
|
555
|
+
return htmlToImage;
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Captures `root` laid out at the page width and fully expanded, as a canvas. The width is applied
|
|
559
|
+
* first and allowed to settle (charts re-render on resize), then clipping elements are expanded.
|
|
560
|
+
* Every style and chart is restored afterwards.
|
|
561
|
+
*/
|
|
562
|
+
async function captureAtPageWidth(root, orientation) {
|
|
563
|
+
const removeCover = showPreparingCover(root);
|
|
564
|
+
const restoreCharts = SharpenCharts();
|
|
565
|
+
const pageWidth = PageLayoutWidth(orientation);
|
|
566
|
+
let restoreWidth = PinLayoutWidth(root, pageWidth);
|
|
567
|
+
let exitPrintMode = null;
|
|
568
|
+
try {
|
|
569
|
+
await settleLayout();
|
|
570
|
+
exitPrintMode = EnterPrintMode(root);
|
|
571
|
+
await settleLayout();
|
|
572
|
+
// A table that needs more than the page width (released from its scroller) would spill past its
|
|
573
|
+
// card: lay the whole component out wider and let the page scale it down. Widen by the largest
|
|
574
|
+
// overflow inside the component until no container's content is wider than the container.
|
|
575
|
+
let layoutWidth = pageWidth;
|
|
576
|
+
const maxWidth = pageWidth * MAX_LAYOUT_WIDTH_FACTOR;
|
|
577
|
+
for (let round = 0, overflow = HorizontalOverflow(root); round < MAX_WIDEN_ROUNDS && overflow > 1 && layoutWidth < maxWidth; round++, overflow = HorizontalOverflow(root)) {
|
|
578
|
+
layoutWidth = Math.min(Math.ceil(layoutWidth + overflow), maxWidth);
|
|
579
|
+
exitPrintMode();
|
|
580
|
+
restoreWidth();
|
|
581
|
+
restoreWidth = PinLayoutWidth(root, layoutWidth);
|
|
582
|
+
await settleLayout();
|
|
583
|
+
exitPrintMode = EnterPrintMode(root);
|
|
584
|
+
await settleLayout();
|
|
585
|
+
}
|
|
586
|
+
const width = root.scrollWidth;
|
|
587
|
+
const background = captureBackground(root);
|
|
588
|
+
const { toCanvas } = await loadHtmlToImage();
|
|
589
|
+
const canvas = await toCanvas(root, {
|
|
590
|
+
pixelRatio: CAPTURE_PIXEL_RATIO,
|
|
591
|
+
backgroundColor: cssColor(background),
|
|
592
|
+
width,
|
|
593
|
+
height: root.scrollHeight,
|
|
594
|
+
filter: node => !(node instanceof HTMLElement) || isCapturedNode(node),
|
|
595
|
+
});
|
|
596
|
+
return { Canvas: canvas, Blocks: captureBlocks(root, canvas.width / Math.max(width, 1), orientation), Background: background };
|
|
597
|
+
}
|
|
598
|
+
finally {
|
|
599
|
+
exitPrintMode?.();
|
|
600
|
+
restoreWidth();
|
|
601
|
+
restoreCharts();
|
|
602
|
+
removeCover();
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
/** Copies one band of the captured canvas into its own canvas, for one page. */
|
|
606
|
+
function sliceCanvas(source, slice, background) {
|
|
607
|
+
const band = document.createElement('canvas');
|
|
608
|
+
band.width = source.width;
|
|
609
|
+
band.height = slice.SourceHeight;
|
|
610
|
+
const context = band.getContext('2d');
|
|
611
|
+
if (context) {
|
|
612
|
+
context.fillStyle = cssColor(background);
|
|
613
|
+
context.fillRect(0, 0, band.width, band.height);
|
|
614
|
+
context.drawImage(source, 0, slice.SourceY, source.width, slice.SourceHeight, 0, 0, source.width, slice.SourceHeight);
|
|
615
|
+
}
|
|
616
|
+
return band;
|
|
617
|
+
}
|
|
618
|
+
/** True when RGBA pixel data holds nothing but the background colour (or very near it). */
|
|
619
|
+
export function IsBlankPixels(pixels, background) {
|
|
620
|
+
const near = (value, target) => Math.abs(value - target) <= BLANK_PIXEL_TOLERANCE;
|
|
621
|
+
for (let i = 0; i < pixels.length; i += 4 * 7) { // every 7th pixel is plenty for page-sized content
|
|
622
|
+
if (!near(pixels[i], background.R) || !near(pixels[i + 1], background.G) || !near(pixels[i + 2], background.B)) {
|
|
623
|
+
return false;
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
return true;
|
|
627
|
+
}
|
|
628
|
+
/** True when a band holds nothing but the capture background, such as trailing padding. */
|
|
629
|
+
function isBlankBand(band, background) {
|
|
630
|
+
const context = band.getContext('2d');
|
|
631
|
+
if (!context || band.width === 0 || band.height === 0) {
|
|
632
|
+
return true;
|
|
633
|
+
}
|
|
634
|
+
return IsBlankPixels(context.getImageData(0, 0, band.width, band.height).data, background);
|
|
635
|
+
}
|
|
636
|
+
/** The JPEG file bytes of a canvas. */
|
|
637
|
+
function jpegBytes(canvas) {
|
|
638
|
+
const base64 = canvas.toDataURL('image/jpeg', 0.92).split(',')[1] ?? '';
|
|
639
|
+
const binary = atob(base64);
|
|
640
|
+
const bytes = new Uint8Array(binary.length);
|
|
641
|
+
for (let i = 0; i < binary.length; i++) {
|
|
642
|
+
bytes[i] = binary.charCodeAt(i);
|
|
643
|
+
}
|
|
644
|
+
return bytes;
|
|
645
|
+
}
|
|
646
|
+
/** Builds the PDF from the captured canvas, one page per slice. */
|
|
647
|
+
function buildPdf(captured, orientation) {
|
|
648
|
+
const canvas = captured.Canvas;
|
|
649
|
+
const plan = PlanPdfPages(canvas.width, canvas.height, orientation, captured.Blocks);
|
|
650
|
+
const bands = plan.Slices.map(slice => ({ slice, band: sliceCanvas(canvas, slice, captured.Background) }));
|
|
651
|
+
const printed = bands.filter(({ band }) => !isBlankBand(band, captured.Background));
|
|
652
|
+
const pages = (printed.length > 0 ? printed : bands.slice(0, 1)).map(({ slice, band }) => ({
|
|
653
|
+
Jpeg: jpegBytes(band),
|
|
654
|
+
PixelWidth: band.width,
|
|
655
|
+
PixelHeight: band.height,
|
|
656
|
+
PageWidthMM: plan.PageWidthMM,
|
|
657
|
+
PageHeightMM: plan.PageHeightMM,
|
|
658
|
+
XMM: slice.XMM,
|
|
659
|
+
YMM: PAGE_MARGIN_MM,
|
|
660
|
+
DrawWidthMM: slice.DrawWidthMM,
|
|
661
|
+
DrawHeightMM: slice.DrawHeightMM,
|
|
662
|
+
}));
|
|
663
|
+
return BuildImagePdf(pages);
|
|
664
|
+
}
|
|
665
|
+
/** Hands the file to the browser as a download. */
|
|
666
|
+
function downloadFile(bytes, fileName) {
|
|
667
|
+
const url = URL.createObjectURL(new Blob([bytes], { type: 'application/pdf' }));
|
|
668
|
+
const anchor = document.createElement('a');
|
|
669
|
+
anchor.href = url;
|
|
670
|
+
anchor.download = fileName;
|
|
671
|
+
anchor.style.display = 'none';
|
|
672
|
+
document.body.appendChild(anchor);
|
|
673
|
+
anchor.click();
|
|
674
|
+
anchor.remove();
|
|
675
|
+
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
|
676
|
+
}
|
|
677
|
+
/**
|
|
678
|
+
* Exports the rendered component under `root` as a PDF download named `<title>_<date>.pdf`:
|
|
679
|
+
* everything the component shows, including content behind inner scrollbars, in its current state,
|
|
680
|
+
* laid out at the page's printable width so the PDF is the same whatever the viewer's size.
|
|
681
|
+
*/
|
|
682
|
+
export async function ExportComponentToPDF(root, title, orientation = 'portrait') {
|
|
683
|
+
const captured = await captureAtPageWidth(root, orientation);
|
|
684
|
+
downloadFile(buildPdf(captured, orientation), PdfFileName(title));
|
|
685
|
+
}
|
|
686
|
+
//# sourceMappingURL=component-pdf-export.js.map
|