@octanejs/to-print 0.0.1
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/LICENSE +21 -0
- package/README.md +21 -0
- package/UPSTREAM.md +46 -0
- package/package.json +54 -0
- package/src/consts.ts +1 -0
- package/src/hooks/useReactToPrint.ts +111 -0
- package/src/index.ts +3 -0
- package/src/types/ContentNode.ts +1 -0
- package/src/types/UseReactToPrintFn.ts +3 -0
- package/src/types/UseReactToPrintHookContent.ts +7 -0
- package/src/types/UseReactToPrintOptions.ts +75 -0
- package/src/types/font-face.d.ts +19 -0
- package/src/types/font.ts +7 -0
- package/src/utils/appendPrintWindow.ts +14 -0
- package/src/utils/clone.ts +50 -0
- package/src/utils/generatePrintWindow.ts +37 -0
- package/src/utils/getContentNode.ts +44 -0
- package/src/utils/getErrorMessage.ts +7 -0
- package/src/utils/getPrintData.ts +47 -0
- package/src/utils/handlePrintWindowOnLoad.ts +396 -0
- package/src/utils/logMessage.ts +25 -0
- package/src/utils/removePrintIframe.ts +15 -0
- package/src/utils/startPrint.ts +142 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Matthew Herbst, Gregory Nowakowski
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# @octanejs/to-print
|
|
2
|
+
|
|
3
|
+
Octane binding for [`react-to-print@3.3.0`](https://github.com/MatthewHerbst/react-to-print).
|
|
4
|
+
|
|
5
|
+
```tsrx
|
|
6
|
+
import { useRef } from 'octane';
|
|
7
|
+
import { useReactToPrint } from '@octanejs/to-print';
|
|
8
|
+
|
|
9
|
+
export function Invoice() {
|
|
10
|
+
const contentRef = useRef<HTMLDivElement>(null);
|
|
11
|
+
const handlePrint = useReactToPrint({ contentRef });
|
|
12
|
+
return (
|
|
13
|
+
<div>
|
|
14
|
+
<button type="button" onClick={handlePrint}>Print</button>
|
|
15
|
+
<div ref={contentRef}>printable</div>
|
|
16
|
+
</div>
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
See [UPSTREAM.md](./UPSTREAM.md) for the pin and crosswalk.
|
package/UPSTREAM.md
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# Upstream provenance
|
|
2
|
+
|
|
3
|
+
`@octanejs/to-print` is pinned to `react-to-print@3.3.0`.
|
|
4
|
+
|
|
5
|
+
- repository: https://github.com/MatthewHerbst/react-to-print
|
|
6
|
+
- tag: `v3.3.0`
|
|
7
|
+
- tag commit: `853666f180006b68b533f216e58f974cc791a97f`
|
|
8
|
+
- advertised range: `3.3.x`
|
|
9
|
+
- license: MIT
|
|
10
|
+
- npm integrity: `sha512-7j9GIeNZA9glZlbv9mIbIHDOOx+WYfRMbJzh04NiSKjdaeGkxJuKjJQrtRuNKtt5AvEVVjrLCPokZ9yJX51Fvg==`
|
|
11
|
+
- npm shasum: `7c893951b2c621a1c2190cb57a88af40852b129c`
|
|
12
|
+
|
|
13
|
+
## Source boundary
|
|
14
|
+
|
|
15
|
+
- `upstream/src/` is the canonical tagged TypeScript source, LICENSE, README, and CHANGELOG.
|
|
16
|
+
- `upstream/npm/` is the published tarball (compiled `dist/`).
|
|
17
|
+
- Octane `src/` mirrors `upstream/src/` module-for-module.
|
|
18
|
+
|
|
19
|
+
Vendored evidence is development-only and excluded from package `files`.
|
|
20
|
+
|
|
21
|
+
## Export crosswalk
|
|
22
|
+
|
|
23
|
+
| Upstream export | Octane status | Evidence / divergence |
|
|
24
|
+
| --- | --- | --- |
|
|
25
|
+
| `useReactToPrint` | Ported | `src/hooks/useReactToPrint.ts`; explicit trailing hook-slot forwarding; `tests/to-print.test.ts` |
|
|
26
|
+
| `UseReactToPrintFn` | Ported | `src/types/UseReactToPrintFn.ts` |
|
|
27
|
+
| `UseReactToPrintOptions` | Ported | `src/types/UseReactToPrintOptions.ts`; `contentRef` is `{ current: ContentNode \| null }` |
|
|
28
|
+
| `UseReactToPrintHookContent` | Ported | `src/types/UseReactToPrintHookContent.ts`; `Event` instead of `React.UIEvent` |
|
|
29
|
+
| `ContentNode` | Ported | `src/types/ContentNode.ts` |
|
|
30
|
+
| `Font` | Ported | `src/types/font.ts` |
|
|
31
|
+
|
|
32
|
+
## Upstream test disposition
|
|
33
|
+
|
|
34
|
+
| Upstream artifact | Disposition |
|
|
35
|
+
| --- | --- |
|
|
36
|
+
| package `scripts` (`build`, `lint`, `start`; no `test`) | Confirmed at pin: the repository has no unit test suite. Examples live outside `src/`. |
|
|
37
|
+
| `examples/` (if present in the tag) | Out of scope: demo app, not a test oracle |
|
|
38
|
+
|
|
39
|
+
Octane behavioral coverage is `tests/to-print.test.ts` (hook return, missing content diagnostic, custom `print`). It is Octane-only because upstream ships no unit tests.
|
|
40
|
+
|
|
41
|
+
## Intentional divergences
|
|
42
|
+
|
|
43
|
+
- React `RefObject` / `IframeHTMLAttributes` / `UIEvent` types are replaced with structural DOM types.
|
|
44
|
+
- The plain TypeScript hook forwards its compiler-injected trailing slot to
|
|
45
|
+
`useCallback`; when called without options, a symbol in the options position
|
|
46
|
+
is treated as empty options.
|
package/package.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@octanejs/to-print",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Octane binding for react-to-print 3.3.0.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=22.22.2"
|
|
9
|
+
},
|
|
10
|
+
"octane": {
|
|
11
|
+
"hookSlots": {
|
|
12
|
+
"manual": [
|
|
13
|
+
"src"
|
|
14
|
+
]
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"author": {
|
|
18
|
+
"name": "Dominic Gannaway",
|
|
19
|
+
"email": "dg@domgan.com"
|
|
20
|
+
},
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public"
|
|
23
|
+
},
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "git+https://github.com/octanejs/octane.git",
|
|
27
|
+
"directory": "packages/to-print"
|
|
28
|
+
},
|
|
29
|
+
"main": "./src/index.ts",
|
|
30
|
+
"module": "./src/index.ts",
|
|
31
|
+
"types": "./src/index.ts",
|
|
32
|
+
"files": [
|
|
33
|
+
"src",
|
|
34
|
+
"README.md",
|
|
35
|
+
"UPSTREAM.md",
|
|
36
|
+
"LICENSE"
|
|
37
|
+
],
|
|
38
|
+
"exports": {
|
|
39
|
+
".": "./src/index.ts",
|
|
40
|
+
"./package.json": "./package.json"
|
|
41
|
+
},
|
|
42
|
+
"peerDependencies": {
|
|
43
|
+
"octane": "0.1.45"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"vitest": "^4.1.10",
|
|
47
|
+
"@octanejs/testing-library": "0.1.42",
|
|
48
|
+
"octane": "0.1.45"
|
|
49
|
+
},
|
|
50
|
+
"scripts": {
|
|
51
|
+
"test": "vitest run --root ../.. --config vitest.config.js --project to-print",
|
|
52
|
+
"typecheck": "tsrx-tsc --noEmit"
|
|
53
|
+
}
|
|
54
|
+
}
|
package/src/consts.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const DEFAULT_PRINT_WINDOW_ID = 'printWindow';
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { useCallback } from 'octane';
|
|
2
|
+
|
|
3
|
+
import type { UseReactToPrintHookContent } from '../types/UseReactToPrintHookContent';
|
|
4
|
+
import type { UseReactToPrintFn } from '../types/UseReactToPrintFn';
|
|
5
|
+
import type { UseReactToPrintOptions } from '../types/UseReactToPrintOptions';
|
|
6
|
+
import { appendPrintWindow } from '../utils/appendPrintWindow';
|
|
7
|
+
import { generatePrintWindow } from '../utils/generatePrintWindow';
|
|
8
|
+
import { getErrorFromUnknown } from '../utils/getErrorMessage';
|
|
9
|
+
import { getPrintData } from '../utils/getPrintData';
|
|
10
|
+
import { logMessages } from '../utils/logMessage';
|
|
11
|
+
import { removePrintIframe } from '../utils/removePrintIframe';
|
|
12
|
+
|
|
13
|
+
export function useReactToPrint(options?: UseReactToPrintOptions): UseReactToPrintFn;
|
|
14
|
+
export function useReactToPrint(
|
|
15
|
+
options: UseReactToPrintOptions | symbol = {},
|
|
16
|
+
...rest: [slot?: symbol]
|
|
17
|
+
): UseReactToPrintFn {
|
|
18
|
+
const slot = typeof options === 'symbol' ? options : rest[0];
|
|
19
|
+
const resolved = typeof options === 'symbol' ? ({} as UseReactToPrintOptions) : options;
|
|
20
|
+
const {
|
|
21
|
+
bodyClass,
|
|
22
|
+
contentRef,
|
|
23
|
+
copyShadowRoots,
|
|
24
|
+
documentTitle,
|
|
25
|
+
fonts,
|
|
26
|
+
ignoreGlobalStyles,
|
|
27
|
+
nonce,
|
|
28
|
+
onAfterPrint,
|
|
29
|
+
onBeforePrint,
|
|
30
|
+
onPrintError,
|
|
31
|
+
pageStyle,
|
|
32
|
+
preserveAfterPrint,
|
|
33
|
+
print,
|
|
34
|
+
printIframeProps,
|
|
35
|
+
suppressErrors,
|
|
36
|
+
} = resolved;
|
|
37
|
+
|
|
38
|
+
const handlePrint = useCallback(
|
|
39
|
+
function handlePrint(optionalContent?: UseReactToPrintHookContent) {
|
|
40
|
+
// Ensure we remove any pre-existing print windows before adding a new one.
|
|
41
|
+
removePrintIframe(preserveAfterPrint, true);
|
|
42
|
+
|
|
43
|
+
function beginPrint() {
|
|
44
|
+
const printOptions: UseReactToPrintOptions = {
|
|
45
|
+
bodyClass,
|
|
46
|
+
contentRef,
|
|
47
|
+
copyShadowRoots,
|
|
48
|
+
documentTitle,
|
|
49
|
+
fonts,
|
|
50
|
+
ignoreGlobalStyles,
|
|
51
|
+
nonce,
|
|
52
|
+
onAfterPrint,
|
|
53
|
+
onBeforePrint,
|
|
54
|
+
onPrintError,
|
|
55
|
+
pageStyle,
|
|
56
|
+
preserveAfterPrint,
|
|
57
|
+
print,
|
|
58
|
+
printIframeProps,
|
|
59
|
+
suppressErrors,
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
const printWindow = generatePrintWindow(printIframeProps);
|
|
63
|
+
const data = getPrintData(optionalContent, printOptions);
|
|
64
|
+
|
|
65
|
+
if (!data) {
|
|
66
|
+
logMessages({
|
|
67
|
+
messages: ['There is nothing to print'],
|
|
68
|
+
suppressErrors,
|
|
69
|
+
});
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
appendPrintWindow(printWindow, data, printOptions);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Run onBeforePrint before appending the iframe, which begins loading
|
|
77
|
+
// the resources required by the print document.
|
|
78
|
+
if (onBeforePrint) {
|
|
79
|
+
onBeforePrint()
|
|
80
|
+
.then(function onBeforePrintResolved() {
|
|
81
|
+
beginPrint();
|
|
82
|
+
})
|
|
83
|
+
.catch(function onBeforePrintRejected(error: unknown) {
|
|
84
|
+
onPrintError?.('onBeforePrint', getErrorFromUnknown(error));
|
|
85
|
+
});
|
|
86
|
+
} else {
|
|
87
|
+
beginPrint();
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
[
|
|
91
|
+
bodyClass,
|
|
92
|
+
contentRef,
|
|
93
|
+
copyShadowRoots,
|
|
94
|
+
documentTitle,
|
|
95
|
+
fonts,
|
|
96
|
+
ignoreGlobalStyles,
|
|
97
|
+
nonce,
|
|
98
|
+
onAfterPrint,
|
|
99
|
+
onBeforePrint,
|
|
100
|
+
onPrintError,
|
|
101
|
+
pageStyle,
|
|
102
|
+
preserveAfterPrint,
|
|
103
|
+
printIframeProps,
|
|
104
|
+
print,
|
|
105
|
+
suppressErrors,
|
|
106
|
+
],
|
|
107
|
+
slot,
|
|
108
|
+
);
|
|
109
|
+
|
|
110
|
+
return handlePrint;
|
|
111
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export type ContentNode = Element | Text | null | undefined;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ContentNode } from './ContentNode';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `Event` allowed so that the `useReactToPrint` callback can be passed directly to an event
|
|
5
|
+
* handler rather than needing to be wrapped.
|
|
6
|
+
*/
|
|
7
|
+
export type UseReactToPrintHookContent = Event | (() => ContentNode);
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { JSX } from 'octane/jsx-runtime';
|
|
2
|
+
import type { Font } from './font';
|
|
3
|
+
import type { ContentNode } from './ContentNode';
|
|
4
|
+
|
|
5
|
+
type IframeProps = JSX.IntrinsicElements['iframe'];
|
|
6
|
+
|
|
7
|
+
/** Options for `useReactToPrint` */
|
|
8
|
+
export interface UseReactToPrintOptions {
|
|
9
|
+
/** One or more class names to pass to the print window, separated by spaces */
|
|
10
|
+
bodyClass?: string;
|
|
11
|
+
/**
|
|
12
|
+
* The ref pointing to the content to be printed. Alternatively, pass the ref directly to the
|
|
13
|
+
* callback returned by `useReactToPrint`
|
|
14
|
+
*/
|
|
15
|
+
contentRef?: { current: ContentNode | null };
|
|
16
|
+
/**
|
|
17
|
+
* Set the title for printing when saving as a file.
|
|
18
|
+
* Can be a static string or a function that returns a string (evaluated at print time).
|
|
19
|
+
* Ignored when passing a custom `print` option
|
|
20
|
+
*/
|
|
21
|
+
documentTitle?: string | (() => string);
|
|
22
|
+
/** A list of fonts to load into the printing iframe. This is useful if you are using custom fonts */
|
|
23
|
+
fonts?: Font[];
|
|
24
|
+
/** Ignore all `<style>` and `<link type="stylesheet" />` tags from `<head>` */
|
|
25
|
+
ignoreGlobalStyles?: boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Set the [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce)
|
|
28
|
+
* attribute for allow-listing script and style elements for Content Security Policy (CSP)
|
|
29
|
+
*/
|
|
30
|
+
nonce?: string;
|
|
31
|
+
/**
|
|
32
|
+
* Callback function that triggers after the print dialog is closed _regardless of if the user
|
|
33
|
+
* selected to print or cancel_
|
|
34
|
+
*/
|
|
35
|
+
onAfterPrint?: () => void;
|
|
36
|
+
/**
|
|
37
|
+
* Callback function that triggers before print. This can be used to change the content on the
|
|
38
|
+
* page before printing as an alternative to, or in conjunction with `@media print` queries. Is
|
|
39
|
+
* run prior to the print iframe being mounted.
|
|
40
|
+
*/
|
|
41
|
+
onBeforePrint?: () => Promise<void>;
|
|
42
|
+
/**
|
|
43
|
+
* Called if there is a printing error serious enough that printing cannot continue. Currently
|
|
44
|
+
* limited to Promise rejections in `onBeforePrint`, and `print`. Use this to attempt to print
|
|
45
|
+
* again. `errorLocation` will tell you where the Promise was rejected
|
|
46
|
+
*/
|
|
47
|
+
onPrintError?: (errorLocation: 'onBeforePrint' | 'print', error: Error) => void;
|
|
48
|
+
/**
|
|
49
|
+
* `react-to-print` sets some basic styles to help improve page printing, notably, removing the
|
|
50
|
+
* header and footer that most browsers add. Use this to override these styles and provide your own
|
|
51
|
+
*/
|
|
52
|
+
pageStyle?: string;
|
|
53
|
+
/**
|
|
54
|
+
* Preserve the print iframe after printing. This can be useful for debugging by inspecting the
|
|
55
|
+
* print iframe
|
|
56
|
+
*/
|
|
57
|
+
preserveAfterPrint?: boolean;
|
|
58
|
+
/**
|
|
59
|
+
* If passed, this function will be used instead of `window.print` to print the content. Use
|
|
60
|
+
* this to print in non-browser environments such as Electron
|
|
61
|
+
*/
|
|
62
|
+
print?: (target: HTMLIFrameElement) => Promise<any>;
|
|
63
|
+
/**
|
|
64
|
+
* Allows setting some security specific props on the iframe used for printing
|
|
65
|
+
*/
|
|
66
|
+
printIframeProps?: {
|
|
67
|
+
allow?: IframeProps['allow'];
|
|
68
|
+
referrerPolicy?: IframeProps['referrerPolicy'];
|
|
69
|
+
sandbox?: IframeProps['sandbox'];
|
|
70
|
+
};
|
|
71
|
+
/** When passed, prevents `console` logging of errors */
|
|
72
|
+
suppressErrors?: boolean;
|
|
73
|
+
/** When passed, shadow root content will be copied */
|
|
74
|
+
copyShadowRoots?: boolean;
|
|
75
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// Lightly modified from: https://github.com/Microsoft/TypeScript/issues/30984#issuecomment-631991019
|
|
2
|
+
// NOTE: TypeScript 4.4 added partial support for FontFace. As such, only a few missing items now
|
|
3
|
+
// need to be manually specified
|
|
4
|
+
// https://github.com/microsoft/TypeScript-DOM-lib-generator/issues/1029#issuecomment-869224737
|
|
5
|
+
export {};
|
|
6
|
+
|
|
7
|
+
declare global {
|
|
8
|
+
interface Document {
|
|
9
|
+
fonts: FontFaceSet; // https://developer.mozilla.org/en-US/docs/Web/API/Document/fonts
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
interface Window {
|
|
13
|
+
FontFace: FontFace; // https://developer.mozilla.org/en-US/docs/Web/API/FontFace
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
interface FontFaceSet extends Iterable<FontFace> {
|
|
17
|
+
add(font: FontFace): void; // https://developer.mozilla.org/en-US/docs/Web/API/FontFaceSet/add
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { UseReactToPrintOptions } from '../types/UseReactToPrintOptions';
|
|
2
|
+
import { handlePrintWindowOnLoad, HandlePrintWindowOnLoadData } from './handlePrintWindowOnLoad';
|
|
3
|
+
|
|
4
|
+
export function appendPrintWindow(
|
|
5
|
+
printWindow: HTMLIFrameElement,
|
|
6
|
+
data: HandlePrintWindowOnLoadData,
|
|
7
|
+
options: UseReactToPrintOptions,
|
|
8
|
+
) {
|
|
9
|
+
printWindow.onload = () => {
|
|
10
|
+
handlePrintWindowOnLoad(printWindow, data, options);
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
document.body.appendChild(printWindow);
|
|
14
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { logMessages } from './logMessage';
|
|
2
|
+
|
|
3
|
+
function collectElements(root: HTMLElement): HTMLElement[] {
|
|
4
|
+
const elements: HTMLElement[] = [];
|
|
5
|
+
const walker: TreeWalker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, null);
|
|
6
|
+
|
|
7
|
+
let element: Node | null = walker.nextNode();
|
|
8
|
+
while (element) {
|
|
9
|
+
elements.push(element as HTMLElement);
|
|
10
|
+
element = walker.nextNode();
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
return elements;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function cloneShadowRoots(
|
|
17
|
+
sourceNode: Node,
|
|
18
|
+
targetNode: Node,
|
|
19
|
+
suppressErrors: boolean,
|
|
20
|
+
): void {
|
|
21
|
+
const sourceElements = collectElements(sourceNode as HTMLElement);
|
|
22
|
+
const targetElements = collectElements(targetNode as HTMLElement);
|
|
23
|
+
|
|
24
|
+
if (sourceElements.length !== targetElements.length) {
|
|
25
|
+
logMessages({
|
|
26
|
+
messages: [
|
|
27
|
+
'When cloning shadow root content, source and target elements have different size. `onBeforePrint` likely resolved too early.',
|
|
28
|
+
sourceNode,
|
|
29
|
+
targetNode,
|
|
30
|
+
],
|
|
31
|
+
suppressErrors,
|
|
32
|
+
});
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
for (let i = 0; i < sourceElements.length; i++) {
|
|
37
|
+
const sourceElement = sourceElements[i];
|
|
38
|
+
const targetElement = targetElements[i];
|
|
39
|
+
|
|
40
|
+
const shadowRoot = sourceElement.shadowRoot;
|
|
41
|
+
if (shadowRoot !== null) {
|
|
42
|
+
const copiedShadowRoot = targetElement.attachShadow({ mode: shadowRoot.mode });
|
|
43
|
+
|
|
44
|
+
copiedShadowRoot.innerHTML = shadowRoot.innerHTML;
|
|
45
|
+
|
|
46
|
+
// Recursively clone any nested Shadow DOMs within this Shadow DOM content
|
|
47
|
+
cloneShadowRoots(shadowRoot, copiedShadowRoot, suppressErrors);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { DEFAULT_PRINT_WINDOW_ID } from '../consts';
|
|
2
|
+
import { UseReactToPrintOptions } from '../types/UseReactToPrintOptions';
|
|
3
|
+
|
|
4
|
+
export function generatePrintWindow(
|
|
5
|
+
printIframeProps: UseReactToPrintOptions['printIframeProps'],
|
|
6
|
+
): HTMLIFrameElement {
|
|
7
|
+
const printWindow = document.createElement('iframe');
|
|
8
|
+
printWindow.width = `${document.documentElement.clientWidth}px`;
|
|
9
|
+
printWindow.height = `${document.documentElement.clientHeight}px`;
|
|
10
|
+
printWindow.style.position = 'absolute';
|
|
11
|
+
printWindow.style.top = `-${document.documentElement.clientHeight + 100}px`;
|
|
12
|
+
printWindow.style.left = `-${document.documentElement.clientWidth + 100}px`;
|
|
13
|
+
printWindow.id = DEFAULT_PRINT_WINDOW_ID;
|
|
14
|
+
// Ensure we set a DOCTYPE on the iframe's document
|
|
15
|
+
// https://github.com/MatthewHerbst/react-to-print/issues/459
|
|
16
|
+
printWindow.srcdoc = '<!DOCTYPE html>';
|
|
17
|
+
|
|
18
|
+
// Assign user supplied iframe props
|
|
19
|
+
if (printIframeProps) {
|
|
20
|
+
if (printIframeProps.allow) {
|
|
21
|
+
// "" is not a meaningful `allow` value
|
|
22
|
+
printWindow.allow = printIframeProps.allow;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
if (printIframeProps.referrerPolicy !== undefined) {
|
|
26
|
+
// Ensure "" is valid, which applies the browser's default referrer policy
|
|
27
|
+
printWindow.referrerPolicy = printIframeProps.referrerPolicy;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
if (printIframeProps.sandbox !== undefined) {
|
|
31
|
+
// Ensure "" is valid, which applies all sandbox rules
|
|
32
|
+
printWindow.sandbox = printIframeProps.sandbox;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
return printWindow;
|
|
37
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { logMessages } from './logMessage';
|
|
2
|
+
import { ContentNode } from '../types/ContentNode';
|
|
3
|
+
import type { UseReactToPrintOptions } from '../types/UseReactToPrintOptions';
|
|
4
|
+
import { UseReactToPrintHookContent } from '../types/UseReactToPrintHookContent';
|
|
5
|
+
|
|
6
|
+
interface GetContentNodesArgs {
|
|
7
|
+
contentRef?: UseReactToPrintOptions['contentRef'];
|
|
8
|
+
optionalContent?: UseReactToPrintHookContent;
|
|
9
|
+
suppressErrors?: boolean;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function getContentNode({
|
|
13
|
+
contentRef,
|
|
14
|
+
optionalContent,
|
|
15
|
+
suppressErrors,
|
|
16
|
+
}: GetContentNodesArgs): ContentNode {
|
|
17
|
+
// This `Event` check allows passing the callback from `useReactToPrint` directly into event
|
|
18
|
+
// handlers without having to wrap it in another function to capture the event
|
|
19
|
+
if (optionalContent && typeof optionalContent === 'function') {
|
|
20
|
+
if (contentRef) {
|
|
21
|
+
logMessages({
|
|
22
|
+
level: 'warning',
|
|
23
|
+
messages: [
|
|
24
|
+
'"react-to-print" received a `contentRef` option and an optional-content param passed to its callback. The `contentRef` option will be ignored.',
|
|
25
|
+
],
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// See [#742](https://github.com/MatthewHerbst/react-to-print/issues/742) and [#724](https://github.com/MatthewHerbst/react-to-print/issues/724)
|
|
30
|
+
return optionalContent();
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (contentRef) {
|
|
34
|
+
return contentRef.current;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
logMessages({
|
|
38
|
+
messages: [
|
|
39
|
+
'"react-to-print" did not receive a `contentRef` option or a optional-content param pass to its callback.',
|
|
40
|
+
],
|
|
41
|
+
suppressErrors,
|
|
42
|
+
});
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { UseReactToPrintHookContent } from '../types/UseReactToPrintHookContent';
|
|
2
|
+
import type { UseReactToPrintOptions } from '../types/UseReactToPrintOptions';
|
|
3
|
+
import { getContentNode } from './getContentNode';
|
|
4
|
+
import type { HandlePrintWindowOnLoadData } from './handlePrintWindowOnLoad';
|
|
5
|
+
|
|
6
|
+
/** Returns `undefined` if there is nothing to print */
|
|
7
|
+
export function getPrintData(
|
|
8
|
+
optionalContent: UseReactToPrintHookContent | undefined,
|
|
9
|
+
options: UseReactToPrintOptions,
|
|
10
|
+
): HandlePrintWindowOnLoadData | undefined {
|
|
11
|
+
const { contentRef, fonts, ignoreGlobalStyles, suppressErrors } = options;
|
|
12
|
+
|
|
13
|
+
const contentNode = getContentNode({
|
|
14
|
+
contentRef,
|
|
15
|
+
optionalContent,
|
|
16
|
+
suppressErrors,
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
if (!contentNode) {
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// NOTE: `canvas` elements do not have their painted images copied
|
|
24
|
+
// https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode
|
|
25
|
+
const clonedContentNode = contentNode.cloneNode(true);
|
|
26
|
+
|
|
27
|
+
const globalLinkNodes = document.querySelectorAll("link[rel~='stylesheet'], link[as='style']");
|
|
28
|
+
const clonedImgNodes = (clonedContentNode as Element).querySelectorAll('img');
|
|
29
|
+
const clonedVideoNodes = (clonedContentNode as Element).querySelectorAll('video');
|
|
30
|
+
|
|
31
|
+
const numFonts = fonts ? fonts.length : 0;
|
|
32
|
+
|
|
33
|
+
const numResourcesToLoad =
|
|
34
|
+
(ignoreGlobalStyles ? 0 : globalLinkNodes.length) +
|
|
35
|
+
clonedImgNodes.length +
|
|
36
|
+
clonedVideoNodes.length +
|
|
37
|
+
numFonts;
|
|
38
|
+
|
|
39
|
+
return {
|
|
40
|
+
contentNode,
|
|
41
|
+
clonedContentNode,
|
|
42
|
+
clonedImgNodes,
|
|
43
|
+
clonedVideoNodes,
|
|
44
|
+
numResourcesToLoad,
|
|
45
|
+
originalCanvasNodes: (contentNode as Element).querySelectorAll('canvas'),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
import { logMessages } from './logMessage';
|
|
2
|
+
import { startPrint } from './startPrint';
|
|
3
|
+
import { Font } from '../types/font';
|
|
4
|
+
import type { UseReactToPrintOptions } from '../types/UseReactToPrintOptions';
|
|
5
|
+
import { cloneShadowRoots } from './clone';
|
|
6
|
+
import { getErrorFromUnknown } from './getErrorMessage';
|
|
7
|
+
|
|
8
|
+
export interface HandlePrintWindowOnLoadData {
|
|
9
|
+
/** The content. */
|
|
10
|
+
contentNode: Node;
|
|
11
|
+
/** The cloned content. This will be inserted into the print iframe */
|
|
12
|
+
clonedContentNode: Node;
|
|
13
|
+
/** Cloned image nodes. Used for pre-loading */
|
|
14
|
+
clonedImgNodes: never[] | NodeListOf<HTMLImageElement>;
|
|
15
|
+
/** Clones video nodes. User for pre-loading */
|
|
16
|
+
clonedVideoNodes: never[] | NodeListOf<HTMLVideoElement>;
|
|
17
|
+
/** The total number of resources to load. Printing will start once all have been loaded */
|
|
18
|
+
numResourcesToLoad: number;
|
|
19
|
+
/** The original canvas nodes. Used to apply paints not copied when cloning the nodes */
|
|
20
|
+
originalCanvasNodes: never[] | NodeListOf<HTMLCanvasElement>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const DEFAULT_PAGE_STYLE = `
|
|
24
|
+
@page {
|
|
25
|
+
/* Remove browser default header (title) and footer (url) */
|
|
26
|
+
margin: 0;
|
|
27
|
+
}
|
|
28
|
+
@media print {
|
|
29
|
+
body {
|
|
30
|
+
/* Tell browsers to print background colors */
|
|
31
|
+
color-adjust: exact; /* Firefox. This is an older version of "print-color-adjust" */
|
|
32
|
+
print-color-adjust: exact; /* Firefox/Safari */
|
|
33
|
+
-webkit-print-color-adjust: exact; /* Chrome/Safari/Edge/Opera */
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
`;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Handles loading resources into the print window and copying over various DOM elements that
|
|
40
|
+
* require special handling.
|
|
41
|
+
*/
|
|
42
|
+
export function handlePrintWindowOnLoad(
|
|
43
|
+
printWindow: HTMLIFrameElement,
|
|
44
|
+
data: HandlePrintWindowOnLoadData,
|
|
45
|
+
options: UseReactToPrintOptions,
|
|
46
|
+
) {
|
|
47
|
+
const {
|
|
48
|
+
contentNode,
|
|
49
|
+
clonedContentNode,
|
|
50
|
+
clonedImgNodes,
|
|
51
|
+
clonedVideoNodes,
|
|
52
|
+
numResourcesToLoad,
|
|
53
|
+
originalCanvasNodes,
|
|
54
|
+
} = data;
|
|
55
|
+
|
|
56
|
+
const {
|
|
57
|
+
bodyClass,
|
|
58
|
+
fonts,
|
|
59
|
+
ignoreGlobalStyles,
|
|
60
|
+
pageStyle,
|
|
61
|
+
nonce,
|
|
62
|
+
suppressErrors,
|
|
63
|
+
copyShadowRoots,
|
|
64
|
+
} = options;
|
|
65
|
+
|
|
66
|
+
const resourcesLoaded: (Element | Font | FontFace)[] = [];
|
|
67
|
+
const resourcesErrored: (Element | Font | FontFace)[] = [];
|
|
68
|
+
|
|
69
|
+
function markLoaded(resource: Element | Font | FontFace, errorMessages?: unknown[]) {
|
|
70
|
+
if (resourcesLoaded.includes(resource)) {
|
|
71
|
+
logMessages({
|
|
72
|
+
level: 'debug',
|
|
73
|
+
messages: ['Tried to mark a resource that has already been handled', resource],
|
|
74
|
+
suppressErrors,
|
|
75
|
+
});
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (!errorMessages) {
|
|
80
|
+
resourcesLoaded.push(resource);
|
|
81
|
+
} else {
|
|
82
|
+
logMessages({
|
|
83
|
+
messages: [
|
|
84
|
+
'"react-to-print" was unable to load a resource but will continue attempting to print the page',
|
|
85
|
+
...errorMessages,
|
|
86
|
+
],
|
|
87
|
+
suppressErrors,
|
|
88
|
+
});
|
|
89
|
+
resourcesErrored.push(resource);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// We may have errors, but attempt to print anyways - maybe they are trivial and the
|
|
93
|
+
// user will be ok ignoring them
|
|
94
|
+
const numResourcesManaged = resourcesLoaded.length + resourcesErrored.length;
|
|
95
|
+
|
|
96
|
+
if (numResourcesManaged === numResourcesToLoad) {
|
|
97
|
+
startPrint(printWindow, options);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Some agents, such as IE11 and Enzyme (as of 2 Jun 2020) continuously call the
|
|
102
|
+
// `onload` callback. This ensures that it is only called once.
|
|
103
|
+
printWindow.onload = null;
|
|
104
|
+
|
|
105
|
+
const domDoc = printWindow.contentDocument ?? printWindow.contentWindow?.document;
|
|
106
|
+
|
|
107
|
+
if (domDoc) {
|
|
108
|
+
const appendedContentNode = domDoc.body.appendChild(clonedContentNode);
|
|
109
|
+
if (copyShadowRoots) {
|
|
110
|
+
cloneShadowRoots(contentNode, appendedContentNode, !!suppressErrors);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (fonts) {
|
|
114
|
+
if (printWindow.contentDocument?.fonts && printWindow.contentWindow?.FontFace) {
|
|
115
|
+
fonts.forEach((font) => {
|
|
116
|
+
const fontFace = new FontFace(font.family, font.source, {
|
|
117
|
+
weight: font.weight,
|
|
118
|
+
style: font.style,
|
|
119
|
+
});
|
|
120
|
+
printWindow.contentDocument!.fonts.add(fontFace);
|
|
121
|
+
fontFace.loaded
|
|
122
|
+
.then(() => {
|
|
123
|
+
markLoaded(fontFace);
|
|
124
|
+
})
|
|
125
|
+
.catch((error: unknown) => {
|
|
126
|
+
markLoaded(fontFace, [
|
|
127
|
+
'Failed loading the font:',
|
|
128
|
+
fontFace,
|
|
129
|
+
'Load error:',
|
|
130
|
+
getErrorFromUnknown(error),
|
|
131
|
+
]);
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
} else {
|
|
135
|
+
// Pretend we loaded the fonts to allow printing to continue
|
|
136
|
+
fonts.forEach((font) => {
|
|
137
|
+
markLoaded(font);
|
|
138
|
+
});
|
|
139
|
+
logMessages({
|
|
140
|
+
messages: [
|
|
141
|
+
'"react-to-print" is not able to load custom fonts because the browser does not support the FontFace API but will continue attempting to print the page',
|
|
142
|
+
],
|
|
143
|
+
suppressErrors,
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const pageStyleToUse = pageStyle ?? DEFAULT_PAGE_STYLE;
|
|
149
|
+
const styleEl = domDoc.createElement('style');
|
|
150
|
+
|
|
151
|
+
if (nonce) {
|
|
152
|
+
styleEl.setAttribute('nonce', nonce);
|
|
153
|
+
domDoc.head.setAttribute('nonce', nonce);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
styleEl.appendChild(domDoc.createTextNode(pageStyleToUse));
|
|
157
|
+
domDoc.head.appendChild(styleEl);
|
|
158
|
+
|
|
159
|
+
if (bodyClass) {
|
|
160
|
+
domDoc.body.classList.add(...bodyClass.split(' '));
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// Copy canvases
|
|
164
|
+
const targetCanvasEls = domDoc.querySelectorAll('canvas');
|
|
165
|
+
for (let i = 0; i < originalCanvasNodes.length; ++i) {
|
|
166
|
+
// NOTE: must use original data here as the canvass elements in `clonedContentNode` will
|
|
167
|
+
// not have had their painted images copied properly. This is specifically mentioned in
|
|
168
|
+
// the [`cloneNode` docs](https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode).
|
|
169
|
+
const sourceCanvas = originalCanvasNodes[i];
|
|
170
|
+
const targetCanvas = targetCanvasEls[i];
|
|
171
|
+
|
|
172
|
+
// The conditional here is necessary; there is no guarantee that the index exists
|
|
173
|
+
// Resolve this by changing to `.at` once we up browser requirements
|
|
174
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
|
175
|
+
if (targetCanvas === undefined) {
|
|
176
|
+
logMessages({
|
|
177
|
+
messages: [
|
|
178
|
+
'A canvas element could not be copied for printing, has it loaded? `onBeforePrint` likely resolved too early.',
|
|
179
|
+
sourceCanvas,
|
|
180
|
+
],
|
|
181
|
+
suppressErrors,
|
|
182
|
+
});
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const targetCanvasContext = targetCanvas.getContext('2d');
|
|
187
|
+
|
|
188
|
+
if (targetCanvasContext) {
|
|
189
|
+
targetCanvasContext.drawImage(sourceCanvas, 0, 0);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Pre-load images
|
|
194
|
+
for (let i = 0; i < clonedImgNodes.length; i++) {
|
|
195
|
+
const imgNode = clonedImgNodes[i];
|
|
196
|
+
const imgSrc = imgNode.getAttribute('src');
|
|
197
|
+
|
|
198
|
+
if (!imgSrc) {
|
|
199
|
+
markLoaded(imgNode, [
|
|
200
|
+
'Found an <img> tag with an empty "src" attribute. This prevents pre-loading it.',
|
|
201
|
+
imgNode,
|
|
202
|
+
]);
|
|
203
|
+
} else {
|
|
204
|
+
// https://stackoverflow.com/questions/10240110/how-do-you-cache-an-image-in-javascript
|
|
205
|
+
const img = new Image();
|
|
206
|
+
img.onload = () => {
|
|
207
|
+
markLoaded(imgNode);
|
|
208
|
+
};
|
|
209
|
+
img.onerror = (_event, _source, _lineno, _colno, error) => {
|
|
210
|
+
markLoaded(imgNode, ['Error loading <img>', imgNode, 'Error', error]);
|
|
211
|
+
};
|
|
212
|
+
img.src = imgSrc;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// Pre-load videos
|
|
217
|
+
for (let i = 0; i < clonedVideoNodes.length; i++) {
|
|
218
|
+
const videoNode = clonedVideoNodes[i];
|
|
219
|
+
videoNode.preload = 'auto'; // Hint to the browser that it should load this resource
|
|
220
|
+
|
|
221
|
+
const videoPoster = videoNode.getAttribute('poster');
|
|
222
|
+
if (videoPoster) {
|
|
223
|
+
// If the video has a poster, pre-load the poster image
|
|
224
|
+
// https://stackoverflow.com/questions/10240110/how-do-you-cache-an-image-in-javascript
|
|
225
|
+
const img = new Image();
|
|
226
|
+
img.onload = () => {
|
|
227
|
+
markLoaded(videoNode);
|
|
228
|
+
};
|
|
229
|
+
img.onerror = (_event, _source, _lineno, _colno, error) => {
|
|
230
|
+
markLoaded(videoNode, [
|
|
231
|
+
'Error loading video poster',
|
|
232
|
+
videoPoster,
|
|
233
|
+
'for video',
|
|
234
|
+
videoNode,
|
|
235
|
+
'Error:',
|
|
236
|
+
error,
|
|
237
|
+
]);
|
|
238
|
+
};
|
|
239
|
+
img.src = videoPoster;
|
|
240
|
+
} else {
|
|
241
|
+
if (videoNode.readyState >= 2) {
|
|
242
|
+
// Check if the video has already loaded a frame
|
|
243
|
+
markLoaded(videoNode);
|
|
244
|
+
} else if (!videoNode.src) {
|
|
245
|
+
// There are scenarios where `src` can be empty, for example with lazy loading.
|
|
246
|
+
markLoaded(videoNode, ['Error loading video, `src` is empty', videoNode]);
|
|
247
|
+
} else {
|
|
248
|
+
videoNode.onloadeddata = () => {
|
|
249
|
+
markLoaded(videoNode);
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
// TODO: why do `onabort` and `onstalled` seem to fire all the time even if there is no issue?
|
|
253
|
+
// videoNode.onabort = () => markLoaded(videoNode, ["Loading video aborted", videoNode], suppressErrors);
|
|
254
|
+
videoNode.onerror = (_event, _source, _lineno, _colno, error) => {
|
|
255
|
+
markLoaded(videoNode, ['Error loading video', videoNode, 'Error', error]);
|
|
256
|
+
};
|
|
257
|
+
// videoNode.onemptied = () => markLoaded(videoNode, ["Loading video emptied, skipping", videoNode]);
|
|
258
|
+
videoNode.onstalled = () => {
|
|
259
|
+
markLoaded(videoNode, ['Loading video stalled, skipping', videoNode]);
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// Copy select states. Without this, the first select option is printed, regardless of
|
|
266
|
+
// selection state
|
|
267
|
+
const selectSelector = 'select';
|
|
268
|
+
const originalSelects = (contentNode as Element).querySelectorAll(selectSelector);
|
|
269
|
+
const copiedSelects = domDoc.querySelectorAll(selectSelector);
|
|
270
|
+
for (let i = 0; i < originalSelects.length; i++) {
|
|
271
|
+
copiedSelects[i].value = originalSelects[i].value;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
if (!ignoreGlobalStyles) {
|
|
275
|
+
const styleAndLinkNodes = document.querySelectorAll(
|
|
276
|
+
"style, link[rel~='stylesheet'], link[as='style']",
|
|
277
|
+
);
|
|
278
|
+
|
|
279
|
+
for (
|
|
280
|
+
let i = 0, styleAndLinkNodesLen = styleAndLinkNodes.length;
|
|
281
|
+
i < styleAndLinkNodesLen;
|
|
282
|
+
++i
|
|
283
|
+
) {
|
|
284
|
+
const node = styleAndLinkNodes[i];
|
|
285
|
+
|
|
286
|
+
if (node.tagName.toLowerCase() === 'style') {
|
|
287
|
+
// <style> nodes
|
|
288
|
+
const newHeadEl = domDoc.createElement(node.tagName);
|
|
289
|
+
const sheet = (node as HTMLStyleElement).sheet;
|
|
290
|
+
if (sheet) {
|
|
291
|
+
let styleCSS = '';
|
|
292
|
+
// NOTE: for-of is not supported by IE
|
|
293
|
+
try {
|
|
294
|
+
// Accessing `sheet.cssRules` on cross-origin sheets can throw
|
|
295
|
+
// security exceptions in some browsers, notably Firefox
|
|
296
|
+
// https://github.com/MatthewHerbst/react-to-print/issues/429
|
|
297
|
+
const cssLength = sheet.cssRules.length;
|
|
298
|
+
for (let j = 0; j < cssLength; ++j) {
|
|
299
|
+
if (typeof sheet.cssRules[j].cssText === 'string') {
|
|
300
|
+
styleCSS += `${sheet.cssRules[j].cssText}\r\n`;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
} catch (error: unknown) {
|
|
304
|
+
logMessages({
|
|
305
|
+
messages: [
|
|
306
|
+
`A stylesheet could not be accessed. This is likely due to the stylesheet having cross-origin imports, and many browsers block script access to cross-origin stylesheets. See https://github.com/MatthewHerbst/react-to-print/issues/429 for details. You may be able to load the sheet by both marking the stylesheet with the cross \`crossorigin\` attribute, and setting the \`Access-Control-Allow-Origin\` header on the server serving the stylesheet. Alternatively, host the stylesheet on your domain to avoid this issue entirely.`, // eslint-disable-line max-len
|
|
307
|
+
node,
|
|
308
|
+
`Original error: ${getErrorFromUnknown(error).message}`,
|
|
309
|
+
],
|
|
310
|
+
level: 'warning',
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
newHeadEl.setAttribute('id', `react-to-print-${i}`);
|
|
315
|
+
if (nonce) {
|
|
316
|
+
newHeadEl.setAttribute('nonce', nonce);
|
|
317
|
+
}
|
|
318
|
+
newHeadEl.appendChild(domDoc.createTextNode(styleCSS));
|
|
319
|
+
domDoc.head.appendChild(newHeadEl);
|
|
320
|
+
}
|
|
321
|
+
} else {
|
|
322
|
+
// <link> nodes, and any others
|
|
323
|
+
// Many browsers will do all sorts of weird things if they encounter an
|
|
324
|
+
// empty `href` tag (which is invalid HTML). Some will attempt to load
|
|
325
|
+
// the current page. Some will attempt to load the page"s parent
|
|
326
|
+
// directory. These problems can cause `react-to-print` to stop without
|
|
327
|
+
// any error being thrown. To avoid such problems we simply do not
|
|
328
|
+
// attempt to load these links.
|
|
329
|
+
if (node.getAttribute('href')) {
|
|
330
|
+
// Browser's don't display `disabled` `link` nodes, so we need to filter them out
|
|
331
|
+
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-disabled
|
|
332
|
+
// https://caniuse.com/mdn-html_elements_link_disabled
|
|
333
|
+
// TODO: ideally we could just filter these out on selection using
|
|
334
|
+
// a selector such as: `link[rel='stylesheet']:not([disabled])`
|
|
335
|
+
// https://stackoverflow.com/questions/27733826/css-selectors-for-excluding-by-attribute-presence
|
|
336
|
+
// However, that doesn't seem to work. Why?
|
|
337
|
+
if (!node.hasAttribute('disabled')) {
|
|
338
|
+
const newHeadEl = domDoc.createElement(node.tagName);
|
|
339
|
+
|
|
340
|
+
// Manually re-create the node
|
|
341
|
+
// TODO: document why cloning the node won't work? I don't recall
|
|
342
|
+
// the reasoning behind why we do it this way
|
|
343
|
+
// NOTE: node.attributes has NamedNodeMap type that is not an Array
|
|
344
|
+
// and can be iterated only via direct [i] access
|
|
345
|
+
for (let j = 0, attrLen = node.attributes.length; j < attrLen; ++j) {
|
|
346
|
+
const attr = node.attributes[j];
|
|
347
|
+
// The conditional here is necessary; there is no guarantee that the index exists
|
|
348
|
+
// Resolve this by changing to `.at` once we up browser requirements
|
|
349
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
|
350
|
+
if (attr) {
|
|
351
|
+
newHeadEl.setAttribute(attr.nodeName, attr.nodeValue ?? '');
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
newHeadEl.onload = () => {
|
|
356
|
+
markLoaded(newHeadEl);
|
|
357
|
+
};
|
|
358
|
+
newHeadEl.onerror = (_event, _source, _lineno, _colno, error) => {
|
|
359
|
+
markLoaded(newHeadEl, ['Failed to load', newHeadEl, 'Error:', error]);
|
|
360
|
+
};
|
|
361
|
+
if (nonce) {
|
|
362
|
+
newHeadEl.setAttribute('nonce', nonce);
|
|
363
|
+
}
|
|
364
|
+
domDoc.head.appendChild(newHeadEl);
|
|
365
|
+
} else {
|
|
366
|
+
logMessages({
|
|
367
|
+
messages: [
|
|
368
|
+
'`react-to-print` encountered a <link> tag with a `disabled` attribute and will ignore it. Note that the `disabled` attribute is deprecated, and some browsers ignore it. You should stop using it. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-disabled. The <link> is:',
|
|
369
|
+
node,
|
|
370
|
+
],
|
|
371
|
+
level: 'warning',
|
|
372
|
+
});
|
|
373
|
+
// `true` because this isn't an error: we are intentionally skipping this node
|
|
374
|
+
markLoaded(node);
|
|
375
|
+
}
|
|
376
|
+
} else {
|
|
377
|
+
logMessages({
|
|
378
|
+
messages: [
|
|
379
|
+
'`react-to-print` encountered a <link> tag with an empty `href` attribute. In addition to being invalid HTML, this can cause problems in many browsers, and so the <link> was not loaded. The <link> is:',
|
|
380
|
+
node,
|
|
381
|
+
],
|
|
382
|
+
level: 'warning',
|
|
383
|
+
});
|
|
384
|
+
// `true` because we"ve already shown a warning for this
|
|
385
|
+
markLoaded(node);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// Handle the base case where there are no resources to load
|
|
393
|
+
if (numResourcesToLoad === 0) {
|
|
394
|
+
startPrint(printWindow, options);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
interface LogMessagesArgs {
|
|
2
|
+
/** The console method to use when logging the messages. Default: 'error' */
|
|
3
|
+
level?: 'error' | 'warning' | 'debug';
|
|
4
|
+
/** The messages to log */
|
|
5
|
+
messages: unknown[];
|
|
6
|
+
/** When `true` prevents all logging */
|
|
7
|
+
suppressErrors?: boolean;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Logs messages to the console. Uses `console.error` by default. */
|
|
11
|
+
export function logMessages({
|
|
12
|
+
level = 'error',
|
|
13
|
+
messages,
|
|
14
|
+
suppressErrors = false,
|
|
15
|
+
}: LogMessagesArgs) {
|
|
16
|
+
if (!suppressErrors) {
|
|
17
|
+
if (level === 'error') {
|
|
18
|
+
console.error(messages);
|
|
19
|
+
} else if (level === 'warning') {
|
|
20
|
+
console.warn(messages);
|
|
21
|
+
} else {
|
|
22
|
+
console.debug(messages);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { DEFAULT_PRINT_WINDOW_ID } from '../consts';
|
|
2
|
+
import type { UseReactToPrintOptions } from '../types/UseReactToPrintOptions';
|
|
3
|
+
|
|
4
|
+
export function removePrintIframe(
|
|
5
|
+
preserveAfterPrint: UseReactToPrintOptions['preserveAfterPrint'],
|
|
6
|
+
force?: boolean,
|
|
7
|
+
) {
|
|
8
|
+
if (force || !preserveAfterPrint) {
|
|
9
|
+
const documentPrintWindow = document.getElementById(DEFAULT_PRINT_WINDOW_ID);
|
|
10
|
+
|
|
11
|
+
if (documentPrintWindow) {
|
|
12
|
+
document.body.removeChild(documentPrintWindow);
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { logMessages } from './logMessage';
|
|
2
|
+
import { removePrintIframe } from './removePrintIframe';
|
|
3
|
+
import type { UseReactToPrintOptions } from '../types/UseReactToPrintOptions';
|
|
4
|
+
import { getErrorFromUnknown } from './getErrorMessage';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Starts the main printing process. This includes determining if we are running the default
|
|
8
|
+
* printing process or using a custom `print` function, handling updating the print windows's title
|
|
9
|
+
* if a `documentTitle` is set, calling `onAfterPrint`, and removing the print iframe based on the
|
|
10
|
+
* value of `preserveAfterPrint`.
|
|
11
|
+
*/
|
|
12
|
+
export function startPrint(printWindow: HTMLIFrameElement, options: UseReactToPrintOptions) {
|
|
13
|
+
const { documentTitle, onAfterPrint, onPrintError, preserveAfterPrint, print, suppressErrors } =
|
|
14
|
+
options;
|
|
15
|
+
|
|
16
|
+
// Some browsers such as Safari don't always behave well without this timeout
|
|
17
|
+
setTimeout(() => {
|
|
18
|
+
if (printWindow.contentWindow) {
|
|
19
|
+
printWindow.contentWindow.focus(); // Needed for IE 11
|
|
20
|
+
|
|
21
|
+
function handleAfterPrint() {
|
|
22
|
+
onAfterPrint?.();
|
|
23
|
+
removePrintIframe(preserveAfterPrint);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
if (print) {
|
|
27
|
+
print(printWindow)
|
|
28
|
+
.then(handleAfterPrint)
|
|
29
|
+
.catch((error: unknown) => {
|
|
30
|
+
if (onPrintError) {
|
|
31
|
+
onPrintError('print', getErrorFromUnknown(error));
|
|
32
|
+
} else {
|
|
33
|
+
logMessages({
|
|
34
|
+
messages: ['An error was thrown by the specified `print` function'],
|
|
35
|
+
suppressErrors,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
} else {
|
|
40
|
+
// Some browsers do not have a `.print` available, even though they should
|
|
41
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
|
42
|
+
if (printWindow.contentWindow.print) {
|
|
43
|
+
const tempContentDocumentTitle = printWindow.contentDocument?.title ?? '';
|
|
44
|
+
const tempOwnerDocumentTitle = printWindow.ownerDocument.title;
|
|
45
|
+
|
|
46
|
+
const resolvedTitle =
|
|
47
|
+
typeof documentTitle === 'function' ? documentTitle() : documentTitle;
|
|
48
|
+
|
|
49
|
+
// Override page and various target content titles during print
|
|
50
|
+
// NOTE: some browsers seem to take the print title from the highest level
|
|
51
|
+
// title, while others take it from the lowest level title. So, we set the title
|
|
52
|
+
// in a few places and hope the current browser takes one of them :pray:
|
|
53
|
+
if (resolvedTitle) {
|
|
54
|
+
// Print filename in Chrome
|
|
55
|
+
printWindow.ownerDocument.title = resolvedTitle;
|
|
56
|
+
|
|
57
|
+
// Print filename in Firefox, Safari
|
|
58
|
+
if (printWindow.contentDocument) {
|
|
59
|
+
printWindow.contentDocument.title = resolvedTitle;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
printWindow.contentWindow.print();
|
|
64
|
+
|
|
65
|
+
// Restore the page's original title information
|
|
66
|
+
if (resolvedTitle) {
|
|
67
|
+
printWindow.ownerDocument.title = tempOwnerDocumentTitle;
|
|
68
|
+
|
|
69
|
+
if (printWindow.contentDocument) {
|
|
70
|
+
printWindow.contentDocument.title = tempContentDocumentTitle;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
} else {
|
|
74
|
+
// Some browsers, such as Firefox Android, do not support printing at all
|
|
75
|
+
// https://developer.mozilla.org/en-US/docs/Web/API/Window/print
|
|
76
|
+
logMessages({
|
|
77
|
+
messages: [
|
|
78
|
+
'Printing for this browser is not currently possible: the browser does not have a `print` method available for iframes.',
|
|
79
|
+
],
|
|
80
|
+
suppressErrors,
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* This workaround is implemented to prevent a bug on mobile browsers where `handleAfterPrint`
|
|
86
|
+
* is called immediately, even before the print dialog opens. This issue is described in #187.
|
|
87
|
+
*
|
|
88
|
+
* On mobile devices, a delay is introduced using `setTimeout` to ensure the dialog has time to open.
|
|
89
|
+
*
|
|
90
|
+
* @see [Stack Overflow Reference](https://stackoverflow.com/q/77215077/4899926)
|
|
91
|
+
*/
|
|
92
|
+
if (isMobileBrowser()) {
|
|
93
|
+
setTimeout(handleAfterPrint, 500);
|
|
94
|
+
} else {
|
|
95
|
+
handleAfterPrint();
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
} else {
|
|
99
|
+
logMessages({
|
|
100
|
+
messages: [
|
|
101
|
+
'Printing failed because the `contentWindow` of the print iframe did not load. This is possibly an error with `react-to-print`. Please file an issue: https://github.com/MatthewHerbst/react-to-print/issues/',
|
|
102
|
+
],
|
|
103
|
+
suppressErrors,
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
}, 500);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Determines if the current browser is a mobile browser by checking the `navigator.userAgent`
|
|
111
|
+
* against a predefined list of common mobile browser identifiers.
|
|
112
|
+
*
|
|
113
|
+
* Note: This function is not exhaustive and may not detect all mobile browsers,
|
|
114
|
+
* as it is designed to remain simple and lightweight.
|
|
115
|
+
*
|
|
116
|
+
* @see [Stack Overflow Reference](https://stackoverflow.com/a/11381730/4899926)
|
|
117
|
+
*/
|
|
118
|
+
function isMobileBrowser() {
|
|
119
|
+
const toMatch = [
|
|
120
|
+
/Android/i,
|
|
121
|
+
/webOS/i,
|
|
122
|
+
/iPhone/i,
|
|
123
|
+
/iPad/i,
|
|
124
|
+
/iPod/i,
|
|
125
|
+
/BlackBerry/i,
|
|
126
|
+
/Windows Phone/i,
|
|
127
|
+
];
|
|
128
|
+
|
|
129
|
+
return toMatch.some((toMatchItem) => {
|
|
130
|
+
return (
|
|
131
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
|
132
|
+
(
|
|
133
|
+
navigator.userAgent ??
|
|
134
|
+
// Retained for compatibility with browsers that use `navigator.vendor` to identify the browser.
|
|
135
|
+
// eslint-disable-next-line @typescript-eslint/no-deprecated
|
|
136
|
+
navigator.vendor ??
|
|
137
|
+
// Retained for compatibility with older versions of Opera that use `window.opera`.
|
|
138
|
+
('opera' in window && window.opera)
|
|
139
|
+
).match(toMatchItem)
|
|
140
|
+
);
|
|
141
|
+
});
|
|
142
|
+
}
|