@paprize/puppeteer 0.0.4 → 0.0.6

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.
@@ -0,0 +1,2128 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __commonJS = (cb, mod) => function __require() {
8
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19
+ // If the importer is in node compatibility mode or this is not an ESM
20
+ // file that has been converted to a CommonJS file using a Babel-
21
+ // compatible transform (i.e. "__esModule" has not been set), then set
22
+ // "default" to the CommonJS "module.exports" for node compatibility.
23
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
+ mod
25
+ ));
26
+
27
+ // ../../node_modules/loglevel/lib/loglevel.js
28
+ var require_loglevel = __commonJS({
29
+ "../../node_modules/loglevel/lib/loglevel.js"(exports, module) {
30
+ (function(root, definition) {
31
+ "use strict";
32
+ if (typeof define === "function" && define.amd) {
33
+ define(definition);
34
+ } else if (typeof module === "object" && module.exports) {
35
+ module.exports = definition();
36
+ } else {
37
+ root.log = definition();
38
+ }
39
+ })(exports, function() {
40
+ "use strict";
41
+ var noop = function() {
42
+ };
43
+ var undefinedType = "undefined";
44
+ var isIE = typeof window !== undefinedType && typeof window.navigator !== undefinedType && /Trident\/|MSIE /.test(window.navigator.userAgent);
45
+ var logMethods = [
46
+ "trace",
47
+ "debug",
48
+ "info",
49
+ "warn",
50
+ "error"
51
+ ];
52
+ var _loggersByName = {};
53
+ var defaultLogger = null;
54
+ function bindMethod(obj, methodName) {
55
+ var method = obj[methodName];
56
+ if (typeof method.bind === "function") {
57
+ return method.bind(obj);
58
+ } else {
59
+ try {
60
+ return Function.prototype.bind.call(method, obj);
61
+ } catch (e) {
62
+ return function() {
63
+ return Function.prototype.apply.apply(method, [obj, arguments]);
64
+ };
65
+ }
66
+ }
67
+ }
68
+ function traceForIE() {
69
+ if (console.log) {
70
+ if (console.log.apply) {
71
+ console.log.apply(console, arguments);
72
+ } else {
73
+ Function.prototype.apply.apply(console.log, [console, arguments]);
74
+ }
75
+ }
76
+ if (console.trace) console.trace();
77
+ }
78
+ function realMethod(methodName) {
79
+ if (methodName === "debug") {
80
+ methodName = "log";
81
+ }
82
+ if (typeof console === undefinedType) {
83
+ return false;
84
+ } else if (methodName === "trace" && isIE) {
85
+ return traceForIE;
86
+ } else if (console[methodName] !== void 0) {
87
+ return bindMethod(console, methodName);
88
+ } else if (console.log !== void 0) {
89
+ return bindMethod(console, "log");
90
+ } else {
91
+ return noop;
92
+ }
93
+ }
94
+ function replaceLoggingMethods() {
95
+ var level = this.getLevel();
96
+ for (var i = 0; i < logMethods.length; i++) {
97
+ var methodName = logMethods[i];
98
+ this[methodName] = i < level ? noop : this.methodFactory(methodName, level, this.name);
99
+ }
100
+ this.log = this.debug;
101
+ if (typeof console === undefinedType && level < this.levels.SILENT) {
102
+ return "No console available for logging";
103
+ }
104
+ }
105
+ function enableLoggingWhenConsoleArrives(methodName) {
106
+ return function() {
107
+ if (typeof console !== undefinedType) {
108
+ replaceLoggingMethods.call(this);
109
+ this[methodName].apply(this, arguments);
110
+ }
111
+ };
112
+ }
113
+ function defaultMethodFactory(methodName, _level, _loggerName) {
114
+ return realMethod(methodName) || enableLoggingWhenConsoleArrives.apply(this, arguments);
115
+ }
116
+ function Logger(name, factory) {
117
+ var self = this;
118
+ var inheritedLevel;
119
+ var defaultLevel;
120
+ var userLevel;
121
+ var storageKey = "loglevel";
122
+ if (typeof name === "string") {
123
+ storageKey += ":" + name;
124
+ } else if (typeof name === "symbol") {
125
+ storageKey = void 0;
126
+ }
127
+ function persistLevelIfPossible(levelNum) {
128
+ var levelName = (logMethods[levelNum] || "silent").toUpperCase();
129
+ if (typeof window === undefinedType || !storageKey) return;
130
+ try {
131
+ window.localStorage[storageKey] = levelName;
132
+ return;
133
+ } catch (ignore) {
134
+ }
135
+ try {
136
+ window.document.cookie = encodeURIComponent(storageKey) + "=" + levelName + ";";
137
+ } catch (ignore) {
138
+ }
139
+ }
140
+ function getPersistedLevel() {
141
+ var storedLevel;
142
+ if (typeof window === undefinedType || !storageKey) return;
143
+ try {
144
+ storedLevel = window.localStorage[storageKey];
145
+ } catch (ignore) {
146
+ }
147
+ if (typeof storedLevel === undefinedType) {
148
+ try {
149
+ var cookie = window.document.cookie;
150
+ var cookieName = encodeURIComponent(storageKey);
151
+ var location = cookie.indexOf(cookieName + "=");
152
+ if (location !== -1) {
153
+ storedLevel = /^([^;]+)/.exec(
154
+ cookie.slice(location + cookieName.length + 1)
155
+ )[1];
156
+ }
157
+ } catch (ignore) {
158
+ }
159
+ }
160
+ if (self.levels[storedLevel] === void 0) {
161
+ storedLevel = void 0;
162
+ }
163
+ return storedLevel;
164
+ }
165
+ function clearPersistedLevel() {
166
+ if (typeof window === undefinedType || !storageKey) return;
167
+ try {
168
+ window.localStorage.removeItem(storageKey);
169
+ } catch (ignore) {
170
+ }
171
+ try {
172
+ window.document.cookie = encodeURIComponent(storageKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
173
+ } catch (ignore) {
174
+ }
175
+ }
176
+ function normalizeLevel(input) {
177
+ var level = input;
178
+ if (typeof level === "string" && self.levels[level.toUpperCase()] !== void 0) {
179
+ level = self.levels[level.toUpperCase()];
180
+ }
181
+ if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) {
182
+ return level;
183
+ } else {
184
+ throw new TypeError("log.setLevel() called with invalid level: " + input);
185
+ }
186
+ }
187
+ self.name = name;
188
+ self.levels = {
189
+ "TRACE": 0,
190
+ "DEBUG": 1,
191
+ "INFO": 2,
192
+ "WARN": 3,
193
+ "ERROR": 4,
194
+ "SILENT": 5
195
+ };
196
+ self.methodFactory = factory || defaultMethodFactory;
197
+ self.getLevel = function() {
198
+ if (userLevel != null) {
199
+ return userLevel;
200
+ } else if (defaultLevel != null) {
201
+ return defaultLevel;
202
+ } else {
203
+ return inheritedLevel;
204
+ }
205
+ };
206
+ self.setLevel = function(level, persist) {
207
+ userLevel = normalizeLevel(level);
208
+ if (persist !== false) {
209
+ persistLevelIfPossible(userLevel);
210
+ }
211
+ return replaceLoggingMethods.call(self);
212
+ };
213
+ self.setDefaultLevel = function(level) {
214
+ defaultLevel = normalizeLevel(level);
215
+ if (!getPersistedLevel()) {
216
+ self.setLevel(level, false);
217
+ }
218
+ };
219
+ self.resetLevel = function() {
220
+ userLevel = null;
221
+ clearPersistedLevel();
222
+ replaceLoggingMethods.call(self);
223
+ };
224
+ self.enableAll = function(persist) {
225
+ self.setLevel(self.levels.TRACE, persist);
226
+ };
227
+ self.disableAll = function(persist) {
228
+ self.setLevel(self.levels.SILENT, persist);
229
+ };
230
+ self.rebuild = function() {
231
+ if (defaultLogger !== self) {
232
+ inheritedLevel = normalizeLevel(defaultLogger.getLevel());
233
+ }
234
+ replaceLoggingMethods.call(self);
235
+ if (defaultLogger === self) {
236
+ for (var childName in _loggersByName) {
237
+ _loggersByName[childName].rebuild();
238
+ }
239
+ }
240
+ };
241
+ inheritedLevel = normalizeLevel(
242
+ defaultLogger ? defaultLogger.getLevel() : "WARN"
243
+ );
244
+ var initialLevel = getPersistedLevel();
245
+ if (initialLevel != null) {
246
+ userLevel = normalizeLevel(initialLevel);
247
+ }
248
+ replaceLoggingMethods.call(self);
249
+ }
250
+ defaultLogger = new Logger();
251
+ defaultLogger.getLogger = function getLogger(name) {
252
+ if (typeof name !== "symbol" && typeof name !== "string" || name === "") {
253
+ throw new TypeError("You must supply a name when creating a logger.");
254
+ }
255
+ var logger3 = _loggersByName[name];
256
+ if (!logger3) {
257
+ logger3 = _loggersByName[name] = new Logger(
258
+ name,
259
+ defaultLogger.methodFactory
260
+ );
261
+ }
262
+ return logger3;
263
+ };
264
+ var _log = typeof window !== undefinedType ? window.log : void 0;
265
+ defaultLogger.noConflict = function() {
266
+ if (typeof window !== undefinedType && window.log === defaultLogger) {
267
+ window.log = _log;
268
+ }
269
+ return defaultLogger;
270
+ };
271
+ defaultLogger.getLoggers = function getLoggers() {
272
+ return _loggersByName;
273
+ };
274
+ defaultLogger["default"] = defaultLogger;
275
+ return defaultLogger;
276
+ });
277
+ }
278
+ });
279
+
280
+ // ../core/src/constants.ts
281
+ var loggerName = "paprize";
282
+ var tempContainerClassName = "pz-temp-container";
283
+ var currentElementClassName = "pz-current-element";
284
+ var currentTextClassName = "pz-current-text";
285
+ var ignoredElementClassName = "pz-ignored-element";
286
+ var ignoredTextClassName = "pz-ignored-text";
287
+ var globalStyleId = "paprize-global-style";
288
+ var pageClassName = "pz-page";
289
+ var sectionClassName = "pz-section";
290
+ var previewClassName = "pz-preview";
291
+ var attributePrefix = "data-pz-";
292
+
293
+ // ../core/src/debugUtilities/debugMode.ts
294
+ var debugMode = false;
295
+ var isDebugMode = () => debugMode;
296
+
297
+ // ../core/src/paginate/domUtilities.ts
298
+ function isElement(node) {
299
+ return node.nodeType === Node.ELEMENT_NODE;
300
+ }
301
+ function isTextNode(node) {
302
+ return node.nodeType === Node.TEXT_NODE;
303
+ }
304
+ function getVisibleHeight(element) {
305
+ const rect = element.getBoundingClientRect();
306
+ const computedStyle = getComputedStyle(element);
307
+ const marginTop = parseFloat(computedStyle.marginTop) || 0;
308
+ const marginBottom = parseFloat(computedStyle.marginBottom) || 0;
309
+ return rect.height + marginTop + marginBottom;
310
+ }
311
+ function moveOffscreen(element) {
312
+ element.style.visibility = "hidden";
313
+ element.style.position = "absolute";
314
+ element.style.left = "-9999px";
315
+ element.style.top = "-9999px";
316
+ }
317
+
318
+ // ../core/src/paginate/LayoutOptions.ts
319
+ var defaultLayoutOptions = {
320
+ hyphen: "-",
321
+ keepOnSamePage: false,
322
+ hyphenationDisabled: false
323
+ };
324
+
325
+ // ../core/src/paginate/attributes.ts
326
+ var layoutOptionsAttributes = {
327
+ hyphen: {
328
+ key: `${attributePrefix}hyphen`,
329
+ reader: (value) => String(value)
330
+ },
331
+ keepOnSamePage: {
332
+ key: `${attributePrefix}keep-on-same-page`,
333
+ reader: (value) => value === "true"
334
+ },
335
+ hyphenationDisabled: {
336
+ key: `${attributePrefix}hyphenation-disabled`,
337
+ reader: (value) => value === "true"
338
+ }
339
+ };
340
+ var attributeCache = /* @__PURE__ */ new WeakMap();
341
+ function assignAttribute(key, reader, value, attributes) {
342
+ if (value == null) {
343
+ return;
344
+ }
345
+ const parsedValue = reader(value);
346
+ if (parsedValue !== void 0) {
347
+ attributes[key] = parsedValue;
348
+ }
349
+ }
350
+ function getNodeLayoutOptionsFromAttribute(node) {
351
+ if (!node) {
352
+ return {};
353
+ }
354
+ if (!(node instanceof Element)) {
355
+ return getNodeLayoutOptionsFromAttribute(node?.parentNode);
356
+ }
357
+ const attributes = {};
358
+ for (const key of Object.keys(defaultLayoutOptions)) {
359
+ const typedKey = key;
360
+ const attribute = layoutOptionsAttributes[typedKey];
361
+ const value = node.getAttribute(attribute.key);
362
+ assignAttribute(typedKey, attribute.reader, value, attributes);
363
+ }
364
+ const parentAttributes = node.parentNode ? attributeCache.get(node.parentNode) : void 0;
365
+ const result = { ...parentAttributes, ...attributes };
366
+ attributeCache.set(node, result);
367
+ return result;
368
+ }
369
+
370
+ // ../core/src/paginate/PaginationOptions.ts
371
+ var defaultPaginationOptions = {
372
+ id: "default",
373
+ plugins: [],
374
+ ...defaultLayoutOptions
375
+ };
376
+ function resolvePaginationOptions(node, globalConfig) {
377
+ const attributes = getNodeLayoutOptionsFromAttribute(node);
378
+ return { ...defaultPaginationOptions, ...globalConfig, ...attributes };
379
+ }
380
+
381
+ // ../core/src/logger.ts
382
+ var import_loglevel = __toESM(require_loglevel(), 1);
383
+ var logger = import_loglevel.default.getLogger(loggerName);
384
+ logger.setDefaultLevel("info");
385
+ var logger_default = logger;
386
+
387
+ // ../core/src/paginate/PaginationPlugin.ts
388
+ var logPrefix = "\x1B[46mPLUGIN\x1B[0m";
389
+ function callPluginHook(plugins, hookName, ...args) {
390
+ plugins.sort((a, b) => a.order - b.order).forEach((plugin) => {
391
+ const hook = plugin[hookName];
392
+ if (!hook) {
393
+ return;
394
+ }
395
+ logger_default.debug(
396
+ logPrefix,
397
+ `executing plugin ${plugin.name}:${String(hookName)} (${String()})`,
398
+ args
399
+ );
400
+ try {
401
+ hook(...args);
402
+ logger_default.debug(
403
+ logPrefix,
404
+ `plugin ${plugin.name}:${String(hookName)} executed`,
405
+ args
406
+ );
407
+ } catch (error) {
408
+ logger_default.debug(
409
+ logPrefix,
410
+ `plugin ${plugin.name}:${String(hookName)} failed`,
411
+ error
412
+ );
413
+ }
414
+ });
415
+ }
416
+
417
+ // ../core/src/paginate/PageNodes.ts
418
+ var PageNodeType = {
419
+ Element: "element",
420
+ Text: "text"
421
+ };
422
+ var PageElement = class _PageElement {
423
+ _node;
424
+ config;
425
+ type = PageNodeType.Element;
426
+ transaction;
427
+ clonedFrom;
428
+ cloneCount;
429
+ constructor(element, transaction, config, clonedFrom) {
430
+ this._node = element;
431
+ this.transaction = transaction;
432
+ this.config = config;
433
+ this.clonedFrom = clonedFrom;
434
+ this.cloneCount = clonedFrom ? clonedFrom.cloneCount + 1 : 0;
435
+ }
436
+ getOriginalNode() {
437
+ let current = this.clonedFrom;
438
+ while (current?.clonedFrom) {
439
+ current = current.clonedFrom;
440
+ }
441
+ return current?._node;
442
+ }
443
+ appendChild(node) {
444
+ if (this.transaction.isActive) {
445
+ this.transaction.addRollbackCallback(() => {
446
+ this._node.removeChild(node.getNode());
447
+ });
448
+ }
449
+ this._node.appendChild(node.getNode());
450
+ }
451
+ clone(withChildren) {
452
+ const clonedElement = this._node.cloneNode(withChildren);
453
+ const clonedPageElement = new _PageElement(
454
+ clonedElement,
455
+ this.transaction,
456
+ this.config,
457
+ this
458
+ );
459
+ callPluginHook(
460
+ this.config.plugins,
461
+ "onClone",
462
+ this.config.id,
463
+ this._node,
464
+ clonedPageElement
465
+ );
466
+ return clonedPageElement;
467
+ }
468
+ getHeight() {
469
+ return getVisibleHeight(this._node);
470
+ }
471
+ remove() {
472
+ this.transaction.addCommitCallback(() => {
473
+ this._node.remove();
474
+ });
475
+ }
476
+ isEmpty() {
477
+ return this._node.innerHTML === "";
478
+ }
479
+ getChildrenCount() {
480
+ return this._node.childNodes.length;
481
+ }
482
+ getNode() {
483
+ return this._node;
484
+ }
485
+ };
486
+ var PageText = class {
487
+ _node;
488
+ type = PageNodeType.Text;
489
+ transaction;
490
+ config;
491
+ constructor(text, transaction, config) {
492
+ this._node = text;
493
+ this.transaction = transaction;
494
+ this.config = config;
495
+ }
496
+ get textContent() {
497
+ return this._node.textContent ?? "";
498
+ }
499
+ set textContent(value) {
500
+ this._node.textContent = value;
501
+ }
502
+ remove() {
503
+ this.transaction.addCommitCallback(() => {
504
+ this._node.remove();
505
+ });
506
+ }
507
+ getNode() {
508
+ return this._node;
509
+ }
510
+ };
511
+ function createPageNode(node, transaction, config) {
512
+ if (isTextNode(node)) {
513
+ return new PageText(node, transaction, config);
514
+ } else if (isElement(node)) {
515
+ return new PageElement(node, transaction, config);
516
+ }
517
+ throw new Error("Unsupported node type");
518
+ }
519
+
520
+ // ../core/src/debugUtilities/pageNodeMarker.ts
521
+ function markIgnoredNode(node) {
522
+ if (!isDebugMode()) {
523
+ return;
524
+ }
525
+ if (node && node.type == PageNodeType.Element) {
526
+ node.getNode().classList.add(ignoredElementClassName);
527
+ } else if (node && node.type == PageNodeType.Text) {
528
+ node.getNode().parentElement?.classList.add(ignoredTextClassName);
529
+ }
530
+ }
531
+ function markCurrentNode(node) {
532
+ if (!isDebugMode()) {
533
+ return;
534
+ }
535
+ if (node && node.type == PageNodeType.Element) {
536
+ node.getNode().classList.add(currentElementClassName);
537
+ } else if (node && node.type == PageNodeType.Text) {
538
+ node.getNode().parentElement?.classList.add(currentTextClassName);
539
+ }
540
+ }
541
+ function unmarkCurrentNode(node) {
542
+ if (!isDebugMode()) {
543
+ return;
544
+ }
545
+ if (node && node.type == PageNodeType.Element) {
546
+ node.getNode().classList.remove(currentElementClassName);
547
+ } else if (node && node.type == PageNodeType.Text) {
548
+ node.getNode().parentElement?.classList.remove(currentTextClassName);
549
+ }
550
+ }
551
+
552
+ // ../core/src/paginate/DomState.ts
553
+ var logPrefix2 = "\x1B[106mDOM\x1B[0m";
554
+ var DomState = class {
555
+ _transaction;
556
+ _treeWalker;
557
+ _config;
558
+ _completed = false;
559
+ _currentNode = null;
560
+ _previousNode = null;
561
+ constructor(root, transaction, config) {
562
+ this._transaction = transaction;
563
+ this._config = config;
564
+ this._treeWalker = document.createTreeWalker(
565
+ root,
566
+ NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT
567
+ );
568
+ }
569
+ get completed() {
570
+ return this._completed;
571
+ }
572
+ get currentNode() {
573
+ return this._currentNode;
574
+ }
575
+ get previousNode() {
576
+ return this._previousNode;
577
+ }
578
+ goToNextNode() {
579
+ const result = this._treeWalker.nextNode();
580
+ if (!result) {
581
+ this._completed = true;
582
+ }
583
+ logger_default.debug(logPrefix2, "moving to next node");
584
+ this.setState();
585
+ }
586
+ goToNextSiblingOrParentSibling() {
587
+ let parentsTraversed = 0;
588
+ if (this._treeWalker.nextSibling()) {
589
+ logger_default.debug(logPrefix2, "moving to next sibling node");
590
+ this.setState();
591
+ return { parentsTraversed };
592
+ }
593
+ while (this._treeWalker.parentNode()) {
594
+ parentsTraversed++;
595
+ if (this._treeWalker.nextSibling()) {
596
+ logger_default.debug(
597
+ logPrefix2,
598
+ "moving to parent sibling node, traversed:",
599
+ parentsTraversed
600
+ );
601
+ this.setState();
602
+ return { parentsTraversed };
603
+ }
604
+ }
605
+ this._completed = true;
606
+ return { parentsTraversed };
607
+ }
608
+ goToFirstChildOrNextNode() {
609
+ if (this._treeWalker.firstChild()) {
610
+ logger_default.debug(logPrefix2, "moving to first child node");
611
+ this.setState();
612
+ return { parentsTraversed: 1 };
613
+ }
614
+ this.goToNextNode();
615
+ return { parentsTraversed: 0 };
616
+ }
617
+ setState() {
618
+ this._previousNode = this._currentNode;
619
+ this._currentNode = createPageNode(
620
+ this._treeWalker.currentNode,
621
+ this._transaction,
622
+ resolvePaginationOptions(this._treeWalker.currentNode, this._config)
623
+ );
624
+ DEV: markCurrentNode(this._currentNode);
625
+ DEV: unmarkCurrentNode(this._previousNode);
626
+ logger_default.debug(logPrefix2, "moved to node", {
627
+ currentNode: this._currentNode,
628
+ previousNode: this._previousNode
629
+ });
630
+ }
631
+ };
632
+
633
+ // ../core/src/paginate/Transaction.ts
634
+ var Transaction = class {
635
+ _onRollback;
636
+ _onCommit;
637
+ isActive;
638
+ constructor() {
639
+ this._onRollback = [];
640
+ this._onCommit = [];
641
+ this.isActive = false;
642
+ }
643
+ start = () => {
644
+ if (this.isActive) {
645
+ throw new Error("Transaction already in progress");
646
+ }
647
+ this.isActive = true;
648
+ this._onRollback = [];
649
+ this._onCommit = [];
650
+ };
651
+ addRollbackCallback = (callback) => {
652
+ this._onRollback.push(callback);
653
+ };
654
+ addCommitCallback = (callback) => {
655
+ if (!this.isActive) {
656
+ callback();
657
+ return;
658
+ }
659
+ this._onCommit.push(callback);
660
+ };
661
+ rollback = () => {
662
+ if (!this.isActive) return;
663
+ this.isActive = false;
664
+ this._onRollback.forEach((func) => func());
665
+ };
666
+ commit = () => {
667
+ if (!this.isActive) return;
668
+ this.isActive = false;
669
+ this._onCommit.forEach((func) => func());
670
+ };
671
+ };
672
+
673
+ // ../core/src/paginate/PageManager.ts
674
+ var logPrefix3 = "\x1B[102mPAGE\x1B[0m";
675
+ var PageState = class _PageState {
676
+ currentPage;
677
+ activeElement;
678
+ currentElement;
679
+ parentStack;
680
+ pageIsFull;
681
+ pageIndex;
682
+ pageHeight;
683
+ constructor(currentPage, activeElement, currentElement, parentStack, pageIsFull, pageIndex, pageHeight) {
684
+ this.currentPage = currentPage;
685
+ this.activeElement = activeElement;
686
+ this.currentElement = currentElement;
687
+ this.parentStack = parentStack;
688
+ this.pageIsFull = pageIsFull;
689
+ this.pageIndex = pageIndex;
690
+ this.pageHeight = pageHeight;
691
+ }
692
+ static create(currentPage, parentStack, pageIndex, pageHeight) {
693
+ return new _PageState(
694
+ currentPage,
695
+ null,
696
+ currentPage,
697
+ parentStack,
698
+ false,
699
+ pageIndex,
700
+ pageHeight
701
+ );
702
+ }
703
+ clone = () => {
704
+ return new _PageState(
705
+ this.currentPage,
706
+ this.activeElement,
707
+ this.currentElement,
708
+ [...this.parentStack],
709
+ this.pageIsFull,
710
+ this.pageIndex,
711
+ this.pageHeight
712
+ );
713
+ };
714
+ };
715
+ var PageManager = class _PageManager {
716
+ _pageState;
717
+ _transaction;
718
+ _tempContainer;
719
+ _config;
720
+ constructor(tempContainer, pageSize2, transaction, config) {
721
+ this._tempContainer = tempContainer;
722
+ this._config = config;
723
+ this._transaction = transaction;
724
+ const pageHtmlElement = _PageManager.createPageHtmlElement(
725
+ pageSize2.width
726
+ );
727
+ const page2 = this.createNewPage(pageHtmlElement);
728
+ this._pageState = PageState.create(page2, [], 0, pageSize2.height);
729
+ callPluginHook(this._config.plugins, "onNewPage", config.id, this);
730
+ }
731
+ nextPage() {
732
+ const page2 = this.createNewPage(
733
+ this._pageState.currentPage.getNode().cloneNode(false)
734
+ );
735
+ const newPageState = PageState.create(
736
+ page2,
737
+ [],
738
+ this._pageState.pageIndex + 1,
739
+ this._pageState.pageHeight
740
+ );
741
+ this.cloneParentStackToNewPage(newPageState);
742
+ this.cleanupEmptyParent();
743
+ this._pageState = newPageState;
744
+ callPluginHook(
745
+ this._config.plugins,
746
+ "onNewPage",
747
+ this._config.id,
748
+ this
749
+ );
750
+ }
751
+ cloneParentStackToNewPage(newPageState) {
752
+ for (const parent of this._pageState.parentStack) {
753
+ const clonedParent = parent.clone(false);
754
+ newPageState.currentElement.appendChild(clonedParent);
755
+ newPageState.currentElement = clonedParent;
756
+ newPageState.parentStack.push(clonedParent);
757
+ }
758
+ }
759
+ cleanupEmptyParent() {
760
+ const parentStack = [...this._pageState.parentStack];
761
+ const cleanup = () => {
762
+ for (let i = parentStack.length - 1; i >= 0; i--) {
763
+ const parent = parentStack[i];
764
+ if (parent.isEmpty()) {
765
+ parent.remove();
766
+ }
767
+ }
768
+ };
769
+ this._transaction.addCommitCallback(cleanup);
770
+ }
771
+ enterElement() {
772
+ if (!this._pageState.activeElement || this._pageState.activeElement.type !== PageNodeType.Element) {
773
+ throw new Error("Invalid state: activeElement is not an Element");
774
+ }
775
+ logger_default.debug(
776
+ logPrefix3,
777
+ "entering an element",
778
+ this._pageState.activeElement
779
+ );
780
+ this._pageState.currentElement = this._pageState.activeElement;
781
+ this._pageState.parentStack.push(this._pageState.activeElement);
782
+ }
783
+ leaveElement() {
784
+ this._pageState.activeElement = null;
785
+ const popped = this._pageState.parentStack.pop();
786
+ logger_default.debug(logPrefix3, "leaving a parent element", popped);
787
+ const parent = this._pageState.parentStack.at(-1);
788
+ this._pageState.currentElement = parent ?? this._pageState.currentPage;
789
+ }
790
+ static createPageHtmlElement(pageWidth) {
791
+ const page2 = document.createElement("div");
792
+ page2.style.width = `${pageWidth}px`;
793
+ page2.style.maxWidth = `${pageWidth}px`;
794
+ return page2;
795
+ }
796
+ createNewPage(pageHtmlElement) {
797
+ this._tempContainer.appendChild(pageHtmlElement);
798
+ if (this._transaction.isActive) {
799
+ this._transaction.addRollbackCallback(() => {
800
+ this._tempContainer.removeChild(pageHtmlElement);
801
+ });
802
+ }
803
+ return createPageNode(pageHtmlElement, this._transaction, this._config);
804
+ }
805
+ startTransaction() {
806
+ this._transaction.start();
807
+ const state = this._pageState.clone();
808
+ this._transaction.addRollbackCallback(() => {
809
+ this._pageState = state;
810
+ });
811
+ return this._transaction;
812
+ }
813
+ hasEmptySpace(elementHeight) {
814
+ return !this._pageState.pageIsFull && this._pageState.currentPage.getHeight() + (elementHeight || 1e-4) <= this._pageState.pageHeight;
815
+ }
816
+ isOverFlow() {
817
+ return this._pageState.currentPage.getHeight() > this._pageState.pageHeight;
818
+ }
819
+ markPageAsFull() {
820
+ this._pageState.pageIsFull = true;
821
+ }
822
+ appendChild(node, withChildren) {
823
+ const clonedNode = node.clone(withChildren);
824
+ DEV: unmarkCurrentNode(clonedNode);
825
+ this._pageState.currentElement.appendChild(clonedNode);
826
+ this._pageState.activeElement = clonedNode;
827
+ return clonedNode;
828
+ }
829
+ addTextNode(text) {
830
+ if (this._pageState.activeElement?.type === PageNodeType.Text) {
831
+ return this._pageState.activeElement;
832
+ }
833
+ const textNode = document.createTextNode(text);
834
+ const newTextNode = createPageNode(
835
+ textNode,
836
+ this._transaction,
837
+ this._config
838
+ );
839
+ this._pageState.currentElement.appendChild(newTextNode);
840
+ this._pageState.activeElement = newTextNode;
841
+ return newTextNode;
842
+ }
843
+ getPageState() {
844
+ return this._pageState;
845
+ }
846
+ };
847
+
848
+ // ../core/src/paginate/SplitResult.ts
849
+ var SplitResult = {
850
+ None: 0,
851
+ // The node fits completely on the page, no further splitting required.
852
+ FullNodePlaced: 1,
853
+ // The entire node was placed on the page, continue with the next sibling or element.
854
+ SplitChildren: 2
855
+ // The node is too large for the page, and its children must be paginated individually.
856
+ };
857
+
858
+ // ../core/src/paginate/paginateElement.ts
859
+ function paginateElementAcrossPages(currentNode, pageManager) {
860
+ const result = tryPlaceElement(currentNode, pageManager);
861
+ if (result !== SplitResult.None) {
862
+ return result;
863
+ }
864
+ const { rollback, commit } = pageManager.startTransaction();
865
+ pageManager.nextPage();
866
+ const nextPageResult = tryPlaceElement(currentNode, pageManager);
867
+ if (nextPageResult !== SplitResult.None) {
868
+ commit();
869
+ return nextPageResult;
870
+ }
871
+ rollback();
872
+ logger_default.debug("Element is too big to fit on a page", currentNode);
873
+ return SplitResult.None;
874
+ }
875
+ function tryPlaceElement(currentNode, pageManager) {
876
+ if (pageManager.hasEmptySpace(currentNode.getHeight())) {
877
+ const clonedNode2 = pageManager.appendChild(currentNode, true);
878
+ if (pageManager.isOverFlow()) {
879
+ clonedNode2.remove();
880
+ } else {
881
+ return SplitResult.FullNodePlaced;
882
+ }
883
+ }
884
+ if (currentNode.config.keepOnSamePage || currentNode.getChildrenCount() === 0) {
885
+ return SplitResult.None;
886
+ }
887
+ const clonedNode = pageManager.appendChild(currentNode, false);
888
+ if (pageManager.isOverFlow()) {
889
+ clonedNode.remove();
890
+ return SplitResult.None;
891
+ }
892
+ return SplitResult.SplitChildren;
893
+ }
894
+
895
+ // ../core/src/paginate/paginateText.ts
896
+ function paginateTextByWord(text, pageManager) {
897
+ let splitResult = SplitResult.FullNodePlaced;
898
+ const tokens = text.textContent.split(/(\s+)/).filter((token) => token !== "");
899
+ let pendingToken;
900
+ let tokenIndex = 0;
901
+ while (pendingToken || tokenIndex < tokens.length) {
902
+ const currentToken = pendingToken ?? tokens[tokenIndex];
903
+ const result = processToken(currentToken, pageManager, text.config);
904
+ if (!result.completed) {
905
+ splitResult = SplitResult.None;
906
+ }
907
+ if (result.pendingToken) {
908
+ pendingToken = result.pendingToken;
909
+ } else {
910
+ pendingToken = void 0;
911
+ tokenIndex++;
912
+ }
913
+ }
914
+ return splitResult;
915
+ }
916
+ function processToken(token, pageManager, config) {
917
+ if (!pageManager.hasEmptySpace()) {
918
+ pageManager.nextPage();
919
+ }
920
+ const textNode = pageManager.addTextNode("");
921
+ const originalContent = textNode.textContent;
922
+ textNode.textContent += token;
923
+ if (!pageManager.isOverFlow()) {
924
+ return {
925
+ completed: true
926
+ };
927
+ }
928
+ textNode.textContent = originalContent;
929
+ const overflowResult = handleTokenOverflow(token, pageManager, config);
930
+ return {
931
+ pendingToken: overflowResult.leftovers,
932
+ completed: overflowResult.completed
933
+ };
934
+ }
935
+ function handleTokenOverflow(token, pageManager, config) {
936
+ const { rollback, commit } = pageManager.startTransaction();
937
+ pageManager.nextPage();
938
+ pageManager.addTextNode(token);
939
+ if (!pageManager.isOverFlow()) {
940
+ commit();
941
+ return {
942
+ completed: true
943
+ };
944
+ }
945
+ rollback();
946
+ if (config.hyphenationDisabled) {
947
+ logger_default.warn("Hyphenation disabled, skipping oversized token:", token);
948
+ return {
949
+ completed: false
950
+ };
951
+ }
952
+ const leftovers = hyphenation(token, config.hyphen, pageManager);
953
+ return {
954
+ completed: true,
955
+ leftovers: leftovers && leftovers.length > 0 ? leftovers : void 0
956
+ };
957
+ }
958
+ function hyphenation(word, hyphen, pageManager) {
959
+ const textNode = pageManager.addTextNode("");
960
+ let appended = "";
961
+ for (let i = 0; i < word.length; i++) {
962
+ const char = word[i];
963
+ const tentative = appended + char;
964
+ textNode.textContent = tentative + hyphen;
965
+ if (!pageManager.hasEmptySpace()) {
966
+ textNode.textContent = appended ? appended + hyphen : "";
967
+ pageManager.markPageAsFull();
968
+ return word.slice(i);
969
+ }
970
+ appended = tentative;
971
+ }
972
+ return null;
973
+ }
974
+
975
+ // ../core/src/paginate/Paginator.ts
976
+ var import_loglevel2 = __toESM(require_loglevel(), 1);
977
+ var logPrefix4 = "\x1B[103mPAGINATOR\x1B[0m";
978
+ var Paginator = class _Paginator {
979
+ _domState;
980
+ _pageManager;
981
+ _transaction;
982
+ _tempContainer;
983
+ _config;
984
+ constructor(root, pageSize2, config) {
985
+ this._config = { ...defaultPaginationOptions, ...config };
986
+ this._tempContainer = _Paginator.createTempContainer(this._config.id);
987
+ this._transaction = new Transaction();
988
+ this._domState = new DomState(root, this._transaction, this._config);
989
+ this._pageManager = new PageManager(
990
+ this._tempContainer,
991
+ pageSize2,
992
+ this._transaction,
993
+ this._config
994
+ );
995
+ }
996
+ static createTempContainer(id) {
997
+ const tempContainer = document.createElement("div");
998
+ tempContainer.style.display = "flex";
999
+ tempContainer.style.flexDirection = "column";
1000
+ tempContainer.style.gap = "20px";
1001
+ tempContainer.setAttribute(`${attributePrefix}-section-id`, id);
1002
+ tempContainer.classList.add(tempContainerClassName);
1003
+ DEV: if (!isDebugMode()) {
1004
+ moveOffscreen(tempContainer);
1005
+ }
1006
+ document.body.appendChild(tempContainer);
1007
+ return tempContainer;
1008
+ }
1009
+ static paginate(root, pageSize2, config) {
1010
+ const paginator = new _Paginator(root, pageSize2, config);
1011
+ paginator.processAllNodes();
1012
+ const result = Array.from(paginator._tempContainer.childNodes).filter((x) => isElement(x)).map((x) => x.innerHTML);
1013
+ DEV: if (!isDebugMode()) {
1014
+ paginator._tempContainer.remove();
1015
+ }
1016
+ return result;
1017
+ }
1018
+ processAllNodes() {
1019
+ this._domState.goToNextNode();
1020
+ do {
1021
+ import_loglevel2.default.debug(
1022
+ logPrefix4,
1023
+ "paginating node",
1024
+ this._domState.currentNode
1025
+ );
1026
+ const result = this.processCurrentNode();
1027
+ callPluginHook(
1028
+ this._config.plugins,
1029
+ "afterVisitNode",
1030
+ this._config.id,
1031
+ result,
1032
+ this._domState,
1033
+ this._pageManager
1034
+ );
1035
+ switch (result) {
1036
+ case SplitResult.None:
1037
+ this.handleNodeSkipped();
1038
+ break;
1039
+ case SplitResult.FullNodePlaced:
1040
+ this.handleFullNodePlaced();
1041
+ break;
1042
+ case SplitResult.SplitChildren:
1043
+ this.handleChildrenSplit();
1044
+ break;
1045
+ }
1046
+ } while (this._domState.completed === false);
1047
+ import_loglevel2.default.debug(logPrefix4, "pagination completed");
1048
+ }
1049
+ handleNodeSkipped() {
1050
+ import_loglevel2.default.debug(logPrefix4, "node skipped - couldn't paginate");
1051
+ DEV: markIgnoredNode(this._domState.currentNode);
1052
+ this._domState.goToNextNode();
1053
+ }
1054
+ handleFullNodePlaced() {
1055
+ import_loglevel2.default.debug(logPrefix4, "node fully paginated");
1056
+ const { parentsTraversed } = this._domState.goToNextSiblingOrParentSibling();
1057
+ for (let i = 0; i < parentsTraversed; i++) {
1058
+ this._pageManager.leaveElement();
1059
+ }
1060
+ }
1061
+ handleChildrenSplit() {
1062
+ import_loglevel2.default.debug(
1063
+ logPrefix4,
1064
+ "node partially paginated - splitting children"
1065
+ );
1066
+ if (this._domState.goToFirstChildOrNextNode().parentsTraversed === 1 && this._domState.previousNode?.type === PageNodeType.Element) {
1067
+ this._pageManager.enterElement();
1068
+ }
1069
+ }
1070
+ processCurrentNode() {
1071
+ if (!this._domState.currentNode) {
1072
+ return SplitResult.None;
1073
+ }
1074
+ if (this._domState.currentNode.type === PageNodeType.Element) {
1075
+ const ctx = {};
1076
+ callPluginHook(
1077
+ this._config.plugins,
1078
+ "onVisitElement",
1079
+ this._config.id,
1080
+ this._domState,
1081
+ this._pageManager,
1082
+ ctx
1083
+ );
1084
+ if (ctx.result !== void 0) {
1085
+ return ctx.result;
1086
+ }
1087
+ return paginateElementAcrossPages(
1088
+ this._domState.currentNode,
1089
+ this._pageManager
1090
+ );
1091
+ } else {
1092
+ const ctx = {};
1093
+ callPluginHook(
1094
+ this._config.plugins,
1095
+ "onVisitText",
1096
+ this._config.id,
1097
+ this._domState,
1098
+ this._pageManager,
1099
+ ctx
1100
+ );
1101
+ if (ctx.result !== void 0) {
1102
+ return ctx.result;
1103
+ }
1104
+ return paginateTextByWord(
1105
+ this._domState.currentNode,
1106
+ this._pageManager
1107
+ );
1108
+ }
1109
+ }
1110
+ };
1111
+
1112
+ // ../core/src/report/EventDispatcher.ts
1113
+ var EventDispatcher = class {
1114
+ registry = /* @__PURE__ */ new Map();
1115
+ addEventListener(name, handler) {
1116
+ const { registry } = this;
1117
+ const listeners = new Set(registry.get(name));
1118
+ listeners.add(handler);
1119
+ registry.set(name, listeners);
1120
+ return () => this.removeEventListener(name, handler);
1121
+ }
1122
+ removeEventListener(name, handler) {
1123
+ const { registry } = this;
1124
+ const listeners = new Set(registry.get(name));
1125
+ listeners.delete(handler);
1126
+ registry.set(name, listeners);
1127
+ }
1128
+ dispatch(name, ...args) {
1129
+ const { registry } = this;
1130
+ const listeners = registry.get(name);
1131
+ if (!listeners) {
1132
+ return;
1133
+ }
1134
+ for (const listener of listeners) {
1135
+ listener(...args);
1136
+ }
1137
+ }
1138
+ };
1139
+
1140
+ // ../core/src/report/pageConst.ts
1141
+ var pageSize = {
1142
+ /** 841mm x 594mm */
1143
+ A1: { height: "841mm", width: "594mm" },
1144
+ /** 594mm x 420mm */
1145
+ A2: { height: "594mm", width: "420mm" },
1146
+ /** 420mm x 297mm */
1147
+ A3: { height: "420mm", width: "297mm" },
1148
+ /** 297mm x 210mm */
1149
+ A4: { height: "297mm", width: "210mm" },
1150
+ /** 210mm x 148mm */
1151
+ A5: { height: "210mm", width: "148mm" },
1152
+ /** 148mm x 105mm */
1153
+ A6: { height: "148mm", width: "105mm" },
1154
+ /** 500mm x 353mm */
1155
+ B3: { height: "500mm", width: "353mm" },
1156
+ /** 353mm x 250mm */
1157
+ B4: { height: "353mm", width: "250mm" },
1158
+ /** 250mm x 176mm */
1159
+ B5: { height: "250mm", width: "176mm" },
1160
+ /** 8.5in x 11in */
1161
+ Letter: { height: "8.5in", width: "11in" },
1162
+ /** 11in x 8.5in */
1163
+ Legal: { height: "11in", width: "8.5in" },
1164
+ /** 11in x 17in */
1165
+ Tabloid: { height: "11in", width: "17in" }
1166
+ };
1167
+ var pageMargin = {
1168
+ /** Top, Right, Bottom, Left: 1in */
1169
+ Normal: {
1170
+ top: "1in",
1171
+ right: "1in",
1172
+ bottom: "1in",
1173
+ left: "1in"
1174
+ },
1175
+ /** Top: 0.4in, Right, Bottom, Left: 0.6in */
1176
+ Narrow: {
1177
+ top: "0.4in",
1178
+ right: "0.6in",
1179
+ bottom: "0.6in",
1180
+ left: "0.6in"
1181
+ },
1182
+ /** Top, Bottom: 0.5in, Right, Left: 2in */
1183
+ Wide: {
1184
+ top: "0.5in",
1185
+ right: "2in",
1186
+ bottom: "0.5in",
1187
+ left: "2in"
1188
+ },
1189
+ /** Top, Right, Bottom, Left: 0 */
1190
+ None: {
1191
+ top: "0in",
1192
+ right: "0in",
1193
+ bottom: "0in",
1194
+ left: "0in"
1195
+ }
1196
+ };
1197
+
1198
+ // ../core/src/report/utils.ts
1199
+ function getVisibleSize(element) {
1200
+ const rect = element.getBoundingClientRect();
1201
+ const computedStyle = getComputedStyle(element);
1202
+ const marginLeft = parseFloat(computedStyle.marginLeft) || 0;
1203
+ const marginRight = parseFloat(computedStyle.marginRight) || 0;
1204
+ return {
1205
+ height: getVisibleHeight(element),
1206
+ width: rect.width + marginLeft + marginRight
1207
+ };
1208
+ }
1209
+ function calculatePageSizes(current, sectionHeader, sectionFooter) {
1210
+ const { height, width } = getVisibleSize(current);
1211
+ const sectionHeaderHeight = sectionHeader ? getVisibleHeight(sectionHeader) : 0;
1212
+ const sectionFooterHeight = sectionFooter ? getVisibleHeight(sectionFooter) : 0;
1213
+ return { height, width, sectionHeaderHeight, sectionFooterHeight };
1214
+ }
1215
+ function createSectionPageHeightPlugin(height, sectionHeaderHeight, sectionFooterHeight) {
1216
+ return {
1217
+ name: "sectionPageHeight",
1218
+ order: 1,
1219
+ afterVisitNode: (_id, _result, domState, pageManager) => {
1220
+ const lastPage = domState.completed;
1221
+ if (!lastPage || sectionFooterHeight <= 0) return;
1222
+ if (!pageManager.hasEmptySpace(sectionFooterHeight)) {
1223
+ pageManager.nextPage();
1224
+ }
1225
+ },
1226
+ onNewPage: (_, pageManager) => {
1227
+ const pageState = pageManager.getPageState();
1228
+ if (pageState.pageIndex === 0) {
1229
+ pageState.pageHeight = height + sectionFooterHeight;
1230
+ } else {
1231
+ pageState.pageHeight = height + sectionHeaderHeight + sectionFooterHeight;
1232
+ }
1233
+ }
1234
+ };
1235
+ }
1236
+ function shorthand(margin) {
1237
+ return margin ? `${margin.top} ${margin.right} ${margin.bottom} ${margin.left}` : "0";
1238
+ }
1239
+
1240
+ // ../core/src/report/reportStyles.ts
1241
+ var globalStyle = `
1242
+ html {
1243
+ box-sizing: border-box;
1244
+ }
1245
+
1246
+ *,
1247
+ *:before,
1248
+ *:after {
1249
+ box-sizing: inherit;
1250
+ }
1251
+
1252
+ :root {
1253
+ --paprize-page-background-color: #ffffff;
1254
+ --paprize-page-margin-bottom: 10px;
1255
+ --paprize-page-box-shadow: rgb(142 138 138) -1px 3px 5px 2px;
1256
+ --paprize-section-margin-bottom: 10px;
1257
+ --paprize-preview-background-color: rgb(218 220 224);
1258
+ --paprize-preview-padding: 30px 10px;
1259
+ }
1260
+
1261
+ body {
1262
+ margin: 0;
1263
+ }
1264
+
1265
+ @media screen {
1266
+ .${previewClassName} {
1267
+ min-height: 100vh;
1268
+ display: flex;
1269
+ flex-direction: column;
1270
+ align-items: center;
1271
+ background-color: var(--paprize-preview-background-color);
1272
+ padding: var(--paprize-preview-padding);
1273
+ }
1274
+
1275
+ .${pageClassName} {
1276
+ box-shadow: var(--paprize-page-box-shadow);
1277
+ margin-bottom: var(--paprize-page-margin-bottom);
1278
+ background-color: var(--paprize-page-background-color);
1279
+ }
1280
+
1281
+ .${sectionClassName} {
1282
+ margin-bottom: var(--paprize-section-margin-bottom);
1283
+ }
1284
+ }
1285
+
1286
+ @media print {
1287
+ html:has(.${previewClassName}) *:not(.${previewClassName}):not(.${previewClassName} *):not(:has(.${previewClassName})) {
1288
+ display: none !important;
1289
+ }
1290
+ }
1291
+ `;
1292
+ var component = {
1293
+ display: "flex",
1294
+ flexDirection: "column"
1295
+ };
1296
+ var outOfScreen = {
1297
+ position: "absolute",
1298
+ left: "-9999px",
1299
+ top: "-9999px",
1300
+ visibility: "hidden"
1301
+ };
1302
+ var page = (pageSize2, pageMargin2) => ({
1303
+ display: "flex",
1304
+ flexDirection: "column",
1305
+ width: pageSize2.width,
1306
+ height: pageSize2.height,
1307
+ maxHeight: pageSize2.height,
1308
+ position: "relative",
1309
+ padding: shorthand(pageMargin2),
1310
+ zIndex: "1"
1311
+ });
1312
+ var pageContent = {
1313
+ overflow: "hidden",
1314
+ width: "100%",
1315
+ height: "100%"
1316
+ };
1317
+ var overlay = {
1318
+ position: "absolute",
1319
+ width: "100%",
1320
+ height: "100%",
1321
+ left: 0,
1322
+ top: 0
1323
+ };
1324
+ var section = (sectionId2) => ({
1325
+ page: `section-${sectionId2}`
1326
+ });
1327
+ function sectionPageMedia(sectionId2, size) {
1328
+ return `@page section-${sectionId2} {
1329
+ margin: none;
1330
+ size:${size.width} ${size.height};
1331
+ width:${size.width};
1332
+ height:${size.height};
1333
+ }`;
1334
+ }
1335
+ var reportStyles = {
1336
+ globalStyle,
1337
+ component,
1338
+ outOfScreen,
1339
+ page,
1340
+ overlay,
1341
+ pageContent,
1342
+ sectionPageMedia,
1343
+ section
1344
+ };
1345
+
1346
+ // ../core/src/report/sectionComponents.ts
1347
+ function cloneElement(element) {
1348
+ return element?.cloneNode(true) ?? null;
1349
+ }
1350
+ function cloneComponents(components) {
1351
+ return {
1352
+ sectionHeader: cloneElement(components.sectionHeader),
1353
+ sectionFooter: cloneElement(components.sectionFooter),
1354
+ pageHeader: cloneElement(components.pageHeader),
1355
+ pageFooter: cloneElement(components.pageFooter),
1356
+ pageContent: cloneElement(components.pageContent)
1357
+ };
1358
+ }
1359
+
1360
+ // ../core/src/plugins/PageBreakPlugin.ts
1361
+ var pageBreakAttributeName = "data-pz-page-break";
1362
+ var PageBreakPlugin = class {
1363
+ name = "pageBreak";
1364
+ order = 1;
1365
+ onVisitElement = (_id, domState, pageManager, context) => {
1366
+ if (domState.currentNode.getNode().getAttribute(pageBreakAttributeName) === "true") {
1367
+ pageManager.markPageAsFull();
1368
+ context.result = SplitResult.FullNodePlaced;
1369
+ }
1370
+ };
1371
+ };
1372
+
1373
+ // ../core/src/plugins/TablePlugin.ts
1374
+ var TablePlugin = class {
1375
+ _options = {};
1376
+ name = "table";
1377
+ order = 1;
1378
+ constructor(options = {}) {
1379
+ this._options = options;
1380
+ }
1381
+ onNewPage = (_id, pageManager) => {
1382
+ if (this._options.includeHeaderOnlyTables) {
1383
+ return;
1384
+ }
1385
+ const pageState = pageManager.getPageState();
1386
+ const tableElement = pageState.parentStack.find(
1387
+ (node) => this._isTable(node.getNode())
1388
+ );
1389
+ if (!tableElement || !tableElement.clonedFrom) {
1390
+ return;
1391
+ }
1392
+ const openTable = tableElement.clonedFrom;
1393
+ const openTableNode = openTable.getNode();
1394
+ const header = openTableNode.tHead;
1395
+ const hasHeader = header !== null;
1396
+ if (!hasHeader) {
1397
+ return;
1398
+ }
1399
+ const body = openTableNode.tBodies;
1400
+ if (!this._isTableBodyEmpty(body)) {
1401
+ return;
1402
+ }
1403
+ openTable.remove();
1404
+ const newTable = tableElement.getNode();
1405
+ if (newTable.tHead === null) {
1406
+ const headerNode = createPageNode(
1407
+ header.cloneNode(true),
1408
+ tableElement.transaction,
1409
+ tableElement.config
1410
+ );
1411
+ tableElement.appendChild(headerNode);
1412
+ }
1413
+ };
1414
+ onClone = (_id, source, cloned) => {
1415
+ if (source.tagName === "TR") {
1416
+ cloned.config.keepOnSamePage = true;
1417
+ return;
1418
+ }
1419
+ if (!this._isTable(source) || !cloned.clonedFrom || cloned.cloneCount === 1) {
1420
+ return;
1421
+ }
1422
+ const originalNode = cloned.getOriginalNode();
1423
+ const head = originalNode.tHead;
1424
+ if (head && this._options.cloneHeader === true) {
1425
+ const clonedHead = new PageElement(
1426
+ head.cloneNode(true),
1427
+ cloned.transaction,
1428
+ cloned.config
1429
+ );
1430
+ cloned.appendChild(clonedHead);
1431
+ }
1432
+ const foot = originalNode.tFoot;
1433
+ if (foot && this._options.cloneFooter === true) {
1434
+ const clonedFoot = new PageElement(
1435
+ foot.cloneNode(true),
1436
+ cloned.transaction,
1437
+ cloned.config
1438
+ );
1439
+ cloned.appendChild(clonedFoot);
1440
+ }
1441
+ };
1442
+ _isTable(element) {
1443
+ return element.tagName === "TABLE";
1444
+ }
1445
+ _isTableBodyEmpty(body) {
1446
+ if (body.length === 0) return true;
1447
+ const tbody = body[0];
1448
+ if (tbody.rows.length !== 1) return false;
1449
+ const row = tbody.rows[0];
1450
+ if (row.cells.length !== 1) return false;
1451
+ const cell = row.cells[0];
1452
+ return cell.textContent.trim() === "";
1453
+ }
1454
+ };
1455
+
1456
+ // ../core/src/plugins/defaultPlugins.ts
1457
+ var defaultPlugins = [
1458
+ new PageBreakPlugin(),
1459
+ new TablePlugin()
1460
+ ];
1461
+
1462
+ // ../core/src/plugins/debugPlugin.ts
1463
+ var debugPlugin = {
1464
+ name: "debug",
1465
+ order: Number.MAX_SAFE_INTEGER,
1466
+ onNewPage: (_, pageManager) => {
1467
+ const page2 = pageManager.getPageState().currentPage.getNode();
1468
+ if (!page2.classList.contains(pageClassName)) {
1469
+ page2.classList.add(pageClassName);
1470
+ }
1471
+ page2.setAttribute(`${attributePrefix}-element`, "page");
1472
+ page2.setAttribute(
1473
+ `${attributePrefix}-height`,
1474
+ pageManager.getPageState().pageHeight.toString()
1475
+ );
1476
+ }
1477
+ };
1478
+
1479
+ // ../core/src/window.ts
1480
+ var paprize_isInitialized = "__PAPRIZE_IS_INITIALIZED";
1481
+ var paprize_isReady = "__PAPRIZE_IS_READY";
1482
+
1483
+ // ../core/src/report/PromiseTracker.ts
1484
+ var PromiseTracker = class _PromiseTracker {
1485
+ _promises;
1486
+ monitor;
1487
+ get promise() {
1488
+ return this._promises.length > 0 ? Promise.allSettled(this._promises.map((p) => p.promise)).then(
1489
+ () => {
1490
+ }
1491
+ ) : Promise.resolve();
1492
+ }
1493
+ constructor() {
1494
+ this._promises = [];
1495
+ this.monitor = new EventDispatcher();
1496
+ }
1497
+ async add(promises = []) {
1498
+ this._promises.push(...promises.map(_PromiseTracker.toTracked));
1499
+ await new Promise((resolve) => setTimeout(resolve, 0));
1500
+ if (this.getPending().length === 0) {
1501
+ this.monitor.dispatch("onChange", 0);
1502
+ return;
1503
+ }
1504
+ this._promises.forEach((p) => this.injectEvents(p));
1505
+ }
1506
+ static toTracked(promise) {
1507
+ const tracked = {
1508
+ promise,
1509
+ status: "pending"
1510
+ };
1511
+ tracked.promise.finally(() => {
1512
+ tracked.status = "resolved";
1513
+ });
1514
+ return tracked;
1515
+ }
1516
+ async injectEvents(tracked) {
1517
+ tracked.promise.finally(() => {
1518
+ const pending = this.getPending();
1519
+ this.monitor.dispatch("onChange", pending.length);
1520
+ });
1521
+ }
1522
+ getPending() {
1523
+ return Array.from(this._promises.values()).filter(
1524
+ (p) => p.status === "pending"
1525
+ );
1526
+ }
1527
+ };
1528
+
1529
+ // ../core/src/utils.ts
1530
+ function buildPageId(sectionId2, pageIndex) {
1531
+ return `${sectionId2}-${pageIndex + 1}`;
1532
+ }
1533
+ function adjustPageSize(size, orientation) {
1534
+ if (orientation === "landscape") {
1535
+ return { height: size.width, width: size.height };
1536
+ }
1537
+ return size;
1538
+ }
1539
+
1540
+ // ../core/src/report/ReportBuilder.ts
1541
+ var logPrefix5 = "\x1B[43mREPORT\x1B[0m";
1542
+ var ReportBuilder = class {
1543
+ _sections;
1544
+ _monitor;
1545
+ _paginationInProgress;
1546
+ _pendingPaginateResolvers;
1547
+ _currentAbortController;
1548
+ constructor() {
1549
+ this._sections = /* @__PURE__ */ new Map();
1550
+ this._monitor = new EventDispatcher();
1551
+ this._paginationInProgress = false;
1552
+ this._pendingPaginateResolvers = [];
1553
+ this._currentAbortController = null;
1554
+ window[paprize_isInitialized] = true;
1555
+ this._injectStyle(reportStyles.globalStyle);
1556
+ }
1557
+ /**
1558
+ * Monitor instance used to subscribe to pagination events.
1559
+ * See {@link ReportBuilderEvents} for available event types.
1560
+ */
1561
+ get monitor() {
1562
+ return this._monitor;
1563
+ }
1564
+ /**
1565
+ * Removes a section from the registered sections, if it has already been registered in the report.
1566
+ */
1567
+ removeSection(sectionId2) {
1568
+ this._sections.delete(sectionId2);
1569
+ }
1570
+ /**
1571
+ * Registers a section by its ID, specifying the page size, margins, and other options.
1572
+ *
1573
+ * @param options - Configuration options for the section.
1574
+ * @param components - The DOM components associated with the section.
1575
+ * @param onPaginationCompleted - Callback invoked when pagination for the section is completed.
1576
+ * @returns `true` if the section was added to the report’s section list, or `false` if it already exists.
1577
+ */
1578
+ tryAddSection(options, components, onPaginationCompleted) {
1579
+ if (this._sections.has(options.id)) {
1580
+ return false;
1581
+ }
1582
+ const context = {
1583
+ sectionIndex: this._sections.size,
1584
+ sectionId: options.id,
1585
+ isPaginated: false,
1586
+ isSuspended: !!options.suspense?.length,
1587
+ pages: []
1588
+ };
1589
+ this._sections.set(options.id, {
1590
+ context,
1591
+ options: {
1592
+ ...options,
1593
+ size: adjustPageSize(
1594
+ options.size,
1595
+ options.orientation ?? "portrait"
1596
+ )
1597
+ },
1598
+ components,
1599
+ onPaginationCompleted
1600
+ });
1601
+ this._injectStyle(
1602
+ reportStyles.sectionPageMedia(options.id, options.size)
1603
+ );
1604
+ this._monitor.dispatch("sectionCreated", context);
1605
+ return true;
1606
+ }
1607
+ /**
1608
+ * Schedules a pagination operation.
1609
+ *
1610
+ * It is not possible to schedule multiple pagination operations in parallel,
1611
+ * as the process involves DOM manipulation, and concurrent modifications
1612
+ * could cause conflicts and unexpected results.
1613
+ * Each newly scheduled operation is queued and executed sequentially.
1614
+ * When a new pagination is scheduled, any ongoing or pending operations
1615
+ * will be aborted, and the new pagination will start immediately afterward.
1616
+ *
1617
+ * @returns A promise that resolves when the first pagination cycle is completed.
1618
+ * It does not wait for suspended sections to resolve and be paginated.
1619
+ * To wait for all sections to complete pagination, use the
1620
+ * `suspension` property of the returned result object.
1621
+ */
1622
+ async schedulePagination() {
1623
+ if (this._sections.size === 0) {
1624
+ window[paprize_isReady] = true;
1625
+ return {
1626
+ sections: [],
1627
+ suspension: Promise.resolve()
1628
+ };
1629
+ }
1630
+ if (this._paginationInProgress && this._currentAbortController) {
1631
+ logger_default.debug(
1632
+ logPrefix5,
1633
+ `Cancelling previous pagination operation.`
1634
+ );
1635
+ this._currentAbortController.abort(
1636
+ "Cancelled by new paginate call"
1637
+ );
1638
+ }
1639
+ if (this._paginationInProgress) {
1640
+ return new Promise((resolve, reject) => {
1641
+ this._pendingPaginateResolvers.push({ resolve, reject });
1642
+ });
1643
+ }
1644
+ return this._executePagination();
1645
+ }
1646
+ async _executePagination() {
1647
+ this._paginationInProgress = true;
1648
+ this._currentAbortController = new AbortController();
1649
+ const abortSignal = this._currentAbortController.signal;
1650
+ try {
1651
+ logger_default.debug(logPrefix5, `Schedule paginate.`);
1652
+ await document.fonts.ready;
1653
+ if (abortSignal.aborted) {
1654
+ return new Promise((resolve, reject) => {
1655
+ this._pendingPaginateResolvers.push({ resolve, reject });
1656
+ });
1657
+ }
1658
+ const trackers = [];
1659
+ for (const state of this._sections.values()) {
1660
+ state.context.isPaginated = false;
1661
+ const tracker = new PromiseTracker();
1662
+ await tracker.add(state.options.suspense);
1663
+ tracker.monitor.addEventListener("onChange", (pendingCount) => {
1664
+ logger_default.debug(
1665
+ logPrefix5,
1666
+ `${pendingCount} pending promises in section '${state.options.id}'.`
1667
+ );
1668
+ });
1669
+ tracker.promise.then(async () => {
1670
+ if (abortSignal.aborted) {
1671
+ return;
1672
+ }
1673
+ logger_default.debug(
1674
+ logPrefix5,
1675
+ `Start paginating section '${state.options.id}'.`
1676
+ );
1677
+ state.context.isSuspended = false;
1678
+ this._paginateSection(state);
1679
+ });
1680
+ trackers.push(tracker);
1681
+ }
1682
+ const reportTracker = new PromiseTracker();
1683
+ reportTracker.monitor.addEventListener("onChange", () => {
1684
+ logger_default.debug(logPrefix5, "Report pagination completed.");
1685
+ this._monitor.dispatch("paginationCycleCompleted", {
1686
+ sections: [...this._sections.values()].map(
1687
+ (s) => s.context
1688
+ )
1689
+ });
1690
+ });
1691
+ if (abortSignal.aborted) {
1692
+ return new Promise((resolve, reject) => {
1693
+ this._pendingPaginateResolvers.push({ resolve, reject });
1694
+ });
1695
+ }
1696
+ await reportTracker.add(trackers.map((t) => t.promise));
1697
+ return {
1698
+ sections: [...this._sections.values()].map((s) => s.context),
1699
+ suspension: reportTracker.promise.then(() => {
1700
+ window[paprize_isReady] = true;
1701
+ })
1702
+ };
1703
+ } finally {
1704
+ this._processPendingPagination();
1705
+ this._paginationInProgress = false;
1706
+ this._currentAbortController = null;
1707
+ }
1708
+ }
1709
+ async _processPendingPagination() {
1710
+ if (this._pendingPaginateResolvers.length === 0) {
1711
+ return;
1712
+ }
1713
+ logger_default.debug(
1714
+ logPrefix5,
1715
+ `Processing ${this._pendingPaginateResolvers.length} pending paginate calls.`
1716
+ );
1717
+ const pendingResolvers = [...this._pendingPaginateResolvers];
1718
+ this._pendingPaginateResolvers = [];
1719
+ const nextResult = await this._executePagination();
1720
+ for (const resolver of pendingResolvers) {
1721
+ resolver.resolve(nextResult);
1722
+ }
1723
+ }
1724
+ _injectStyle(styleContent) {
1725
+ let style = document.getElementById(
1726
+ globalStyleId
1727
+ );
1728
+ if (!style) {
1729
+ style = document.createElement("style");
1730
+ style.id = globalStyleId;
1731
+ style.textContent = "";
1732
+ document.head.appendChild(style);
1733
+ }
1734
+ style.textContent = (style.textContent + styleContent).replace(/\s+/g, " ").replace(/\s*([:;{}])\s*/g, "$1").trim();
1735
+ }
1736
+ async _paginateSection(state) {
1737
+ const temporarilyContainer = document.createElement("div");
1738
+ Object.assign(
1739
+ temporarilyContainer.style,
1740
+ reportStyles.page(
1741
+ state.options.size,
1742
+ state.options.margin ?? pageMargin.None
1743
+ )
1744
+ );
1745
+ if (!isDebugMode()) {
1746
+ Object.assign(temporarilyContainer.style, reportStyles.outOfScreen);
1747
+ }
1748
+ const components = cloneComponents(state.components);
1749
+ if (components.sectionHeader) {
1750
+ Object.assign(
1751
+ components.sectionHeader.style,
1752
+ reportStyles.component
1753
+ );
1754
+ temporarilyContainer.appendChild(components.sectionHeader);
1755
+ }
1756
+ if (components.pageHeader) {
1757
+ Object.assign(components.pageHeader.style, reportStyles.component);
1758
+ temporarilyContainer.appendChild(components.pageHeader);
1759
+ }
1760
+ Object.assign(components.pageContent.style, reportStyles.pageContent);
1761
+ temporarilyContainer.appendChild(components.pageContent);
1762
+ if (components.pageFooter) {
1763
+ Object.assign(components.pageFooter.style, reportStyles.component);
1764
+ temporarilyContainer.appendChild(components.pageFooter);
1765
+ }
1766
+ if (components.sectionFooter) {
1767
+ Object.assign(
1768
+ components.sectionFooter.style,
1769
+ reportStyles.component
1770
+ );
1771
+ temporarilyContainer.appendChild(components.sectionFooter);
1772
+ }
1773
+ document.body.appendChild(temporarilyContainer);
1774
+ const { height, width, sectionHeaderHeight, sectionFooterHeight } = calculatePageSizes(
1775
+ components.pageContent,
1776
+ components.sectionHeader,
1777
+ components.sectionFooter
1778
+ );
1779
+ const paginatorResult = Paginator.paginate(
1780
+ components.pageContent,
1781
+ { height, width },
1782
+ {
1783
+ id: state.options.id,
1784
+ plugins: [
1785
+ ...state.options.plugins ?? defaultPlugins,
1786
+ createSectionPageHeightPlugin(
1787
+ height,
1788
+ sectionHeaderHeight,
1789
+ sectionFooterHeight
1790
+ )
1791
+ ]
1792
+ }
1793
+ );
1794
+ temporarilyContainer.remove();
1795
+ const pageContexts = paginatorResult.map((content, index) => ({
1796
+ pageIndex: index,
1797
+ totalPages: paginatorResult.length,
1798
+ sectionId: state.options.id,
1799
+ pageContentHtml: content
1800
+ }));
1801
+ state.onPaginationCompleted(pageContexts);
1802
+ for (const pageContext of pageContexts) {
1803
+ this._monitor.dispatch("pageCompleted", pageContext);
1804
+ }
1805
+ const sectionContext = {
1806
+ ...state.context,
1807
+ isPaginated: true,
1808
+ isSuspended: false,
1809
+ pages: pageContexts
1810
+ };
1811
+ this._sections.set(state.options.id, {
1812
+ ...state,
1813
+ context: sectionContext
1814
+ });
1815
+ this._monitor.dispatch("sectionCompleted", sectionContext);
1816
+ }
1817
+ };
1818
+
1819
+ // ../vanilla/src/attributes.ts
1820
+ var sectionAttribute = `${attributePrefix}section`;
1821
+ var previewAttribute = `${attributePrefix}preview`;
1822
+ var sectionHeaderAttribute = `${attributePrefix}section-header`;
1823
+ var sectionFooterAttribute = `${attributePrefix}section-footer`;
1824
+ var pageHeaderAttribute = `${attributePrefix}page-header`;
1825
+ var pageFooterAttribute = `${attributePrefix}page-footer`;
1826
+ var pageContentAttribute = `${attributePrefix}page-content`;
1827
+ var pageOverlayAttribute = `${attributePrefix}page-overlay`;
1828
+ var sectionIdMetadataAttribute = `${attributePrefix}section-id`;
1829
+ var pageIndexMetadataAttribute = `${attributePrefix}page-index`;
1830
+ var pageNumberValueAttribute = `${attributePrefix}v-page-number`;
1831
+ var totalPagesValueAttribute = `${attributePrefix}v-total-pages`;
1832
+ var sectionNumberValueAttribute = `${attributePrefix}v-section-number`;
1833
+ var totalSectionsValueAttribute = `${attributePrefix}v-total-sections`;
1834
+
1835
+ // ../vanilla/src/PaprizeReport.ts
1836
+ var globalStyles = `
1837
+ [${sectionAttribute}=true] {
1838
+ display: none;
1839
+ }
1840
+ `;
1841
+ var PaprizeReport = class {
1842
+ _sections = /* @__PURE__ */ new Map();
1843
+ _reportManager;
1844
+ _monitor;
1845
+ _root;
1846
+ _options;
1847
+ /** @public */
1848
+ constructor(options) {
1849
+ const style = document.createElement("style");
1850
+ style.textContent = globalStyles;
1851
+ document.head.appendChild(style);
1852
+ this._options = options ?? {};
1853
+ this._monitor = new EventDispatcher();
1854
+ this._reportManager = new ReportBuilder();
1855
+ this._root = this._createRootElement();
1856
+ this._reportManager.monitor.addEventListener(
1857
+ "sectionCreated",
1858
+ (event) => {
1859
+ this._monitor.dispatch("sectionCreated", {
1860
+ ...event,
1861
+ pages: []
1862
+ });
1863
+ }
1864
+ );
1865
+ this._reportManager.monitor.addEventListener(
1866
+ "sectionCompleted",
1867
+ (event) => {
1868
+ const pages = this._getSectionState(event.sectionId).pages;
1869
+ this._monitor.dispatch("sectionCompleted", {
1870
+ ...event,
1871
+ pages: pages ?? []
1872
+ });
1873
+ }
1874
+ );
1875
+ this._reportManager.monitor.addEventListener(
1876
+ "pageCompleted",
1877
+ (event) => {
1878
+ const pages = this._getSectionState(event.sectionId).pages;
1879
+ this._monitor.dispatch("pageCompleted", pages[event.pageIndex]);
1880
+ }
1881
+ );
1882
+ this._reportManager.monitor.addEventListener(
1883
+ "paginationCycleCompleted",
1884
+ (event) => {
1885
+ this._monitor.dispatch("paginationCycleCompleted", {
1886
+ sections: event.sections.map((s) => ({
1887
+ ...s,
1888
+ pages: this._sections.get(s.sectionId)?.pages ?? []
1889
+ }))
1890
+ });
1891
+ }
1892
+ );
1893
+ }
1894
+ _createRootElement() {
1895
+ const wrapper = document.createElement("div");
1896
+ if (document.querySelector(`[${previewAttribute}]`)) {
1897
+ wrapper.classList.add(previewClassName);
1898
+ }
1899
+ (this._options.root ?? document.body).appendChild(wrapper);
1900
+ return wrapper;
1901
+ }
1902
+ /**
1903
+ * {@inheritDoc @paprize/core!ReportBuilder.schedulePagination}
1904
+ */
1905
+ async schedulePagination() {
1906
+ const result = await this._reportManager.schedulePagination();
1907
+ return {
1908
+ suspension: result.suspension,
1909
+ sections: result.sections.map((s) => ({
1910
+ ...s,
1911
+ pages: this._sections.get(s.sectionId)?.pages ?? []
1912
+ }))
1913
+ };
1914
+ }
1915
+ /**
1916
+ * Monitor instance used to subscribe to pagination events.
1917
+ * See {@link PaprizeReportEvents} for available event types.
1918
+ */
1919
+ get monitor() {
1920
+ return this._monitor;
1921
+ }
1922
+ /**
1923
+ * Registers a section by its id, specifying the page size, margins, and other options.
1924
+ * If a section with the same id already exists, the operation will be ignored.
1925
+ * @param options - Configuration options for the section.
1926
+ */
1927
+ addSection(options) {
1928
+ if (this._sections.has(options.id)) {
1929
+ return this;
1930
+ }
1931
+ const section2 = document.getElementById(options.id);
1932
+ if (!section2) {
1933
+ throw new Error(
1934
+ `Section with id ${options.id} not found in the DOM.`
1935
+ );
1936
+ }
1937
+ const components = this._getSectionComponents(section2);
1938
+ const sectionElement = this._createSectionInDom(options.id);
1939
+ const result = this._reportManager.tryAddSection(
1940
+ options,
1941
+ components,
1942
+ (pageContexts) => {
1943
+ this._renderSection(options, pageContexts);
1944
+ }
1945
+ );
1946
+ if (!result) {
1947
+ this._root.removeChild(sectionElement);
1948
+ logger_default.error(
1949
+ `Section with id ${options.id} already exists in the report manager.`
1950
+ );
1951
+ return this;
1952
+ }
1953
+ this._sections.set(options.id, {
1954
+ pages: [],
1955
+ sectionElement,
1956
+ components,
1957
+ options
1958
+ });
1959
+ return this;
1960
+ }
1961
+ _getSectionState(id) {
1962
+ const state = this._sections.get(id);
1963
+ if (!state) {
1964
+ throw new Error(`Section with id ${id} not found in the report.`);
1965
+ }
1966
+ return state;
1967
+ }
1968
+ _createSectionInDom(sectionId2) {
1969
+ const section2 = document.createElement("div");
1970
+ section2.setAttribute(sectionIdMetadataAttribute, sectionId2);
1971
+ section2.classList.add(sectionClassName);
1972
+ section2.id = sectionId2;
1973
+ Object.assign(section2.style, reportStyles.section(sectionId2));
1974
+ this._root.appendChild(section2);
1975
+ return section2;
1976
+ }
1977
+ _getSectionComponents(section2) {
1978
+ const pageContent2 = section2.querySelector(
1979
+ `[${pageContentAttribute}]`
1980
+ );
1981
+ if (!pageContent2) {
1982
+ throw new Error(
1983
+ `Page content not found in section with id ${section2.id}`
1984
+ );
1985
+ }
1986
+ return {
1987
+ sectionHeader: section2.querySelector(
1988
+ `[${sectionHeaderAttribute}]`
1989
+ ),
1990
+ sectionFooter: section2.querySelector(
1991
+ `[${sectionFooterAttribute}]`
1992
+ ),
1993
+ pageHeader: section2.querySelector(
1994
+ `[${pageHeaderAttribute}]`
1995
+ ),
1996
+ pageFooter: section2.querySelector(
1997
+ `[${pageFooterAttribute}]`
1998
+ ),
1999
+ pageContent: pageContent2
2000
+ };
2001
+ }
2002
+ async _renderSection(options, pageContexts) {
2003
+ const state = this._getSectionState(options.id);
2004
+ if (!this._options.keepInitialElementAfterPagination) {
2005
+ document.getElementById(options.id)?.remove();
2006
+ }
2007
+ const pages = [];
2008
+ for (const pageContext of pageContexts) {
2009
+ const page2 = document.createElement("div");
2010
+ page2.classList.add(pageClassName);
2011
+ page2.id = buildPageId(options.id, pageContext.pageIndex);
2012
+ page2.setAttribute(
2013
+ pageIndexMetadataAttribute,
2014
+ pageContext.pageIndex.toString()
2015
+ );
2016
+ Object.assign(
2017
+ page2.style,
2018
+ reportStyles.page(
2019
+ options.size,
2020
+ options.margin ?? pageMargin.None
2021
+ )
2022
+ );
2023
+ const components = cloneComponents(state.components);
2024
+ if (pageContext.pageIndex === 0 && components.sectionHeader) {
2025
+ page2.appendChild(components.sectionHeader);
2026
+ }
2027
+ if (components.pageHeader) {
2028
+ page2.appendChild(components.pageHeader);
2029
+ }
2030
+ const pageContent2 = document.createElement("div");
2031
+ pageContent2.innerHTML = pageContext.pageContentHtml;
2032
+ page2.appendChild(pageContent2);
2033
+ const pageFooterContainer = document.createElement("div");
2034
+ pageFooterContainer.style.marginTop = "auto";
2035
+ if (components.pageFooter) {
2036
+ pageFooterContainer.appendChild(components.pageFooter);
2037
+ }
2038
+ if (pageContext.pageIndex === pageContexts.length - 1 && components.sectionFooter) {
2039
+ pageFooterContainer.appendChild(
2040
+ components.sectionFooter.cloneNode(true)
2041
+ );
2042
+ }
2043
+ if (pageFooterContainer.children.length > 0) {
2044
+ page2.appendChild(pageFooterContainer);
2045
+ }
2046
+ this._replaceContentInfoValues(
2047
+ { ...components, pageContent: pageContent2 },
2048
+ pageContext
2049
+ );
2050
+ state.sectionElement.appendChild(page2);
2051
+ const domPageContext = {
2052
+ sectionId: options.id,
2053
+ pageIndex: pageContext.pageIndex,
2054
+ totalPages: pageContexts.length,
2055
+ page: page2,
2056
+ components: { ...components, pageContent: pageContent2 }
2057
+ };
2058
+ pages.push(domPageContext);
2059
+ }
2060
+ this._sections.set(options.id, {
2061
+ ...state,
2062
+ pages
2063
+ });
2064
+ }
2065
+ _replaceContentInfoValues(components, pageContext) {
2066
+ for (const component2 of Object.values(components)) {
2067
+ if (!component2) continue;
2068
+ component2.querySelectorAll(`[${pageNumberValueAttribute}]`).forEach((el) => {
2069
+ el.textContent = (pageContext.pageIndex + 1).toString();
2070
+ });
2071
+ component2.querySelectorAll(`[${totalPagesValueAttribute}]`).forEach((el) => {
2072
+ el.textContent = pageContext.totalPages.toString();
2073
+ });
2074
+ component2.querySelectorAll(`[${sectionNumberValueAttribute}]`).forEach((el) => {
2075
+ el.textContent = (Array.from(this._sections.keys()).indexOf(
2076
+ pageContext.sectionId
2077
+ ) + 1).toString();
2078
+ });
2079
+ component2.querySelectorAll(`[${totalSectionsValueAttribute}]`).forEach((el) => {
2080
+ el.textContent = this._sections.size.toString();
2081
+ });
2082
+ }
2083
+ }
2084
+ };
2085
+
2086
+ // src/zeroReport.ts
2087
+ var sectionPageSizeAttribute = `${attributePrefix}section-page-size`;
2088
+ var sectionPageMarginAttribute = `${attributePrefix}section-page-margin`;
2089
+ function parsePageSizeAttribute(section2) {
2090
+ const sizeAttributeValue = section2.getAttribute(sectionPageSizeAttribute);
2091
+ console.warn(
2092
+ "ss",
2093
+ sizeAttributeValue,
2094
+ section2.getAttributeNames().join(","),
2095
+ sectionPageSizeAttribute,
2096
+ section2.getAttribute("data-pz-section-page-size")
2097
+ );
2098
+ const size = Object.entries(pageSize).find(
2099
+ ([key]) => key.toLowerCase() === sizeAttributeValue?.toLowerCase()
2100
+ )?.[1];
2101
+ return size ?? pageSize.A4;
2102
+ }
2103
+ function parsePageMarginAttribute(section2) {
2104
+ const size = section2.getAttribute(sectionPageMarginAttribute);
2105
+ const margin = Object.entries(pageMargin).find(
2106
+ ([key]) => key.toLowerCase() === size?.toLowerCase()
2107
+ )?.[1];
2108
+ return margin ?? pageMargin.Narrow;
2109
+ }
2110
+ var sectionId = 1;
2111
+ var report = new PaprizeReport();
2112
+ document.querySelectorAll(`[${sectionAttribute}]`).forEach((el) => {
2113
+ const id = el.id || `section-${sectionId++}`;
2114
+ if (!el.id) {
2115
+ el.id = id;
2116
+ }
2117
+ report.addSection({
2118
+ size: parsePageSizeAttribute(el),
2119
+ margin: parsePageMarginAttribute(el),
2120
+ id
2121
+ });
2122
+ });
2123
+ report.schedulePagination();
2124
+ export {
2125
+ sectionPageMarginAttribute,
2126
+ sectionPageSizeAttribute
2127
+ };
2128
+ //# sourceMappingURL=paprize-zero.js.map