@marcusumn/html2pdf.js 0.1.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/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "@marcusumn/html2pdf.js",
3
+ "version": "0.1.0",
4
+ "description": "Maintained fork of html2pdf.js - client-side HTML-to-PDF rendering using pure JS",
5
+ "main": "dist/html2pdf.js",
6
+ "types": "./type.d.ts",
7
+ "files": [
8
+ "/src",
9
+ "/dist",
10
+ "./type.d.ts"
11
+ ],
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/MarcusUMN/html2pdf.js.git"
15
+ },
16
+ "keywords": [
17
+ "javascript",
18
+ "pdf-generation",
19
+ "html",
20
+ "client-side",
21
+ "canvas"
22
+ ],
23
+ "author": {
24
+ "name": "Erik Koopmans",
25
+ "email": "erik@erik-koopmans.com",
26
+ "url": "https://www.erik-koopmans.com"
27
+ },
28
+ "license": "MIT",
29
+ "bugs": {
30
+ "url": "https://github.com/MarcusUMN/html2pdf.js/issues"
31
+ },
32
+ "homepage": "https://marcusumn.github.io/html2pdf.js/",
33
+ "dependencies": {
34
+ "html2canvas": "^1.0.0",
35
+ "jspdf": "^4.0.0"
36
+ },
37
+ "devDependencies": {
38
+ "@babel/core": "^7.14.8",
39
+ "@babel/preset-env": "^7.14.8",
40
+ "@brightspace-ui/core": "^3.156.4",
41
+ "@brightspace-ui/testing": "^1.31.2",
42
+ "@web/dev-server": "^0.4.6",
43
+ "babel-loader": "^10.0.0",
44
+ "core-js": "^3.16.0",
45
+ "lit": "^3.3.1",
46
+ "pdfjs-dist": "^5.3.93",
47
+ "rimraf": "^6.0.1",
48
+ "sinon": "^21.0.0",
49
+ "webpack": "^5.101.0",
50
+ "webpack-bundle-analyzer": "^4.4.2",
51
+ "webpack-cli": "^6.0.1"
52
+ },
53
+ "scripts": {
54
+ "build": "npm run clean && webpack --env=prod",
55
+ "build:analyze": "npm run clean && webpack --env=prod --env=analyzer",
56
+ "clean": "rimraf dist",
57
+ "dev": "webpack --env=dev",
58
+ "dev:analyze": "webpack --env=dev --env=analyzer",
59
+ "start": "web-dev-server --open demo/ --node-resolve --watch",
60
+ "test": "npm run test:unit && npm run test:vdiff",
61
+ "test:unit": "d2l-test-runner --chrome",
62
+ "test:vdiff": "d2l-test-runner vdiff",
63
+ "test:vdiff:golden": "d2l-test-runner vdiff golden"
64
+ }
65
+ }
package/src/index.js ADDED
@@ -0,0 +1,29 @@
1
+ import Worker from './worker.js';
2
+ import './plugin/jspdf-plugin.js';
3
+ import './plugin/pagebreaks.js';
4
+ import './plugin/hyperlinks.js';
5
+
6
+ /**
7
+ * Generate a PDF from an HTML element or string using html2canvas and jsPDF.
8
+ *
9
+ * @param {Element|string} source The source element or HTML string.
10
+ * @param {Object=} opt An object of optional settings: 'margin', 'filename',
11
+ * 'image' ('type' and 'quality'), and 'html2canvas' / 'jspdf', which are
12
+ * sent as settings to their corresponding functions.
13
+ */
14
+ var html2pdf = function html2pdf(src, opt) {
15
+ // Create a new worker with the given options.
16
+ var worker = new html2pdf.Worker(opt);
17
+
18
+ if (src) {
19
+ // If src is specified, perform the traditional 'simple' operation.
20
+ return worker.from(src).save();
21
+ } else {
22
+ // Otherwise, return the worker for new Promise-based operation.
23
+ return worker;
24
+ }
25
+ }
26
+ html2pdf.Worker = Worker;
27
+
28
+ // Expose the html2pdf function.
29
+ export default html2pdf;
@@ -0,0 +1,59 @@
1
+ import Worker from '../worker.js';
2
+ import { unitConvert } from '../utils.js';
3
+
4
+ // Add hyperlink functionality to the PDF creation.
5
+
6
+ // Main link array, and refs to original functions.
7
+ var linkInfo = [];
8
+ var orig = {
9
+ toContainer: Worker.prototype.toContainer,
10
+ toPdf: Worker.prototype.toPdf,
11
+ };
12
+
13
+ Worker.prototype.toContainer = function toContainer() {
14
+ return orig.toContainer.call(this).then(function toContainer_hyperlink() {
15
+ // Retrieve hyperlink info if the option is enabled.
16
+ if (this.opt.enableLinks) {
17
+ // Find all anchor tags and get the container's bounds for reference.
18
+ var container = this.prop.container;
19
+ var links = container.querySelectorAll('a');
20
+ var containerRect = unitConvert(container.getBoundingClientRect(), this.prop.pageSize.k);
21
+ linkInfo = [];
22
+
23
+ // Loop through each anchor tag.
24
+ Array.prototype.forEach.call(links, function(link) {
25
+ // Treat each client rect as a separate link (for text-wrapping).
26
+ var clientRects = link.getClientRects();
27
+ for (var i=0; i<clientRects.length; i++) {
28
+ var clientRect = unitConvert(clientRects[i], this.prop.pageSize.k);
29
+ clientRect.left -= containerRect.left;
30
+ clientRect.top -= containerRect.top;
31
+
32
+ var page = Math.floor(clientRect.top / this.prop.pageSize.inner.height) + 1;
33
+ var top = this.opt.margin[0] + clientRect.top % this.prop.pageSize.inner.height;
34
+ var left = this.opt.margin[1] + clientRect.left;
35
+
36
+ linkInfo.push({ page, top, left, clientRect, link });
37
+ }
38
+ }, this);
39
+ }
40
+ });
41
+ };
42
+
43
+ Worker.prototype.toPdf = function toPdf() {
44
+ return orig.toPdf.call(this).then(function toPdf_hyperlink() {
45
+ // Add hyperlinks if the option is enabled.
46
+ if (this.opt.enableLinks) {
47
+ // Attach each anchor tag based on info from toContainer().
48
+ linkInfo.forEach(function(l) {
49
+ this.prop.pdf.setPage(l.page);
50
+ this.prop.pdf.link(l.left, l.top, l.clientRect.width, l.clientRect.height,
51
+ { url: l.link.href });
52
+ }, this);
53
+
54
+ // Reset the active page of the PDF to the final page.
55
+ var nPages = this.prop.pdf.internal.getNumberOfPages();
56
+ this.prop.pdf.setPage(nPages);
57
+ }
58
+ });
59
+ };
@@ -0,0 +1,99 @@
1
+ // Import dependencies.
2
+ import jsPDF from 'jspdf/dist/jspdf.es.min.js';
3
+
4
+ // Get dimensions of a PDF page, as determined by jsPDF.
5
+ jsPDF.getPageSize = function(orientation, unit, format) {
6
+ // Decode options object
7
+ if (typeof orientation === 'object') {
8
+ var options = orientation;
9
+ orientation = options.orientation;
10
+ unit = options.unit || unit;
11
+ format = options.format || format;
12
+ }
13
+
14
+ // Default options
15
+ unit = unit || 'mm';
16
+ format = format || 'a4';
17
+ orientation = ('' + (orientation || 'P')).toLowerCase();
18
+ var format_as_string = ('' + format).toLowerCase();
19
+
20
+ // Size in pt of various paper formats
21
+ var pageFormats = {
22
+ 'a0' : [2383.94, 3370.39], 'a1' : [1683.78, 2383.94],
23
+ 'a2' : [1190.55, 1683.78], 'a3' : [ 841.89, 1190.55],
24
+ 'a4' : [ 595.28, 841.89], 'a5' : [ 419.53, 595.28],
25
+ 'a6' : [ 297.64, 419.53], 'a7' : [ 209.76, 297.64],
26
+ 'a8' : [ 147.40, 209.76], 'a9' : [ 104.88, 147.40],
27
+ 'a10' : [ 73.70, 104.88], 'b0' : [2834.65, 4008.19],
28
+ 'b1' : [2004.09, 2834.65], 'b2' : [1417.32, 2004.09],
29
+ 'b3' : [1000.63, 1417.32], 'b4' : [ 708.66, 1000.63],
30
+ 'b5' : [ 498.90, 708.66], 'b6' : [ 354.33, 498.90],
31
+ 'b7' : [ 249.45, 354.33], 'b8' : [ 175.75, 249.45],
32
+ 'b9' : [ 124.72, 175.75], 'b10' : [ 87.87, 124.72],
33
+ 'c0' : [2599.37, 3676.54], 'c1' : [1836.85, 2599.37],
34
+ 'c2' : [1298.27, 1836.85], 'c3' : [ 918.43, 1298.27],
35
+ 'c4' : [ 649.13, 918.43], 'c5' : [ 459.21, 649.13],
36
+ 'c6' : [ 323.15, 459.21], 'c7' : [ 229.61, 323.15],
37
+ 'c8' : [ 161.57, 229.61], 'c9' : [ 113.39, 161.57],
38
+ 'c10' : [ 79.37, 113.39], 'dl' : [ 311.81, 623.62],
39
+ 'letter' : [612, 792],
40
+ 'government-letter' : [576, 756],
41
+ 'legal' : [612, 1008],
42
+ 'junior-legal' : [576, 360],
43
+ 'ledger' : [1224, 792],
44
+ 'tabloid' : [792, 1224],
45
+ 'credit-card' : [153, 243]
46
+ };
47
+
48
+ // Unit conversion
49
+ switch (unit) {
50
+ case 'pt': var k = 1; break;
51
+ case 'mm': var k = 72 / 25.4; break;
52
+ case 'cm': var k = 72 / 2.54; break;
53
+ case 'in': var k = 72; break;
54
+ case 'px': var k = 72 / 96; break;
55
+ case 'pc': var k = 12; break;
56
+ case 'em': var k = 12; break;
57
+ case 'ex': var k = 6; break;
58
+ default:
59
+ throw ('Invalid unit: ' + unit);
60
+ }
61
+
62
+ // Dimensions are stored as user units and converted to points on output
63
+ if (pageFormats.hasOwnProperty(format_as_string)) {
64
+ var pageHeight = pageFormats[format_as_string][1] / k;
65
+ var pageWidth = pageFormats[format_as_string][0] / k;
66
+ } else {
67
+ try {
68
+ var pageHeight = format[1];
69
+ var pageWidth = format[0];
70
+ } catch (err) {
71
+ throw new Error('Invalid format: ' + format);
72
+ }
73
+ }
74
+
75
+ // Handle page orientation
76
+ if (orientation === 'p' || orientation === 'portrait') {
77
+ orientation = 'p';
78
+ if (pageWidth > pageHeight) {
79
+ var tmp = pageWidth;
80
+ pageWidth = pageHeight;
81
+ pageHeight = tmp;
82
+ }
83
+ } else if (orientation === 'l' || orientation === 'landscape') {
84
+ orientation = 'l';
85
+ if (pageHeight > pageWidth) {
86
+ var tmp = pageWidth;
87
+ pageWidth = pageHeight;
88
+ pageHeight = tmp;
89
+ }
90
+ } else {
91
+ throw('Invalid orientation: ' + orientation);
92
+ }
93
+
94
+ // Return information (k is the unit conversion ratio from pts)
95
+ var info = { 'width': pageWidth, 'height': pageHeight, 'unit': unit, 'k': k };
96
+ return info;
97
+ };
98
+
99
+ export default jsPDF;
@@ -0,0 +1,134 @@
1
+ import Worker from '../worker.js';
2
+ import { objType, createElement } from '../utils.js';
3
+
4
+ /* Pagebreak plugin:
5
+
6
+ Adds page-break functionality to the html2pdf library. Page-breaks can be
7
+ enabled by CSS styles, set on individual elements using selectors, or
8
+ avoided from breaking inside all elements.
9
+
10
+ Options on the `opt.pagebreak` object:
11
+
12
+ mode: String or array of strings: 'avoid-all', 'css', and/or 'legacy'
13
+ Default: ['css', 'legacy']
14
+
15
+ before: String or array of CSS selectors for which to add page-breaks
16
+ before each element. Can be a specific element with an ID
17
+ ('#myID'), all elements of a type (e.g. 'img'), all of a class
18
+ ('.myClass'), or even '*' to match every element.
19
+
20
+ after: Like 'before', but adds a page-break immediately after the element.
21
+
22
+ avoid: Like 'before', but avoids page-breaks on these elements. You can
23
+ enable this feature on every element using the 'avoid-all' mode.
24
+ */
25
+
26
+ // Refs to original functions.
27
+ var orig = {
28
+ toContainer: Worker.prototype.toContainer
29
+ };
30
+
31
+ // Add pagebreak default options to the Worker template.
32
+ Worker.template.opt.pagebreak = {
33
+ mode: ['css', 'legacy'],
34
+ before: [],
35
+ after: [],
36
+ avoid: []
37
+ };
38
+
39
+ Worker.prototype.toContainer = function toContainer() {
40
+ return orig.toContainer.call(this).then(function toContainer_pagebreak() {
41
+ // Setup root element and inner page height.
42
+ var root = this.prop.container;
43
+ var pxPageHeight = this.prop.pageSize.inner.px.height;
44
+
45
+ // Check all requested modes.
46
+ var modeSrc = [].concat(this.opt.pagebreak.mode);
47
+ var mode = {
48
+ avoidAll: modeSrc.indexOf('avoid-all') !== -1,
49
+ css: modeSrc.indexOf('css') !== -1,
50
+ legacy: modeSrc.indexOf('legacy') !== -1
51
+ };
52
+
53
+ // Get arrays of all explicitly requested elements.
54
+ var select = {};
55
+ var self = this;
56
+ ['before', 'after', 'avoid'].forEach(function(key) {
57
+ var all = mode.avoidAll && key === 'avoid';
58
+ select[key] = all ? [] : [].concat(self.opt.pagebreak[key] || []);
59
+ if (select[key].length > 0) {
60
+ select[key] = Array.prototype.slice.call(
61
+ root.querySelectorAll(select[key].join(', ')));
62
+ }
63
+ });
64
+
65
+ // Get all legacy page-break elements.
66
+ var legacyEls = root.querySelectorAll('.html2pdf__page-break');
67
+ legacyEls = Array.prototype.slice.call(legacyEls);
68
+
69
+ // Loop through all elements.
70
+ var els = root.querySelectorAll('*');
71
+ Array.prototype.forEach.call(els, function pagebreak_loop(el) {
72
+ // Setup pagebreak rules based on legacy and avoidAll modes.
73
+ var rules = {
74
+ before: false,
75
+ after: mode.legacy && legacyEls.indexOf(el) !== -1,
76
+ avoid: mode.avoidAll
77
+ };
78
+
79
+ // Add rules for css mode.
80
+ if (mode.css) {
81
+ // TODO: Check if this is valid with iFrames.
82
+ var style = window.getComputedStyle(el);
83
+ // TODO: Handle 'left' and 'right' correctly.
84
+ // TODO: Add support for 'avoid' on breakBefore/After.
85
+ var breakOpt = ['always', 'page', 'left', 'right'];
86
+ var avoidOpt = ['avoid', 'avoid-page'];
87
+ rules = {
88
+ before: rules.before || breakOpt.indexOf(style.breakBefore || style.pageBreakBefore) !== -1,
89
+ after: rules.after || breakOpt.indexOf(style.breakAfter || style.pageBreakAfter) !== -1,
90
+ avoid: rules.avoid || avoidOpt.indexOf(style.breakInside || style.pageBreakInside) !== -1
91
+ };
92
+ }
93
+
94
+ // Add rules for explicit requests.
95
+ Object.keys(rules).forEach(function(key) {
96
+ rules[key] = rules[key] || select[key].indexOf(el) !== -1;
97
+ });
98
+
99
+ // Get element position on the screen.
100
+ // TODO: Subtract the top of the container from clientRect.top/bottom?
101
+ var clientRect = el.getBoundingClientRect();
102
+
103
+ // Avoid: Check if a break happens mid-element.
104
+ if (rules.avoid && !rules.before) {
105
+ var startPage = Math.floor(clientRect.top / pxPageHeight);
106
+ var endPage = Math.floor(clientRect.bottom / pxPageHeight);
107
+ var nPages = Math.abs(clientRect.bottom - clientRect.top) / pxPageHeight;
108
+
109
+ // Turn on rules.before if the el is broken and is at most one page long.
110
+ if (endPage !== startPage && nPages <= 1) {
111
+ rules.before = true;
112
+ }
113
+ }
114
+
115
+ // Before: Create a padding div to push the element to the next page.
116
+ if (rules.before) {
117
+ var pad = createElement('div', {style: {
118
+ display: 'block',
119
+ height: pxPageHeight - (clientRect.top % pxPageHeight) + 'px'
120
+ }});
121
+ el.parentNode.insertBefore(pad, el);
122
+ }
123
+
124
+ // After: Create a padding div to fill the remaining page.
125
+ if (rules.after) {
126
+ var pad = createElement('div', {style: {
127
+ display: 'block',
128
+ height: pxPageHeight - (clientRect.bottom % pxPageHeight) + 'px'
129
+ }});
130
+ el.parentNode.insertBefore(pad, el.nextSibling);
131
+ }
132
+ });
133
+ });
134
+ };
@@ -0,0 +1,212 @@
1
+ // https://github.com/zumerlab/snapdom
2
+ //
3
+ // MIT License
4
+ //
5
+ // Copyright (c) 2025 ZumerLab
6
+ //
7
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ // of this software and associated documentation files (the "Software"), to deal
9
+ // in the Software without restriction, including without limitation the rights
10
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ // copies of the Software, and to permit persons to whom the Software is
12
+ // furnished to do so, subject to the following conditions:
13
+ //
14
+ // The above copyright notice and this permission notice shall be included in all
15
+ // copies or substantial portions of the Software.
16
+ //
17
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ // SOFTWARE.
24
+
25
+ /**
26
+ * Deep cloning utilities for DOM elements, including styles and shadow DOM.
27
+ * @module clone
28
+ */
29
+
30
+
31
+ /**
32
+ * Freeze the responsive selection of an <img> that has srcset/sizes.
33
+ * Copies a concrete URL into `src` and removes `srcset`/`sizes` so the clone
34
+ * doesn't need layout to resolve a candidate.
35
+ * Works with <picture> because currentSrc reflects the chosen source.
36
+ * @param {HTMLImageElement} original - Image in the live DOM.
37
+ * @param {HTMLImageElement} cloned - Just-created cloned <img>.
38
+ */
39
+ function freezeImgSrcset(original, cloned) {
40
+ try {
41
+ const chosen = original.currentSrc || original.src || '';
42
+ if (!chosen) return;
43
+ cloned.setAttribute('src', chosen);
44
+ cloned.removeAttribute('srcset');
45
+ cloned.removeAttribute('sizes');
46
+ // Hint deterministic decode/load for capture
47
+ cloned.loading = 'eager';
48
+ cloned.decoding = 'sync';
49
+ } catch {
50
+ // no-op
51
+ }
52
+ }
53
+
54
+
55
+ /**
56
+ * Creates a deep clone of a DOM node, including styles, shadow DOM, and special handling for excluded/placeholder/canvas nodes.
57
+ *
58
+ * @param {Node} node - Node to clone
59
+ * @returns {Node|null} Cloned node with styles and shadow DOM content, or null for empty text nodes or filtered elements
60
+ */
61
+
62
+
63
+ export function deepCloneBasic(node) {
64
+ if (!node) throw new Error('Invalid node');
65
+
66
+ // Local set to avoid duplicates in slot processing
67
+ const clonedAssignedNodes = new Set();
68
+ let pendingSelectValue = null; // Track select value for later fix
69
+
70
+ // 1. Text nodes
71
+ if (node.nodeType === Node.TEXT_NODE) {
72
+ return node.cloneNode(true);
73
+ }
74
+
75
+ // 2. Non-element nodes (comments, etc.)
76
+ if (node.nodeType !== Node.ELEMENT_NODE) {
77
+ return node.cloneNode(true);
78
+ }
79
+
80
+ // 6. Special case: iframe → fallback pattern
81
+ if (node.tagName === "IFRAME") {
82
+ const fallback = document.createElement("div");
83
+ fallback.style.cssText = `width:${node.offsetWidth}px;height:${node.offsetHeight}px;background-image:repeating-linear-gradient(45deg,#ddd,#ddd 5px,#f9f9f9 5px,#f9f9f9 10px);display:flex;align-items:center;justify-content:center;font-size:12px;color:#555;border:1px solid #aaa;`;
84
+ return fallback;
85
+ }
86
+
87
+ // 8. Canvas → convert to image
88
+ if (node.tagName === "CANVAS") {
89
+ const dataURL = node.toDataURL();
90
+ const img = document.createElement("img");
91
+ img.src = dataURL;
92
+ img.width = node.width;
93
+ img.height = node.height;
94
+ return img;
95
+ }
96
+
97
+ // 9. Base clone (without children)
98
+ let clone;
99
+ try {
100
+ clone = node.cloneNode(false);
101
+
102
+ if (node.tagName === 'IMG') {
103
+ freezeImgSrcset(node, clone);
104
+ }
105
+ } catch (err) {
106
+ console.error("[Snapdom] Failed to clone node:", node, err);
107
+ throw err;
108
+ }
109
+
110
+ // Special handling: textarea (keep size and value)
111
+ if (node instanceof HTMLTextAreaElement) {
112
+ clone.textContent = node.value;
113
+ clone.value = node.value;
114
+ const rect = node.getBoundingClientRect();
115
+ clone.style.boxSizing = 'border-box';
116
+ clone.style.width = `${rect.width}px`;
117
+ clone.style.height = `${rect.height}px`;
118
+ return clone;
119
+ }
120
+
121
+ // Special handling: input
122
+ if (node instanceof HTMLInputElement) {
123
+ if (node.hasAttribute("value")) {
124
+ clone.value = node.value;
125
+ clone.setAttribute("value", node.value);
126
+ }
127
+ if (node.checked !== void 0) {
128
+ clone.checked = node.checked;
129
+ if (node.checked) clone.setAttribute("checked", "");
130
+ if (node.indeterminate) clone.indeterminate = node.indeterminate;
131
+ }
132
+ // return clone;
133
+ }
134
+
135
+ // Special handling: select → postpone value adjustment
136
+ if (node instanceof HTMLSelectElement) {
137
+ pendingSelectValue = node.value;
138
+ }
139
+
140
+ // 12. ShadowRoot logic
141
+ if (node.shadowRoot) {
142
+ const hasSlot = Array.from(node.shadowRoot.querySelectorAll("slot")).length > 0;
143
+
144
+ if (hasSlot) {
145
+ } else {
146
+ // ShadowRoot without slots: clone full content
147
+ const shadowFrag = document.createDocumentFragment();
148
+ for (const child of node.shadowRoot.childNodes) {
149
+ if (child.nodeType === Node.ELEMENT_NODE && child.tagName === "STYLE") {
150
+ continue;
151
+ }
152
+ const clonedChild = deepCloneBasic(child);
153
+ if (clonedChild) shadowFrag.appendChild(clonedChild);
154
+ }
155
+ clone.appendChild(shadowFrag);
156
+ }
157
+ }
158
+
159
+ // 13. Slot outside ShadowRoot
160
+ if (node.tagName === "SLOT") {
161
+ const assigned = node.assignedNodes?.({ flatten: true }) || [];
162
+ const nodesToClone = assigned.length > 0 ? assigned : Array.from(node.childNodes);
163
+ const fragment = document.createDocumentFragment();
164
+
165
+ for (const child of nodesToClone) {
166
+ const clonedChild = deepCloneBasic(child);
167
+ if (clonedChild) fragment.appendChild(clonedChild);
168
+ }
169
+ return fragment;
170
+ }
171
+
172
+ // 14. Clone children (light DOM), skipping duplicates
173
+ for (const child of node.childNodes) {
174
+ if (clonedAssignedNodes.has(child)) continue;
175
+
176
+ const clonedChild = deepCloneBasic(child);
177
+ if (clonedChild) clone.appendChild(clonedChild);
178
+ }
179
+
180
+ // Adjust select value after children are cloned
181
+ if (pendingSelectValue !== null && clone instanceof HTMLSelectElement) {
182
+ clone.value = pendingSelectValue;
183
+ for (const opt of clone.options) {
184
+ if (opt.value === pendingSelectValue) {
185
+ opt.setAttribute("selected", "");
186
+ } else {
187
+ opt.removeAttribute("selected");
188
+ }
189
+ }
190
+ }
191
+
192
+ // Fix scrolling (taken from prepareClone).
193
+ const scrollX = node.scrollLeft;
194
+ const scrollY = node.scrollTop;
195
+ const hasScroll = scrollX || scrollY;
196
+ if (hasScroll && clone instanceof HTMLElement) {
197
+ clone.style.overflow = "hidden";
198
+ clone.style.scrollbarWidth = "none";
199
+ clone.style.msOverflowStyle = "none";
200
+ const inner = document.createElement("div");
201
+ inner.style.transform = `translate(${-scrollX}px, ${-scrollY}px)`;
202
+ inner.style.willChange = "transform";
203
+ inner.style.display = "inline-block";
204
+ inner.style.width = "100%";
205
+ while (clone.firstChild) {
206
+ inner.appendChild(clone.firstChild);
207
+ }
208
+ clone.appendChild(inner);
209
+ }
210
+
211
+ return clone;
212
+ }
package/src/utils.js ADDED
@@ -0,0 +1,47 @@
1
+ // Determine the type of a variable/object.
2
+ export const objType = function objType(obj) {
3
+ var type = typeof obj;
4
+ if (type === 'undefined') return 'undefined';
5
+ else if (type === 'string' || obj instanceof String) return 'string';
6
+ else if (type === 'number' || obj instanceof Number) return 'number';
7
+ else if (type === 'function' || obj instanceof Function) return 'function';
8
+ else if (!!obj && obj.constructor === Array) return 'array';
9
+ else if (obj && obj.nodeType === 1) return 'element';
10
+ else if (type === 'object') return 'object';
11
+ else return 'unknown';
12
+ };
13
+
14
+ // Create an HTML element with optional className, innerHTML, and style.
15
+ export const createElement = function createElement(tagName, opt) {
16
+ var el = document.createElement(tagName);
17
+ if (opt.className) el.className = opt.className;
18
+ if (opt.innerHTML) {
19
+ el.innerHTML = opt.innerHTML;
20
+ var scripts = el.getElementsByTagName('script');
21
+ for (var i = scripts.length; i-- > 0; null) {
22
+ scripts[i].parentNode.removeChild(scripts[i]);
23
+ }
24
+ }
25
+ for (var key in opt.style) {
26
+ el.style[key] = opt.style[key];
27
+ }
28
+ return el;
29
+ };
30
+
31
+ // Convert units from px using the conversion value 'k' from jsPDF.
32
+ export const unitConvert = function unitConvert(obj, k) {
33
+ if (objType(obj) === 'number') {
34
+ return obj * 72 / 96 / k;
35
+ } else {
36
+ var newObj = {};
37
+ for (var key in obj) {
38
+ newObj[key] = obj[key] * 72 / 96 / k;
39
+ }
40
+ return newObj;
41
+ }
42
+ };
43
+
44
+ // Convert units to px using the conversion value 'k' from jsPDF.
45
+ export const toPx = function toPx(val, k) {
46
+ return Math.floor(val * k / 72 * 96);
47
+ }