@paprize/core 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,8 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # Paprize
2
+
3
+ Design your report using the full power of JavaScript and CSS, mark the report section by paprize components and then paprize pagination engine will transforming it into a beautiful, professional, print-ready pages.
4
+
5
+ ![Components](https://raw.githubusercontent.com/PejmanNik/paprize/refs/heads/bootstrap/packages/website/static/img/components.svg)
@@ -0,0 +1,232 @@
1
+ import { default as default_2 } from 'loglevel';
2
+
3
+ declare const AttributeDef: {
4
+ hyphen: AttributeValueDef<string>;
5
+ keepOnSamePage: AttributeValueDef<boolean>;
6
+ hyphenationEnabled: AttributeValueDef<boolean>;
7
+ };
8
+
9
+ declare type AttributeKey = keyof typeof AttributeDef;
10
+
11
+ export declare const attributePrefix = "data-pz-";
12
+
13
+ declare type AttributeValue<K extends AttributeKey> = (typeof AttributeDef)[K] extends AttributeValueDef<infer R> ? R : never;
14
+
15
+ declare class AttributeValueDef<T> {
16
+ name: string;
17
+ defaultValue: T;
18
+ private _reader;
19
+ constructor(name: string, reader: (value: string) => T, defaultValue: T);
20
+ read(value: string): T;
21
+ static createStr(name: string, defaultValue: string): AttributeValueDef<string>;
22
+ static createBool(name: string, defaultValue: boolean): AttributeValueDef<boolean>;
23
+ }
24
+
25
+ export declare function callPluginHook<T extends PluginHookNames>(plugins: PaginationPlugin[], hookName: T, ...args: Parameters<NonNullable<PaginationPlugin[T]>>): void;
26
+
27
+ export declare type ConfigAttribute = {
28
+ [K in AttributeKey]?: AttributeValue<K>;
29
+ };
30
+
31
+ export declare function configToAttributeMap(config: ConfigAttribute): Record<string, string>;
32
+
33
+ export declare function createLoremIpsumParagraph(wordCount: number, seed: number): string;
34
+
35
+ export declare const currentElementClassName = "pz-current-element";
36
+
37
+ export declare const currentTextClassName = "pz-current-text";
38
+
39
+ export declare const defaultPlugins: PaginationPlugin[];
40
+
41
+ export declare class DomState {
42
+ private readonly _transaction;
43
+ private readonly _treeWalker;
44
+ private readonly _config;
45
+ private _completed;
46
+ private _currentNode;
47
+ private _previousNode;
48
+ constructor(root: Element, transaction: Transaction, config: PaginationConfig);
49
+ get completed(): boolean;
50
+ get currentNode(): PageNode | null;
51
+ get previousNode(): PageNode | null;
52
+ nextNode(): void;
53
+ nextSiblingOrParentSibling(): {
54
+ parentsTraversed: number;
55
+ };
56
+ firstChildOrNextNode(): {
57
+ parentsTraversed: number;
58
+ };
59
+ private setState;
60
+ }
61
+
62
+ export declare const enableDebugMode: () => void;
63
+
64
+ export declare function getVisibleHeight(element: Element): number;
65
+
66
+ export declare const ignoredElementClassName = "pz-ignored-element";
67
+
68
+ export declare const ignoredTextClassName = "pz-ignored-text";
69
+
70
+ export declare const isDebugMode: () => boolean;
71
+
72
+ export declare function isElement(node: Node): node is Element;
73
+
74
+ export declare function isTextNode(node: Node): node is Text;
75
+
76
+ export declare const logger: default_2.Logger;
77
+
78
+ export declare const loggerName = "paprize";
79
+
80
+ export declare function moveOffscreen(element: HTMLDivElement): void;
81
+
82
+ export declare const pageBreakAttributeName = "data-pz-page-break";
83
+
84
+ export declare const pageBreakPlugin: PaginationPlugin;
85
+
86
+ export declare const pageBreakPluginName = "pageBreak";
87
+
88
+ export declare const pageClassName = "pz-page";
89
+
90
+ declare class PageElement {
91
+ private readonly _node;
92
+ private readonly _transaction;
93
+ readonly type: 'element';
94
+ readonly config: PaginationConfig;
95
+ constructor(element: Element, transaction: Transaction, config: PaginationConfig);
96
+ appendChild(node: PageNode): void;
97
+ clone(withChildren?: boolean): PageElement;
98
+ getHeight(): number;
99
+ remove(): void;
100
+ isEmpty(): boolean;
101
+ getChildrenCount(): number;
102
+ getNode(): SafeElement;
103
+ }
104
+
105
+ declare class PageManager {
106
+ private _pageState;
107
+ private readonly _transaction;
108
+ private readonly _tempContainer;
109
+ private readonly _config;
110
+ constructor(tempContainer: Element, pageSize: PageSize, transaction: Transaction, config: PaginationConfig);
111
+ nextPage(): void;
112
+ private cloneParentStackToNewPage;
113
+ private cleanupEmptyParent;
114
+ enterElement(): void;
115
+ leaveElement(): void;
116
+ private static createPageHtmlElement;
117
+ private createNewPage;
118
+ startTransaction(): {
119
+ rollback: () => void;
120
+ commit: () => void;
121
+ };
122
+ hasEmptySpace(elementHeight?: number): boolean;
123
+ isOverFlow(): boolean;
124
+ markPageAsFull(): void;
125
+ appendChild(node: PageElement, withChildren: boolean): PageElement;
126
+ addTextNode(text: string): PageText;
127
+ }
128
+
129
+ declare type PageNode = PageElement | PageText;
130
+
131
+ export declare interface PageSize {
132
+ width: number;
133
+ height: number;
134
+ }
135
+
136
+ declare class PageState {
137
+ currentPage: PageElement;
138
+ activeElement: PageNode | null;
139
+ currentElement: PageElement;
140
+ parentStack: PageElement[];
141
+ pageIsFull: boolean;
142
+ pageIndex: number;
143
+ pageHeight: number;
144
+ constructor(currentPage: PageElement, activeElement: PageNode | null, currentElement: PageElement, parentStack: PageElement[], pageIsFull: boolean, pageIndex: number, pageHeight: number);
145
+ static create(currentPage: PageElement, parentStack: PageElement[], pageIndex: number, pageHeight: number): PageState;
146
+ clone: () => PageState;
147
+ }
148
+
149
+ declare class PageText {
150
+ private readonly _node;
151
+ private readonly _transaction;
152
+ readonly type: 'text';
153
+ readonly config: PaginationConfig;
154
+ constructor(text: Text, transaction: Transaction, config: PaginationConfig);
155
+ get textContent(): string;
156
+ set textContent(value: string);
157
+ remove(): void;
158
+ getNode(): SafeText;
159
+ }
160
+
161
+ export declare type PaginateResult = string[];
162
+
163
+ export declare type PaginationConfig = Required<ConfigAttribute> & {
164
+ plugins: PaginationPlugin[];
165
+ };
166
+
167
+ export declare interface PaginationPlugin {
168
+ readonly name: string;
169
+ onVisitText?: (domState: DomState & {
170
+ currentNode: PageText;
171
+ }, pageManager: PageManager, context: VisitContext) => void;
172
+ onVisitElement?: (domState: DomState & {
173
+ currentNode: PageElement;
174
+ }, pageManager: PageManager, context: VisitContext) => void;
175
+ afterVisitNode?: (domState: DomState, pageManager: PageManager) => void;
176
+ onNewPage?: (newPageState: PageState) => void;
177
+ onClone?: (source: Element, cloned: PageElement) => void;
178
+ }
179
+
180
+ export declare class Paginator {
181
+ private readonly _domState;
182
+ private readonly _pageManager;
183
+ private readonly _transaction;
184
+ private readonly _tempContainer;
185
+ private readonly _config;
186
+ private constructor();
187
+ private static createTempContainer;
188
+ static paginate(root: Element, pageSize: PageSize, config?: Partial<PaginationConfig>): PaginateResult;
189
+ private processAllNodes;
190
+ private handleNodeSkipped;
191
+ private handleFullNodePlaced;
192
+ private handleChildrenSplit;
193
+ private processCurrentNode;
194
+ }
195
+
196
+ declare type PluginHookNames = NonNullable<PluginKeys>;
197
+
198
+ declare type PluginKeys = {
199
+ [K in keyof PaginationPlugin]: PaginationPlugin[K] extends ((...args: any[]) => any) | undefined ? K : never;
200
+ }[keyof PaginationPlugin];
201
+
202
+ declare type SafeElement = Omit<Element, 'removeChild' | 'appendChild' | 'replaceChild' | 'remove'>;
203
+
204
+ declare type SafeText = Omit<Text, 'remove'>;
205
+
206
+ export declare const SplitResult: {
207
+ readonly None: 0;
208
+ readonly FullNodePlaced: 1;
209
+ readonly SplitChildren: 2;
210
+ };
211
+
212
+ export declare type SplitResult = (typeof SplitResult)[keyof typeof SplitResult];
213
+
214
+ export declare const tempContainerClassName = "pz-temp-container";
215
+
216
+ declare class Transaction {
217
+ private _onRollback;
218
+ private _onCommit;
219
+ isActive: boolean;
220
+ constructor();
221
+ start: () => void;
222
+ addRollbackCallback: (callback: () => void) => void;
223
+ addCommitCallback: (callback: () => void) => void;
224
+ rollback: () => void;
225
+ commit: () => void;
226
+ }
227
+
228
+ export declare interface VisitContext {
229
+ result?: SplitResult;
230
+ }
231
+
232
+ export { }
@@ -0,0 +1,836 @@
1
+ const ie = "paprize", re = "pz-temp-container", xe = "pz-current-element", we = "pz-current-text", ke = "pz-ignored-element", Te = "pz-ignored-text", Pe = "pz-page", V = "data-pz-";
2
+ let G = !1;
3
+ const Le = () => {
4
+ G = !0;
5
+ }, Ae = () => G;
6
+ function j(n) {
7
+ return n.nodeType === Node.ELEMENT_NODE;
8
+ }
9
+ function ae(n) {
10
+ return n.nodeType === Node.TEXT_NODE;
11
+ }
12
+ function se(n) {
13
+ const e = n.getBoundingClientRect(), t = getComputedStyle(n), o = parseFloat(t.marginTop) || 0, i = parseFloat(t.marginBottom) || 0;
14
+ return e.height + o + i;
15
+ }
16
+ function Fe(n) {
17
+ n.style.visibility = "hidden", n.style.position = "absolute", n.style.left = "-9999px", n.style.top = "-9999px";
18
+ }
19
+ class v {
20
+ name;
21
+ defaultValue;
22
+ _reader;
23
+ constructor(e, t, o) {
24
+ this.name = e, this._reader = t, this.defaultValue = o;
25
+ }
26
+ read(e) {
27
+ return this._reader(e);
28
+ }
29
+ static createStr(e, t) {
30
+ return new v(e, (o) => o, t);
31
+ }
32
+ static createBool(e, t) {
33
+ return new v(
34
+ e,
35
+ (o) => o === "true",
36
+ t
37
+ );
38
+ }
39
+ }
40
+ const P = {
41
+ hyphen: v.createStr("hyphen", "-"),
42
+ keepOnSamePage: v.createBool("keep-on-same-page", !1),
43
+ hyphenationEnabled: v.createBool(
44
+ "hyphenation-enabled",
45
+ !0
46
+ )
47
+ };
48
+ function Ie(n) {
49
+ const e = {};
50
+ for (const t in n) {
51
+ const o = n[t];
52
+ if (o !== void 0) {
53
+ const i = P[t];
54
+ e[`${V}${i.name}`] = String(o);
55
+ }
56
+ }
57
+ return e;
58
+ }
59
+ const le = Object.fromEntries(
60
+ Object.entries(P).map(([n, e]) => [
61
+ n,
62
+ e.defaultValue
63
+ ])
64
+ ), M = /* @__PURE__ */ new WeakMap();
65
+ function X(n) {
66
+ if (!n)
67
+ return {};
68
+ if (!(n instanceof Element))
69
+ return X(n?.parentNode);
70
+ const e = {};
71
+ for (const i in P) {
72
+ const a = P[i], s = `${V}${a.name}`, p = n.getAttribute(s);
73
+ p !== null && (e[i] = a.read(p));
74
+ }
75
+ const o = { ...n.parentNode ? M.get(n.parentNode) : void 0, ...e };
76
+ return M.set(n, o), o;
77
+ }
78
+ const J = {
79
+ plugins: [],
80
+ ...le
81
+ };
82
+ function ce(n, e) {
83
+ const t = X(n);
84
+ return { ...J, ...e, ...t };
85
+ }
86
+ function ue(n) {
87
+ return n && n.__esModule && Object.prototype.hasOwnProperty.call(n, "default") ? n.default : n;
88
+ }
89
+ var T = { exports: {} }, de = T.exports, D;
90
+ function pe() {
91
+ return D || (D = 1, (function(n) {
92
+ (function(e, t) {
93
+ n.exports ? n.exports = t() : e.log = t();
94
+ })(de, function() {
95
+ var e = function() {
96
+ }, t = "undefined", o = typeof window !== t && typeof window.navigator !== t && /Trident\/|MSIE /.test(window.navigator.userAgent), i = [
97
+ "trace",
98
+ "debug",
99
+ "info",
100
+ "warn",
101
+ "error"
102
+ ], a = {}, s = null;
103
+ function p(l, u) {
104
+ var r = l[u];
105
+ if (typeof r.bind == "function")
106
+ return r.bind(l);
107
+ try {
108
+ return Function.prototype.bind.call(r, l);
109
+ } catch {
110
+ return function() {
111
+ return Function.prototype.apply.apply(r, [l, arguments]);
112
+ };
113
+ }
114
+ }
115
+ function K() {
116
+ console.log && (console.log.apply ? console.log.apply(console, arguments) : Function.prototype.apply.apply(console.log, [console, arguments])), console.trace && console.trace();
117
+ }
118
+ function Y(l) {
119
+ return l === "debug" && (l = "log"), typeof console === t ? !1 : l === "trace" && o ? K : console[l] !== void 0 ? p(console, l) : console.log !== void 0 ? p(console, "log") : e;
120
+ }
121
+ function y() {
122
+ for (var l = this.getLevel(), u = 0; u < i.length; u++) {
123
+ var r = i[u];
124
+ this[r] = u < l ? e : this.methodFactory(r, l, this.name);
125
+ }
126
+ if (this.log = this.debug, typeof console === t && l < this.levels.SILENT)
127
+ return "No console available for logging";
128
+ }
129
+ function Q(l) {
130
+ return function() {
131
+ typeof console !== t && (y.call(this), this[l].apply(this, arguments));
132
+ };
133
+ }
134
+ function Z(l, u, r) {
135
+ return Y(l) || Q.apply(this, arguments);
136
+ }
137
+ function B(l, u) {
138
+ var r = this, w, L, m, f = "loglevel";
139
+ typeof l == "string" ? f += ":" + l : typeof l == "symbol" && (f = void 0);
140
+ function te(c) {
141
+ var d = (i[c] || "silent").toUpperCase();
142
+ if (!(typeof window === t || !f)) {
143
+ try {
144
+ window.localStorage[f] = d;
145
+ return;
146
+ } catch {
147
+ }
148
+ try {
149
+ window.document.cookie = encodeURIComponent(f) + "=" + d + ";";
150
+ } catch {
151
+ }
152
+ }
153
+ }
154
+ function H() {
155
+ var c;
156
+ if (!(typeof window === t || !f)) {
157
+ try {
158
+ c = window.localStorage[f];
159
+ } catch {
160
+ }
161
+ if (typeof c === t)
162
+ try {
163
+ var d = window.document.cookie, k = encodeURIComponent(f), $ = d.indexOf(k + "=");
164
+ $ !== -1 && (c = /^([^;]+)/.exec(
165
+ d.slice($ + k.length + 1)
166
+ )[1]);
167
+ } catch {
168
+ }
169
+ return r.levels[c] === void 0 && (c = void 0), c;
170
+ }
171
+ }
172
+ function ne() {
173
+ if (!(typeof window === t || !f)) {
174
+ try {
175
+ window.localStorage.removeItem(f);
176
+ } catch {
177
+ }
178
+ try {
179
+ window.document.cookie = encodeURIComponent(f) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
180
+ } catch {
181
+ }
182
+ }
183
+ }
184
+ function b(c) {
185
+ var d = c;
186
+ if (typeof d == "string" && r.levels[d.toUpperCase()] !== void 0 && (d = r.levels[d.toUpperCase()]), typeof d == "number" && d >= 0 && d <= r.levels.SILENT)
187
+ return d;
188
+ throw new TypeError("log.setLevel() called with invalid level: " + c);
189
+ }
190
+ r.name = l, r.levels = {
191
+ TRACE: 0,
192
+ DEBUG: 1,
193
+ INFO: 2,
194
+ WARN: 3,
195
+ ERROR: 4,
196
+ SILENT: 5
197
+ }, r.methodFactory = u || Z, r.getLevel = function() {
198
+ return m ?? L ?? w;
199
+ }, r.setLevel = function(c, d) {
200
+ return m = b(c), d !== !1 && te(m), y.call(r);
201
+ }, r.setDefaultLevel = function(c) {
202
+ L = b(c), H() || r.setLevel(c, !1);
203
+ }, r.resetLevel = function() {
204
+ m = null, ne(), y.call(r);
205
+ }, r.enableAll = function(c) {
206
+ r.setLevel(r.levels.TRACE, c);
207
+ }, r.disableAll = function(c) {
208
+ r.setLevel(r.levels.SILENT, c);
209
+ }, r.rebuild = function() {
210
+ if (s !== r && (w = b(s.getLevel())), y.call(r), s === r)
211
+ for (var c in a)
212
+ a[c].rebuild();
213
+ }, w = b(
214
+ s ? s.getLevel() : "WARN"
215
+ );
216
+ var W = H();
217
+ W != null && (m = b(W)), y.call(r);
218
+ }
219
+ s = new B(), s.getLogger = function(u) {
220
+ if (typeof u != "symbol" && typeof u != "string" || u === "")
221
+ throw new TypeError("You must supply a name when creating a logger.");
222
+ var r = a[u];
223
+ return r || (r = a[u] = new B(
224
+ u,
225
+ s.methodFactory
226
+ )), r;
227
+ };
228
+ var ee = typeof window !== t ? window.log : void 0;
229
+ return s.noConflict = function() {
230
+ return typeof window !== t && window.log === s && (window.log = ee), s;
231
+ }, s.getLoggers = function() {
232
+ return a;
233
+ }, s.default = s, s;
234
+ });
235
+ })(T)), T.exports;
236
+ }
237
+ var ge = pe();
238
+ const _ = /* @__PURE__ */ ue(ge), h = _.getLogger(ie);
239
+ h.setDefaultLevel("info");
240
+ const A = "\x1B[46mPLUGIN\x1B[0m";
241
+ function N(n, e, ...t) {
242
+ n.forEach((o) => {
243
+ const i = o[e];
244
+ if (i) {
245
+ h.debug(
246
+ A,
247
+ `executing plugin ${o.name}:${String(e)}`,
248
+ t
249
+ );
250
+ try {
251
+ i(...t), h.debug(
252
+ A,
253
+ `plugin ${o.name}:${String(e)} executed`,
254
+ t
255
+ );
256
+ } catch (a) {
257
+ h.debug(
258
+ A,
259
+ `plugin ${o.name}:${String(e)} failed`,
260
+ a
261
+ );
262
+ }
263
+ }
264
+ });
265
+ }
266
+ const S = {
267
+ Element: "element",
268
+ Text: "text"
269
+ };
270
+ class O {
271
+ _node;
272
+ _transaction;
273
+ type = S.Element;
274
+ config;
275
+ constructor(e, t, o) {
276
+ this._node = e, this._transaction = t, this.config = o;
277
+ }
278
+ appendChild(e) {
279
+ this._transaction.isActive && this._transaction.addRollbackCallback(() => {
280
+ this._node.removeChild(e.getNode());
281
+ }), this._node.appendChild(e.getNode());
282
+ }
283
+ clone(e) {
284
+ const t = this._node.cloneNode(e), o = new O(
285
+ t,
286
+ this._transaction,
287
+ this.config
288
+ );
289
+ return N(
290
+ this.config.plugins,
291
+ "onClone",
292
+ this._node,
293
+ o
294
+ ), o;
295
+ }
296
+ getHeight() {
297
+ return se(this._node);
298
+ }
299
+ remove() {
300
+ this._transaction.addCommitCallback(() => {
301
+ this._node.remove();
302
+ });
303
+ }
304
+ isEmpty() {
305
+ return this._node.innerHTML === "";
306
+ }
307
+ getChildrenCount() {
308
+ return this._node.childNodes.length;
309
+ }
310
+ getNode() {
311
+ return this._node;
312
+ }
313
+ }
314
+ class he {
315
+ _node;
316
+ _transaction;
317
+ type = S.Text;
318
+ config;
319
+ constructor(e, t, o) {
320
+ this._node = e, this._transaction = t, this.config = o;
321
+ }
322
+ get textContent() {
323
+ return this._node.textContent ?? "";
324
+ }
325
+ set textContent(e) {
326
+ this._node.textContent = e;
327
+ }
328
+ remove() {
329
+ this._transaction.addCommitCallback(() => {
330
+ this._node.remove();
331
+ });
332
+ }
333
+ getNode() {
334
+ return this._node;
335
+ }
336
+ }
337
+ function F(n, e, t) {
338
+ if (ae(n))
339
+ return new he(n, e, t);
340
+ if (j(n))
341
+ return new O(n, e, t);
342
+ throw new Error("Unsupported node type");
343
+ }
344
+ const C = "\x1B[106mDOM\x1B[0m";
345
+ class fe {
346
+ _transaction;
347
+ _treeWalker;
348
+ _config;
349
+ _completed = !1;
350
+ _currentNode = null;
351
+ _previousNode = null;
352
+ constructor(e, t, o) {
353
+ this._transaction = t, this._config = o, this._treeWalker = document.createTreeWalker(
354
+ e,
355
+ NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT
356
+ );
357
+ }
358
+ get completed() {
359
+ return this._completed;
360
+ }
361
+ get currentNode() {
362
+ return this._currentNode;
363
+ }
364
+ get previousNode() {
365
+ return this._previousNode;
366
+ }
367
+ nextNode() {
368
+ this._treeWalker.nextNode() || (this._completed = !0), h.debug(C, "moving to next node"), this.setState();
369
+ }
370
+ nextSiblingOrParentSibling() {
371
+ let e = 0;
372
+ if (this._treeWalker.nextSibling())
373
+ return h.debug(C, "moving to next sibling node"), this.setState(), { parentsTraversed: e };
374
+ for (; this._treeWalker.parentNode(); )
375
+ if (e++, this._treeWalker.nextSibling())
376
+ return h.debug(
377
+ C,
378
+ "moving to parent sibling node, traversed:",
379
+ e
380
+ ), this.setState(), { parentsTraversed: e };
381
+ return this._completed = !0, { parentsTraversed: e };
382
+ }
383
+ firstChildOrNextNode() {
384
+ return this._treeWalker.firstChild() ? (h.debug(C, "moving to first child node"), this.setState(), { parentsTraversed: 1 }) : (this.nextNode(), { parentsTraversed: 0 });
385
+ }
386
+ setState() {
387
+ this._previousNode = this._currentNode, this._currentNode = F(
388
+ this._treeWalker.currentNode,
389
+ this._transaction,
390
+ ce(this._treeWalker.currentNode, this._config)
391
+ ), h.debug(C, "moved to node", {
392
+ currentNode: this.currentNode,
393
+ previousNode: this.previousNode
394
+ });
395
+ }
396
+ }
397
+ class me {
398
+ _onRollback;
399
+ _onCommit;
400
+ isActive;
401
+ constructor() {
402
+ this._onRollback = [], this._onCommit = [], this.isActive = !1;
403
+ }
404
+ start = () => {
405
+ if (this.isActive)
406
+ throw new Error("Transaction already in progress");
407
+ this.isActive = !0, this._onRollback = [], this._onCommit = [];
408
+ };
409
+ addRollbackCallback = (e) => {
410
+ this._onRollback.push(e);
411
+ };
412
+ addCommitCallback = (e) => {
413
+ if (!this.isActive) {
414
+ e();
415
+ return;
416
+ }
417
+ this._onCommit.push(e);
418
+ };
419
+ rollback = () => {
420
+ this.isActive && (this.isActive = !1, this._onRollback.forEach((e) => e()));
421
+ };
422
+ commit = () => {
423
+ this.isActive && (this.isActive = !1, this._onCommit.forEach((e) => e()));
424
+ };
425
+ }
426
+ const U = "\x1B[102mPAGE\x1B[0m";
427
+ class x {
428
+ currentPage;
429
+ activeElement;
430
+ currentElement;
431
+ parentStack;
432
+ pageIsFull;
433
+ pageIndex;
434
+ pageHeight;
435
+ constructor(e, t, o, i, a, s, p) {
436
+ this.currentPage = e, this.activeElement = t, this.currentElement = o, this.parentStack = i, this.pageIsFull = a, this.pageIndex = s, this.pageHeight = p;
437
+ }
438
+ static create(e, t, o, i) {
439
+ return new x(
440
+ e,
441
+ null,
442
+ e,
443
+ t,
444
+ !1,
445
+ o,
446
+ i
447
+ );
448
+ }
449
+ clone = () => new x(
450
+ this.currentPage,
451
+ this.activeElement,
452
+ this.currentElement,
453
+ [...this.parentStack],
454
+ this.pageIsFull,
455
+ this.pageIndex,
456
+ this.pageHeight
457
+ );
458
+ }
459
+ class R {
460
+ _pageState;
461
+ _transaction;
462
+ _tempContainer;
463
+ _config;
464
+ constructor(e, t, o, i) {
465
+ this._tempContainer = e, this._config = i, this._transaction = o;
466
+ const a = R.createPageHtmlElement(
467
+ t.width
468
+ ), s = this.createNewPage(a);
469
+ this._pageState = x.create(s, [], 0, t.height), N(this._config.plugins, "onNewPage", this._pageState);
470
+ }
471
+ nextPage() {
472
+ const e = this.createNewPage(
473
+ this._pageState.currentPage.getNode().cloneNode(!1)
474
+ ), t = x.create(
475
+ e,
476
+ [],
477
+ this._pageState.pageIndex + 1,
478
+ this._pageState.pageHeight
479
+ );
480
+ this.cloneParentStackToNewPage(t), this.cleanupEmptyParent(), this._pageState = t, N(this._config.plugins, "onNewPage", this._pageState);
481
+ }
482
+ cloneParentStackToNewPage(e) {
483
+ for (const t of this._pageState.parentStack) {
484
+ const o = t.clone(!1);
485
+ e.currentElement.appendChild(o), e.currentElement = o, e.parentStack.push(o);
486
+ }
487
+ }
488
+ cleanupEmptyParent() {
489
+ const e = [...this._pageState.parentStack], t = () => {
490
+ for (let o = e.length - 1; o >= 0; o--) {
491
+ const i = e[o];
492
+ i.isEmpty() && i.remove();
493
+ }
494
+ };
495
+ this._transaction.addCommitCallback(t);
496
+ }
497
+ enterElement() {
498
+ if (!this._pageState.activeElement || this._pageState.activeElement.type !== S.Element)
499
+ throw new Error("Invalid state: activeElement is not an Element");
500
+ h.debug(
501
+ U,
502
+ "entering an element",
503
+ this._pageState.activeElement
504
+ ), this._pageState.currentElement = this._pageState.activeElement, this._pageState.parentStack.push(this._pageState.activeElement);
505
+ }
506
+ leaveElement() {
507
+ this._pageState.activeElement = null;
508
+ const e = this._pageState.parentStack.pop();
509
+ h.debug(U, "leaving a parent element", e);
510
+ const t = this._pageState.parentStack.at(-1);
511
+ this._pageState.currentElement = t ?? this._pageState.currentPage;
512
+ }
513
+ static createPageHtmlElement(e) {
514
+ const t = document.createElement("div");
515
+ return t.style.display = "flex", t.style.flexDirection = "column", t.style.width = `${e}px`, t.style.maxWidth = `${e}px`, t;
516
+ }
517
+ createNewPage(e) {
518
+ return this._tempContainer.appendChild(e), this._transaction.isActive && this._transaction.addRollbackCallback(() => {
519
+ this._tempContainer.removeChild(e);
520
+ }), F(e, this._transaction, this._config);
521
+ }
522
+ startTransaction() {
523
+ this._transaction.start();
524
+ const e = this._pageState.clone();
525
+ return this._transaction.addRollbackCallback(() => {
526
+ this._pageState = e;
527
+ }), this._transaction;
528
+ }
529
+ hasEmptySpace(e) {
530
+ return !this._pageState.pageIsFull && this._pageState.currentPage.getHeight() + (e || 1) <= this._pageState.pageHeight;
531
+ }
532
+ isOverFlow() {
533
+ return this._pageState.currentPage.getHeight() > this._pageState.pageHeight;
534
+ }
535
+ markPageAsFull() {
536
+ this._pageState.pageIsFull = !0;
537
+ }
538
+ appendChild(e, t) {
539
+ const o = e.clone(t);
540
+ return this._pageState.currentElement.appendChild(o), this._pageState.activeElement = o, o;
541
+ }
542
+ addTextNode(e) {
543
+ if (this._pageState.activeElement?.type === S.Text)
544
+ return this._pageState.activeElement;
545
+ const t = document.createTextNode(e), o = F(
546
+ t,
547
+ this._transaction,
548
+ this._config
549
+ );
550
+ return this._pageState.currentElement.appendChild(o), this._pageState.activeElement = o, o;
551
+ }
552
+ }
553
+ const g = {
554
+ None: 0,
555
+ // The node fits completely on the page, no further splitting required.
556
+ FullNodePlaced: 1,
557
+ // The entire node was placed on the page, continue with the next sibling or element.
558
+ SplitChildren: 2
559
+ // The node is too large for the page, and its children must be paginated individually.
560
+ };
561
+ function _e(n, e) {
562
+ const t = z(n, e);
563
+ if (t !== g.None)
564
+ return t;
565
+ const { rollback: o, commit: i } = e.startTransaction();
566
+ e.nextPage();
567
+ const a = z(n, e);
568
+ return a !== g.None ? (i(), a) : (o(), h.debug("Element is too big to fit on a page", n), g.None);
569
+ }
570
+ function z(n, e) {
571
+ if (e.hasEmptySpace(n.getHeight())) {
572
+ const o = e.appendChild(n, !0);
573
+ if (e.isOverFlow())
574
+ o.remove();
575
+ else
576
+ return g.FullNodePlaced;
577
+ }
578
+ if (n.config.keepOnSamePage || n.getChildrenCount() === 0)
579
+ return g.None;
580
+ const t = e.appendChild(n, !1);
581
+ return e.isOverFlow() ? (t.remove(), g.None) : g.SplitChildren;
582
+ }
583
+ function ve(n, e) {
584
+ let t = g.FullNodePlaced;
585
+ const o = n.textContent.split(/(\s+)/).filter((s) => s !== "");
586
+ let i, a = 0;
587
+ for (; i || a < o.length; ) {
588
+ const s = i ?? o[a], p = Ne(s, e, n.config);
589
+ p.completed || (t = g.None), p.pendingToken ? i = p.pendingToken : (i = void 0, a++);
590
+ }
591
+ return t;
592
+ }
593
+ function Ne(n, e, t) {
594
+ e.hasEmptySpace() || e.nextPage();
595
+ let o = e.addTextNode("");
596
+ const i = o.textContent;
597
+ if (o.textContent += n, !e.isOverFlow())
598
+ return {
599
+ completed: !0
600
+ };
601
+ o.textContent = i;
602
+ const a = Se(n, e, t);
603
+ return {
604
+ pendingToken: a.leftovers,
605
+ completed: a.completed
606
+ };
607
+ }
608
+ function Se(n, e, t) {
609
+ const { rollback: o, commit: i } = e.startTransaction();
610
+ if (e.nextPage(), e.addTextNode(n), !e.isOverFlow())
611
+ return i(), {
612
+ completed: !0
613
+ };
614
+ if (o(), !t.hyphenationEnabled)
615
+ return h.warn("Hyphenation disabled, skipping oversized token:", n), {
616
+ completed: !1
617
+ };
618
+ const a = ye(n, t.hyphen, e);
619
+ return {
620
+ completed: !0,
621
+ leftovers: a && a.length > 0 ? a : void 0
622
+ };
623
+ }
624
+ function ye(n, e, t) {
625
+ const o = t.addTextNode("");
626
+ let i = "";
627
+ for (let a = 0; a < n.length; a++) {
628
+ const s = n[a], p = i + s;
629
+ if (o.textContent = p + e, !t.hasEmptySpace())
630
+ return o.textContent = i ? i + e : "", t.markPageAsFull(), n.slice(a);
631
+ i = p;
632
+ }
633
+ return null;
634
+ }
635
+ const E = "\x1B[103mPAGINATOR\x1B[0m";
636
+ class I {
637
+ _domState;
638
+ _pageManager;
639
+ _transaction;
640
+ _tempContainer;
641
+ _config;
642
+ constructor(e, t, o) {
643
+ this._config = { ...J, ...o }, this._tempContainer = I.createTempContainer(), this._transaction = new me(), this._domState = new fe(e, this._transaction, this._config), this._pageManager = new R(
644
+ this._tempContainer,
645
+ t,
646
+ this._transaction,
647
+ this._config
648
+ );
649
+ }
650
+ static createTempContainer() {
651
+ const e = document.createElement("div");
652
+ return e.classList.add(re), document.body.appendChild(e), e;
653
+ }
654
+ static paginate(e, t, o) {
655
+ const i = new I(e, t, o);
656
+ return i.processAllNodes(), Array.from(i._tempContainer.childNodes).filter((s) => j(s)).map((s) => s.innerHTML);
657
+ }
658
+ processAllNodes() {
659
+ this._domState.nextNode();
660
+ do {
661
+ switch (_.debug(
662
+ E,
663
+ "paginating node",
664
+ this._domState.currentNode
665
+ ), this.processCurrentNode()) {
666
+ case g.None:
667
+ this.handleNodeSkipped();
668
+ break;
669
+ case g.FullNodePlaced:
670
+ this.handleFullNodePlaced();
671
+ break;
672
+ case g.SplitChildren:
673
+ this.handleChildrenSplit();
674
+ break;
675
+ }
676
+ N(
677
+ this._config.plugins,
678
+ "afterVisitNode",
679
+ this._domState,
680
+ this._pageManager
681
+ );
682
+ } while (this._domState.completed === !1);
683
+ _.debug(E, "pagination completed");
684
+ }
685
+ handleNodeSkipped() {
686
+ _.debug(E, "node skipped - couldn't paginate"), this._domState.nextNode();
687
+ }
688
+ handleFullNodePlaced() {
689
+ _.debug(E, "node fully paginated");
690
+ const { parentsTraversed: e } = this._domState.nextSiblingOrParentSibling();
691
+ for (let t = 0; t < e; t++)
692
+ this._pageManager.leaveElement();
693
+ }
694
+ handleChildrenSplit() {
695
+ _.debug(
696
+ E,
697
+ "node partially paginated - splitting children"
698
+ ), this._domState.firstChildOrNextNode().parentsTraversed === 1 && this._domState.previousNode?.type === S.Element && this._pageManager.enterElement();
699
+ }
700
+ processCurrentNode() {
701
+ if (!this._domState.currentNode)
702
+ return g.None;
703
+ if (this._domState.currentNode.type === S.Element) {
704
+ const e = {};
705
+ return N(
706
+ this._config.plugins,
707
+ "onVisitElement",
708
+ this._domState,
709
+ this._pageManager,
710
+ e
711
+ ), e.result !== void 0 ? e.result : _e(
712
+ this._domState.currentNode,
713
+ this._pageManager
714
+ );
715
+ } else {
716
+ const e = {};
717
+ return N(
718
+ this._config.plugins,
719
+ "onVisitText",
720
+ this._domState,
721
+ this._pageManager,
722
+ e
723
+ ), e.result !== void 0 ? e.result : ve(
724
+ this._domState.currentNode,
725
+ this._pageManager
726
+ );
727
+ }
728
+ }
729
+ }
730
+ const q = [
731
+ "ad",
732
+ "adipisicing",
733
+ "aliqua",
734
+ "aliquip",
735
+ "amet",
736
+ "anim",
737
+ "aute",
738
+ "cillum",
739
+ "commodo",
740
+ "consectetur",
741
+ "consequat",
742
+ "culpa",
743
+ "cupidatat",
744
+ "deserunt",
745
+ "do",
746
+ "dolor",
747
+ "dolore",
748
+ "duis",
749
+ "ea",
750
+ "eiusmod",
751
+ "elit",
752
+ "enim",
753
+ "esse",
754
+ "est",
755
+ "et",
756
+ "eu",
757
+ "ex",
758
+ "excepteur",
759
+ "exercitation",
760
+ "fugiat",
761
+ "id",
762
+ "in",
763
+ "incididunt",
764
+ "ipsum",
765
+ "irure",
766
+ "labore",
767
+ "laboris",
768
+ "laborum",
769
+ "Lorem",
770
+ "magna",
771
+ "minim",
772
+ "mollit",
773
+ "nisi",
774
+ "non",
775
+ "nostrud",
776
+ "nulla",
777
+ "occaecat",
778
+ "officia",
779
+ "pariatur",
780
+ "proident",
781
+ "qui",
782
+ "quis",
783
+ "reprehenderit",
784
+ "sint",
785
+ "sit",
786
+ "sunt",
787
+ "tempor",
788
+ "ullamco",
789
+ "ut",
790
+ "velit",
791
+ "veniam",
792
+ "voluptate"
793
+ ];
794
+ function Oe(n, e) {
795
+ if (n <= 0)
796
+ return "";
797
+ const t = [], o = Math.floor(e * 982451653);
798
+ for (let i = 0; i < n; i++) {
799
+ const a = (o + i * 2654435761) % Math.pow(2, 32), s = Math.floor(
800
+ a / Math.pow(2, 32) * q.length
801
+ );
802
+ t.push(q[s]);
803
+ }
804
+ return t.length > 0 && (t[0] = t[0].charAt(0).toUpperCase() + t[0].slice(1)), t.join(" ") + ".";
805
+ }
806
+ const be = "data-pz-page-break", Ce = "pageBreak", Ee = {
807
+ name: Ce,
808
+ onVisitElement: (n, e, t) => {
809
+ n.currentNode.getNode().getAttribute(be) === "true" && (e.markPageAsFull(), t.result = g.FullNodePlaced);
810
+ }
811
+ }, Re = [Ee];
812
+ export {
813
+ I as Paginator,
814
+ g as SplitResult,
815
+ V as attributePrefix,
816
+ Ie as configToAttributeMap,
817
+ Oe as createLoremIpsumParagraph,
818
+ xe as currentElementClassName,
819
+ we as currentTextClassName,
820
+ Re as defaultPlugins,
821
+ Le as enableDebugMode,
822
+ se as getVisibleHeight,
823
+ ke as ignoredElementClassName,
824
+ Te as ignoredTextClassName,
825
+ Ae as isDebugMode,
826
+ j as isElement,
827
+ ae as isTextNode,
828
+ h as logger,
829
+ ie as loggerName,
830
+ Fe as moveOffscreen,
831
+ be as pageBreakAttributeName,
832
+ Ee as pageBreakPlugin,
833
+ Ce as pageBreakPluginName,
834
+ Pe as pageClassName,
835
+ re as tempContainerClassName
836
+ };
@@ -0,0 +1 @@
1
+ (function(l,_){typeof exports=="object"&&typeof module<"u"?_(exports):typeof define=="function"&&define.amd?define(["exports"],_):(l=typeof globalThis<"u"?globalThis:l||self,_(l.paprize_core={}))})(this,(function(l){"use strict";const _="paprize",M="pz-temp-container",oe="pz-current-element",re="pz-current-text",ae="pz-ignored-element",se="pz-ignored-text",le="pz-page",I="data-pz-";let D=!1;const ce=()=>{D=!0},ue=()=>D;function O(n){return n.nodeType===Node.ELEMENT_NODE}function z(n){return n.nodeType===Node.TEXT_NODE}function U(n){const e=n.getBoundingClientRect(),t=getComputedStyle(n),i=parseFloat(t.marginTop)||0,o=parseFloat(t.marginBottom)||0;return e.height+i+o}function de(n){n.style.visibility="hidden",n.style.position="absolute",n.style.left="-9999px",n.style.top="-9999px"}class v{name;defaultValue;_reader;constructor(e,t,i){this.name=e,this._reader=t,this.defaultValue=i}read(e){return this._reader(e)}static createStr(e,t){return new v(e,i=>i,t)}static createBool(e,t){return new v(e,i=>i==="true",t)}}const T={hyphen:v.createStr("hyphen","-"),keepOnSamePage:v.createBool("keep-on-same-page",!1),hyphenationEnabled:v.createBool("hyphenation-enabled",!0)};function ge(n){const e={};for(const t in n){const i=n[t];if(i!==void 0){const o=T[t];e[`${I}${o.name}`]=String(i)}}return e}const pe=Object.fromEntries(Object.entries(T).map(([n,e])=>[n,e.defaultValue])),V=new WeakMap;function q(n){if(!n)return{};if(!(n instanceof Element))return q(n?.parentNode);const e={};for(const o in T){const a=T[o],s=`${I}${a.name}`,f=n.getAttribute(s);f!==null&&(e[o]=a.read(f))}const i={...n.parentNode?V.get(n.parentNode):void 0,...e};return V.set(n,i),i}const j={plugins:[],...pe};function he(n,e){const t=q(n);return{...j,...e,...t}}function fe(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var P={exports:{}},me=P.exports,G;function _e(){return G||(G=1,(function(n){(function(e,t){n.exports?n.exports=t():e.log=t()})(me,function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),o=["trace","debug","info","warn","error"],a={},s=null;function f(c,d){var r=c[d];if(typeof r.bind=="function")return r.bind(c);try{return Function.prototype.bind.call(r,c)}catch{return function(){return Function.prototype.apply.apply(r,[c,arguments])}}}function Pe(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function Le(c){return c==="debug"&&(c="log"),typeof console===t?!1:c==="trace"&&i?Pe:console[c]!==void 0?f(console,c):console.log!==void 0?f(console,"log"):e}function k(){for(var c=this.getLevel(),d=0;d<o.length;d++){var r=o[d];this[r]=d<c?e:this.methodFactory(r,c,this.name)}if(this.log=this.debug,typeof console===t&&c<this.levels.SILENT)return"No console available for logging"}function Ae(c){return function(){typeof console!==t&&(k.call(this),this[c].apply(this,arguments))}}function Fe(c,d,r){return Le(c)||Ae.apply(this,arguments)}function ee(c,d){var r=this,A,$,y,m="loglevel";typeof c=="string"?m+=":"+c:typeof c=="symbol"&&(m=void 0);function Oe(u){var g=(o[u]||"silent").toUpperCase();if(!(typeof window===t||!m)){try{window.localStorage[m]=g;return}catch{}try{window.document.cookie=encodeURIComponent(m)+"="+g+";"}catch{}}}function te(){var u;if(!(typeof window===t||!m)){try{u=window.localStorage[m]}catch{}if(typeof u===t)try{var g=window.document.cookie,F=encodeURIComponent(m),ie=g.indexOf(F+"=");ie!==-1&&(u=/^([^;]+)/.exec(g.slice(ie+F.length+1))[1])}catch{}return r.levels[u]===void 0&&(u=void 0),u}}function Re(){if(!(typeof window===t||!m)){try{window.localStorage.removeItem(m)}catch{}try{window.document.cookie=encodeURIComponent(m)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function x(u){var g=u;if(typeof g=="string"&&r.levels[g.toUpperCase()]!==void 0&&(g=r.levels[g.toUpperCase()]),typeof g=="number"&&g>=0&&g<=r.levels.SILENT)return g;throw new TypeError("log.setLevel() called with invalid level: "+u)}r.name=c,r.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},r.methodFactory=d||Fe,r.getLevel=function(){return y??$??A},r.setLevel=function(u,g){return y=x(u),g!==!1&&Oe(y),k.call(r)},r.setDefaultLevel=function(u){$=x(u),te()||r.setLevel(u,!1)},r.resetLevel=function(){y=null,Re(),k.call(r)},r.enableAll=function(u){r.setLevel(r.levels.TRACE,u)},r.disableAll=function(u){r.setLevel(r.levels.SILENT,u)},r.rebuild=function(){if(s!==r&&(A=x(s.getLevel())),k.call(r),s===r)for(var u in a)a[u].rebuild()},A=x(s?s.getLevel():"WARN");var ne=te();ne!=null&&(y=x(ne)),k.call(r)}s=new ee,s.getLogger=function(d){if(typeof d!="symbol"&&typeof d!="string"||d==="")throw new TypeError("You must supply a name when creating a logger.");var r=a[d];return r||(r=a[d]=new ee(d,s.methodFactory)),r};var Ie=typeof window!==t?window.log:void 0;return s.noConflict=function(){return typeof window!==t&&window.log===s&&(window.log=Ie),s},s.getLoggers=function(){return a},s.default=s,s})})(P)),P.exports}var ve=_e();const N=fe(ve),h=N.getLogger(_);h.setDefaultLevel("info");const R="\x1B[46mPLUGIN\x1B[0m";function S(n,e,...t){n.forEach(i=>{const o=i[e];if(o){h.debug(R,`executing plugin ${i.name}:${String(e)}`,t);try{o(...t),h.debug(R,`plugin ${i.name}:${String(e)} executed`,t)}catch(a){h.debug(R,`plugin ${i.name}:${String(e)} failed`,a)}}})}const b={Element:"element",Text:"text"};class B{_node;_transaction;type=b.Element;config;constructor(e,t,i){this._node=e,this._transaction=t,this.config=i}appendChild(e){this._transaction.isActive&&this._transaction.addRollbackCallback(()=>{this._node.removeChild(e.getNode())}),this._node.appendChild(e.getNode())}clone(e){const t=this._node.cloneNode(e),i=new B(t,this._transaction,this.config);return S(this.config.plugins,"onClone",this._node,i),i}getHeight(){return U(this._node)}remove(){this._transaction.addCommitCallback(()=>{this._node.remove()})}isEmpty(){return this._node.innerHTML===""}getChildrenCount(){return this._node.childNodes.length}getNode(){return this._node}}class Ne{_node;_transaction;type=b.Text;config;constructor(e,t,i){this._node=e,this._transaction=t,this.config=i}get textContent(){return this._node.textContent??""}set textContent(e){this._node.textContent=e}remove(){this._transaction.addCommitCallback(()=>{this._node.remove()})}getNode(){return this._node}}function H(n,e,t){if(z(n))return new Ne(n,e,t);if(O(n))return new B(n,e,t);throw new Error("Unsupported node type")}const C="\x1B[106mDOM\x1B[0m";class Se{_transaction;_treeWalker;_config;_completed=!1;_currentNode=null;_previousNode=null;constructor(e,t,i){this._transaction=t,this._config=i,this._treeWalker=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT)}get completed(){return this._completed}get currentNode(){return this._currentNode}get previousNode(){return this._previousNode}nextNode(){this._treeWalker.nextNode()||(this._completed=!0),h.debug(C,"moving to next node"),this.setState()}nextSiblingOrParentSibling(){let e=0;if(this._treeWalker.nextSibling())return h.debug(C,"moving to next sibling node"),this.setState(),{parentsTraversed:e};for(;this._treeWalker.parentNode();)if(e++,this._treeWalker.nextSibling())return h.debug(C,"moving to parent sibling node, traversed:",e),this.setState(),{parentsTraversed:e};return this._completed=!0,{parentsTraversed:e}}firstChildOrNextNode(){return this._treeWalker.firstChild()?(h.debug(C,"moving to first child node"),this.setState(),{parentsTraversed:1}):(this.nextNode(),{parentsTraversed:0})}setState(){this._previousNode=this._currentNode,this._currentNode=H(this._treeWalker.currentNode,this._transaction,he(this._treeWalker.currentNode,this._config)),h.debug(C,"moved to node",{currentNode:this.currentNode,previousNode:this.previousNode})}}class be{_onRollback;_onCommit;isActive;constructor(){this._onRollback=[],this._onCommit=[],this.isActive=!1}start=()=>{if(this.isActive)throw new Error("Transaction already in progress");this.isActive=!0,this._onRollback=[],this._onCommit=[]};addRollbackCallback=e=>{this._onRollback.push(e)};addCommitCallback=e=>{if(!this.isActive){e();return}this._onCommit.push(e)};rollback=()=>{this.isActive&&(this.isActive=!1,this._onRollback.forEach(e=>e()))};commit=()=>{this.isActive&&(this.isActive=!1,this._onCommit.forEach(e=>e()))}}const X="\x1B[102mPAGE\x1B[0m";class E{currentPage;activeElement;currentElement;parentStack;pageIsFull;pageIndex;pageHeight;constructor(e,t,i,o,a,s,f){this.currentPage=e,this.activeElement=t,this.currentElement=i,this.parentStack=o,this.pageIsFull=a,this.pageIndex=s,this.pageHeight=f}static create(e,t,i,o){return new E(e,null,e,t,!1,i,o)}clone=()=>new E(this.currentPage,this.activeElement,this.currentElement,[...this.parentStack],this.pageIsFull,this.pageIndex,this.pageHeight)}class W{_pageState;_transaction;_tempContainer;_config;constructor(e,t,i,o){this._tempContainer=e,this._config=o,this._transaction=i;const a=W.createPageHtmlElement(t.width),s=this.createNewPage(a);this._pageState=E.create(s,[],0,t.height),S(this._config.plugins,"onNewPage",this._pageState)}nextPage(){const e=this.createNewPage(this._pageState.currentPage.getNode().cloneNode(!1)),t=E.create(e,[],this._pageState.pageIndex+1,this._pageState.pageHeight);this.cloneParentStackToNewPage(t),this.cleanupEmptyParent(),this._pageState=t,S(this._config.plugins,"onNewPage",this._pageState)}cloneParentStackToNewPage(e){for(const t of this._pageState.parentStack){const i=t.clone(!1);e.currentElement.appendChild(i),e.currentElement=i,e.parentStack.push(i)}}cleanupEmptyParent(){const e=[...this._pageState.parentStack],t=()=>{for(let i=e.length-1;i>=0;i--){const o=e[i];o.isEmpty()&&o.remove()}};this._transaction.addCommitCallback(t)}enterElement(){if(!this._pageState.activeElement||this._pageState.activeElement.type!==b.Element)throw new Error("Invalid state: activeElement is not an Element");h.debug(X,"entering an element",this._pageState.activeElement),this._pageState.currentElement=this._pageState.activeElement,this._pageState.parentStack.push(this._pageState.activeElement)}leaveElement(){this._pageState.activeElement=null;const e=this._pageState.parentStack.pop();h.debug(X,"leaving a parent element",e);const t=this._pageState.parentStack.at(-1);this._pageState.currentElement=t??this._pageState.currentPage}static createPageHtmlElement(e){const t=document.createElement("div");return t.style.display="flex",t.style.flexDirection="column",t.style.width=`${e}px`,t.style.maxWidth=`${e}px`,t}createNewPage(e){return this._tempContainer.appendChild(e),this._transaction.isActive&&this._transaction.addRollbackCallback(()=>{this._tempContainer.removeChild(e)}),H(e,this._transaction,this._config)}startTransaction(){this._transaction.start();const e=this._pageState.clone();return this._transaction.addRollbackCallback(()=>{this._pageState=e}),this._transaction}hasEmptySpace(e){return!this._pageState.pageIsFull&&this._pageState.currentPage.getHeight()+(e||1)<=this._pageState.pageHeight}isOverFlow(){return this._pageState.currentPage.getHeight()>this._pageState.pageHeight}markPageAsFull(){this._pageState.pageIsFull=!0}appendChild(e,t){const i=e.clone(t);return this._pageState.currentElement.appendChild(i),this._pageState.activeElement=i,i}addTextNode(e){if(this._pageState.activeElement?.type===b.Text)return this._pageState.activeElement;const t=document.createTextNode(e),i=H(t,this._transaction,this._config);return this._pageState.currentElement.appendChild(i),this._pageState.activeElement=i,i}}const p={None:0,FullNodePlaced:1,SplitChildren:2};function ye(n,e){const t=J(n,e);if(t!==p.None)return t;const{rollback:i,commit:o}=e.startTransaction();e.nextPage();const a=J(n,e);return a!==p.None?(o(),a):(i(),h.debug("Element is too big to fit on a page",n),p.None)}function J(n,e){if(e.hasEmptySpace(n.getHeight())){const i=e.appendChild(n,!0);if(e.isOverFlow())i.remove();else return p.FullNodePlaced}if(n.config.keepOnSamePage||n.getChildrenCount()===0)return p.None;const t=e.appendChild(n,!1);return e.isOverFlow()?(t.remove(),p.None):p.SplitChildren}function Ce(n,e){let t=p.FullNodePlaced;const i=n.textContent.split(/(\s+)/).filter(s=>s!=="");let o,a=0;for(;o||a<i.length;){const s=o??i[a],f=Ee(s,e,n.config);f.completed||(t=p.None),f.pendingToken?o=f.pendingToken:(o=void 0,a++)}return t}function Ee(n,e,t){e.hasEmptySpace()||e.nextPage();let i=e.addTextNode("");const o=i.textContent;if(i.textContent+=n,!e.isOverFlow())return{completed:!0};i.textContent=o;const a=we(n,e,t);return{pendingToken:a.leftovers,completed:a.completed}}function we(n,e,t){const{rollback:i,commit:o}=e.startTransaction();if(e.nextPage(),e.addTextNode(n),!e.isOverFlow())return o(),{completed:!0};if(i(),!t.hyphenationEnabled)return h.warn("Hyphenation disabled, skipping oversized token:",n),{completed:!1};const a=ke(n,t.hyphen,e);return{completed:!0,leftovers:a&&a.length>0?a:void 0}}function ke(n,e,t){const i=t.addTextNode("");let o="";for(let a=0;a<n.length;a++){const s=n[a],f=o+s;if(i.textContent=f+e,!t.hasEmptySpace())return i.textContent=o?o+e:"",t.markPageAsFull(),n.slice(a);o=f}return null}const w="\x1B[103mPAGINATOR\x1B[0m";class L{_domState;_pageManager;_transaction;_tempContainer;_config;constructor(e,t,i){this._config={...j,...i},this._tempContainer=L.createTempContainer(),this._transaction=new be,this._domState=new Se(e,this._transaction,this._config),this._pageManager=new W(this._tempContainer,t,this._transaction,this._config)}static createTempContainer(){const e=document.createElement("div");return e.classList.add(M),document.body.appendChild(e),e}static paginate(e,t,i){const o=new L(e,t,i);return o.processAllNodes(),Array.from(o._tempContainer.childNodes).filter(s=>O(s)).map(s=>s.innerHTML)}processAllNodes(){this._domState.nextNode();do{switch(N.debug(w,"paginating node",this._domState.currentNode),this.processCurrentNode()){case p.None:this.handleNodeSkipped();break;case p.FullNodePlaced:this.handleFullNodePlaced();break;case p.SplitChildren:this.handleChildrenSplit();break}S(this._config.plugins,"afterVisitNode",this._domState,this._pageManager)}while(this._domState.completed===!1);N.debug(w,"pagination completed")}handleNodeSkipped(){N.debug(w,"node skipped - couldn't paginate"),this._domState.nextNode()}handleFullNodePlaced(){N.debug(w,"node fully paginated");const{parentsTraversed:e}=this._domState.nextSiblingOrParentSibling();for(let t=0;t<e;t++)this._pageManager.leaveElement()}handleChildrenSplit(){N.debug(w,"node partially paginated - splitting children"),this._domState.firstChildOrNextNode().parentsTraversed===1&&this._domState.previousNode?.type===b.Element&&this._pageManager.enterElement()}processCurrentNode(){if(!this._domState.currentNode)return p.None;if(this._domState.currentNode.type===b.Element){const e={};return S(this._config.plugins,"onVisitElement",this._domState,this._pageManager,e),e.result!==void 0?e.result:ye(this._domState.currentNode,this._pageManager)}else{const e={};return S(this._config.plugins,"onVisitText",this._domState,this._pageManager,e),e.result!==void 0?e.result:Ce(this._domState.currentNode,this._pageManager)}}}const K=["ad","adipisicing","aliqua","aliquip","amet","anim","aute","cillum","commodo","consectetur","consequat","culpa","cupidatat","deserunt","do","dolor","dolore","duis","ea","eiusmod","elit","enim","esse","est","et","eu","ex","excepteur","exercitation","fugiat","id","in","incididunt","ipsum","irure","labore","laboris","laborum","Lorem","magna","minim","mollit","nisi","non","nostrud","nulla","occaecat","officia","pariatur","proident","qui","quis","reprehenderit","sint","sit","sunt","tempor","ullamco","ut","velit","veniam","voluptate"];function xe(n,e){if(n<=0)return"";const t=[],i=Math.floor(e*982451653);for(let o=0;o<n;o++){const a=(i+o*2654435761)%Math.pow(2,32),s=Math.floor(a/Math.pow(2,32)*K.length);t.push(K[s])}return t.length>0&&(t[0]=t[0].charAt(0).toUpperCase()+t[0].slice(1)),t.join(" ")+"."}const Y="data-pz-page-break",Q="pageBreak",Z={name:Q,onVisitElement:(n,e,t)=>{n.currentNode.getNode().getAttribute(Y)==="true"&&(e.markPageAsFull(),t.result=p.FullNodePlaced)}},Te=[Z];l.Paginator=L,l.SplitResult=p,l.attributePrefix=I,l.configToAttributeMap=ge,l.createLoremIpsumParagraph=xe,l.currentElementClassName=oe,l.currentTextClassName=re,l.defaultPlugins=Te,l.enableDebugMode=ce,l.getVisibleHeight=U,l.ignoredElementClassName=ae,l.ignoredTextClassName=se,l.isDebugMode=ue,l.isElement=O,l.isTextNode=z,l.logger=h,l.loggerName=_,l.moveOffscreen=de,l.pageBreakAttributeName=Y,l.pageBreakPlugin=Z,l.pageBreakPluginName=Q,l.pageClassName=le,l.tempContainerClassName=M,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"})}));
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "@paprize/core",
3
+ "version": "0.0.1",
4
+ "description": "Paginate DOM elements for professional, print-ready reports",
5
+ "type": "module",
6
+ "files": [
7
+ "dist",
8
+ "CHANGELOG.md"
9
+ ],
10
+ "main": "./dist/paprize-core.umd.cjs",
11
+ "module": "./dist/paprize-core.js",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/paprize-core.d.ts",
15
+ "import": "./dist/paprize-core.js",
16
+ "require": "./dist/paprize-core.umd.cjs"
17
+ },
18
+ "./src": {
19
+ "types": "./src/index.ts",
20
+ "import": "./src/index.ts"
21
+ },
22
+ "./src/debug-styles.css": "./src/debugUtilities/styles.css"
23
+ },
24
+ "keywords": [
25
+ "paper",
26
+ "print",
27
+ "report",
28
+ "html2pdf",
29
+ "pdf"
30
+ ],
31
+ "homepage": "https://github.com/PejmanNik/paprize#readme",
32
+ "bugs": {
33
+ "url": "https://github.com/PejmanNik/paprize/issues"
34
+ },
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/PejmanNik/paprize.git"
38
+ },
39
+ "license": "Apache-2.0",
40
+ "author": "PejmanNikram",
41
+ "scripts": {
42
+ "dev": "vite",
43
+ "test": "vitest",
44
+ "coverage": "vitest run --coverage",
45
+ "build": "tsc && vite build",
46
+ "preview": "vite preview",
47
+ "prepack": "node ../../scripts/prepack.mjs"
48
+ },
49
+ "devDependencies": {
50
+ "@microsoft/api-extractor": "^7.52.10",
51
+ "@vitest/coverage-v8": "^3.2.4",
52
+ "happy-dom": "^18.0.1",
53
+ "preact": "^10.27.0",
54
+ "typescript": "~5.8.3",
55
+ "unplugin-dts": "^1.0.0-beta.6",
56
+ "vite": "^7.0.4",
57
+ "vite-plugin-checker": "^0.10.2",
58
+ "vitest": "^3.2.4"
59
+ },
60
+ "dependencies": {
61
+ "loglevel": "^1.9.2"
62
+ }
63
+ }