@papyrus-sdk/engine-epub 0.2.6 → 0.2.7

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/dist/index.mjs CHANGED
@@ -1,17 +1,48 @@
1
1
  // index.ts
2
2
  import ePub from "epubjs";
3
3
  import { BaseDocumentEngine } from "@papyrus-sdk/core";
4
- var EPUBEngine = class extends BaseDocumentEngine {
4
+ var EPUBEngine = class _EPUBEngine extends BaseDocumentEngine {
5
5
  constructor() {
6
6
  super(...arguments);
7
7
  this.book = null;
8
8
  this.spineItems = [];
9
- this.renditions = /* @__PURE__ */ new Map();
10
- this.renditionTargets = /* @__PURE__ */ new Map();
9
+ this.coverUrl = null;
10
+ this.readerRendition = null;
11
+ this.readerTarget = null;
11
12
  this.pageSizes = /* @__PURE__ */ new Map();
12
13
  this.currentPage = 1;
13
14
  this.zoom = 1;
14
15
  this.rotation = 0;
16
+ this.heightSyncVersion = 0;
17
+ this.renderVersion = 0;
18
+ this.renderLock = Promise.resolve();
19
+ this.pendingHrefDestination = null;
20
+ this.destinationSequence = [];
21
+ this.destinationCursor = -1;
22
+ this.lastDestinationNavTime = 0;
23
+ this.lastDestinationPageIndex = null;
24
+ this.lastDestinationHref = null;
25
+ }
26
+ static {
27
+ this.A4_RATIO = 1.4142;
28
+ }
29
+ static {
30
+ this.USE_INTERNAL_IFRAME_SCROLL = true;
31
+ }
32
+ static {
33
+ this.MOBILE_VIEWPORT_MAX_WIDTH_PX = 768;
34
+ }
35
+ static {
36
+ this.MOBILE_SHORT_VIEWPORT_MAX_HEIGHT_PX = 500;
37
+ }
38
+ static {
39
+ this.INTERNAL_VIEWPORT_PADDING_PX = 10;
40
+ }
41
+ static {
42
+ this.MAX_SECTION_HEIGHT = 1e6;
43
+ }
44
+ static {
45
+ this.HEIGHT_PADDING = 24;
15
46
  }
16
47
  getRenderTargetType() {
17
48
  return "element";
@@ -20,34 +51,243 @@ var EPUBEngine = class extends BaseDocumentEngine {
20
51
  try {
21
52
  const { source, type } = this.normalizeLoadInput(input);
22
53
  if (type && type !== "epub") {
23
- throw new Error(`[EPUBEngine] Tipo de documento n\xE3o suportado: ${type}`);
54
+ throw new Error(
55
+ `[EPUBEngine] Tipo de documento n\xE3o suportado: ${type}`
56
+ );
24
57
  }
58
+ this.renderVersion += 1;
59
+ this.renderLock = Promise.resolve();
60
+ this.disposeReader();
61
+ this.pageSizes.clear();
62
+ this.spineItems = [];
63
+ this.coverUrl = null;
64
+ this.destinationSequence = [];
65
+ this.destinationCursor = -1;
66
+ this.lastDestinationNavTime = 0;
67
+ this.lastDestinationPageIndex = null;
68
+ this.lastDestinationHref = null;
69
+ if (this.book?.destroy) this.book.destroy();
25
70
  const data = await this.resolveSource(source);
26
71
  this.book = ePub(data);
72
+ if (this.book?.opened) {
73
+ await this.book.opened;
74
+ }
27
75
  await this.book.ready;
28
- this.spineItems = this.book.spine?.items ?? [];
76
+ const packaging = this.book?.package ?? this.book?.packaging ?? null;
77
+ if (!packaging) {
78
+ throw new Error("[EPUBEngine] packaging indisponivel.");
79
+ }
80
+ if (!this.book.package) {
81
+ this.book.package = packaging;
82
+ }
83
+ if (!this.book.packaging) {
84
+ this.book.packaging = packaging;
85
+ }
86
+ if (this.book?.loaded?.navigation) {
87
+ await this.book.loaded.navigation;
88
+ }
89
+ this.spineItems = this.getLinearSpineItems(this.book.spine?.items ?? []);
90
+ if (typeof this.book.coverUrl === "function") {
91
+ try {
92
+ const resolvedCover = await this.book.coverUrl();
93
+ if (typeof resolvedCover === "string" && resolvedCover.length > 0) {
94
+ this.coverUrl = resolvedCover;
95
+ }
96
+ } catch {
97
+ this.coverUrl = null;
98
+ }
99
+ }
29
100
  this.currentPage = 1;
30
- this.renditions.forEach((rendition) => rendition?.destroy?.());
31
- this.renditions.clear();
32
- this.renditionTargets.clear();
33
- this.pageSizes.clear();
34
101
  } catch (error) {
35
102
  console.error("[EPUBEngine] Erro ao carregar:", error);
36
103
  throw error;
37
104
  }
38
105
  }
39
106
  getPageCount() {
40
- return this.spineItems.length;
107
+ return this.spineItems.length + (this.hasCoverPage() ? 1 : 0);
41
108
  }
42
109
  getCurrentPage() {
43
110
  return this.currentPage;
44
111
  }
45
112
  goToPage(page) {
46
- if (page >= 1 && page <= this.getPageCount()) this.currentPage = page;
113
+ if (page < 1 || page > this.getPageCount()) return;
114
+ this.currentPage = page;
115
+ this.pendingHrefDestination = null;
116
+ if (this.destinationSequence.length) {
117
+ const destinationIndex = this.findNearestDestinationIndexByPage(page - 1);
118
+ if (destinationIndex >= 0) this.destinationCursor = destinationIndex;
119
+ }
120
+ }
121
+ async goToDestination(dest) {
122
+ const href = this.extractHrefDestination(dest);
123
+ if (!href) {
124
+ const pageIndex = await this.getPageIndex(dest);
125
+ if (pageIndex != null) this.goToPage(pageIndex + 1);
126
+ return pageIndex;
127
+ }
128
+ const baseHref = this.normalizeHref(href);
129
+ const currentBaseHref = this.lastDestinationHref ? this.normalizeHref(this.lastDestinationHref) : null;
130
+ const hasAnchor = href.includes("#");
131
+ if (!hasAnchor && currentBaseHref && baseHref === currentBaseHref && this.readerRendition) {
132
+ this.debugLog("goToDestination:skip-same-base", {
133
+ href,
134
+ currentBaseHref
135
+ });
136
+ const pageIndex = await this.resolvePageIndexFromHref(href);
137
+ return pageIndex;
138
+ }
139
+ let releaseCurrent = null;
140
+ const previousRender = this.renderLock;
141
+ this.renderLock = new Promise((resolve) => {
142
+ releaseCurrent = resolve;
143
+ });
144
+ await previousRender;
145
+ try {
146
+ this.pendingHrefDestination = href;
147
+ let pageIndex = await this.resolvePageIndexFromHref(href);
148
+ if (pageIndex != null) this.currentPage = pageIndex + 1;
149
+ this.debugLog("goToDestination:start", {
150
+ href,
151
+ pageIndex,
152
+ currentPage: this.currentPage
153
+ });
154
+ const rendition = this.readerRendition;
155
+ let displayFailed = false;
156
+ if (rendition) {
157
+ try {
158
+ const didDisplay = await this.displayDestinationWithRetry(
159
+ rendition,
160
+ href
161
+ );
162
+ if (!didDisplay)
163
+ throw new Error("Destination display retry exhausted");
164
+ if (pageIndex == null) {
165
+ const locationPageIndex = this.getPageIndexFromRenditionLocation(rendition);
166
+ if (locationPageIndex != null) {
167
+ pageIndex = locationPageIndex;
168
+ this.currentPage = locationPageIndex + 1;
169
+ }
170
+ }
171
+ this.debugLog("goToDestination:displayed", {
172
+ href,
173
+ pageIndex,
174
+ currentPage: this.currentPage
175
+ });
176
+ this.updateDestinationCursor(href, pageIndex);
177
+ this.pendingHrefDestination = null;
178
+ this.lastDestinationNavTime = Date.now();
179
+ this.lastDestinationPageIndex = pageIndex;
180
+ this.lastDestinationHref = href;
181
+ return pageIndex;
182
+ } catch {
183
+ displayFailed = true;
184
+ this.debugLog("goToDestination:display-failed", { href, pageIndex });
185
+ }
186
+ }
187
+ if (displayFailed && pageIndex != null && this.readerTarget && typeof this.readerTarget.isConnected === "boolean" && this.readerTarget.isConnected) {
188
+ void this.renderPage(pageIndex, this.readerTarget, 1).catch(() => {
189
+ });
190
+ }
191
+ this.debugLog("goToDestination:no-rendition", {
192
+ href,
193
+ pageIndex,
194
+ currentPage: this.currentPage
195
+ });
196
+ this.updateDestinationCursor(href, pageIndex);
197
+ return pageIndex;
198
+ } finally {
199
+ releaseCurrent?.();
200
+ }
201
+ }
202
+ async goToAdjacentDestination(delta) {
203
+ if (!Number.isFinite(delta) || delta === 0) return this.currentPage - 1;
204
+ await this.ensureDestinationSequence();
205
+ if (!this.destinationSequence.length) {
206
+ const basePageIndex = Math.max(0, this.currentPage - 1);
207
+ const nextPageIndex = Math.max(
208
+ 0,
209
+ Math.min(this.getPageCount() - 1, basePageIndex + (delta > 0 ? 1 : -1))
210
+ );
211
+ if (nextPageIndex === basePageIndex) return basePageIndex;
212
+ this.goToPage(nextPageIndex + 1);
213
+ return nextPageIndex;
214
+ }
215
+ if (this.destinationCursor < 0) {
216
+ const inferred = this.findNearestDestinationIndexByPage(
217
+ this.currentPage - 1
218
+ );
219
+ this.destinationCursor = inferred >= 0 ? inferred : 0;
220
+ }
221
+ const currentEntry = this.destinationSequence[this.destinationCursor];
222
+ const currentBaseHref = currentEntry ? this.normalizeHref(currentEntry.href) : null;
223
+ this.debugLog("goToAdjacentDestination:start", {
224
+ delta,
225
+ cursor: this.destinationCursor,
226
+ total: this.destinationSequence.length,
227
+ currentPage: this.currentPage,
228
+ currentBaseHref
229
+ });
230
+ const step = delta > 0 ? 1 : -1;
231
+ let nextIndex = this.destinationCursor;
232
+ const limit = delta > 0 ? this.destinationSequence.length - 1 : 0;
233
+ while (true) {
234
+ const candidate = nextIndex + step;
235
+ if (candidate < 0 || candidate > this.destinationSequence.length - 1)
236
+ break;
237
+ nextIndex = candidate;
238
+ const candidateBaseHref = this.normalizeHref(
239
+ this.destinationSequence[nextIndex].href
240
+ );
241
+ if (!currentBaseHref || candidateBaseHref !== currentBaseHref) break;
242
+ }
243
+ if (nextIndex === this.destinationCursor) {
244
+ this.debugLog("goToAdjacentDestination:at-boundary", {
245
+ delta,
246
+ cursor: this.destinationCursor
247
+ });
248
+ const current = this.destinationSequence[this.destinationCursor];
249
+ return current?.pageIndex ?? this.currentPage - 1;
250
+ }
251
+ const target = this.destinationSequence[nextIndex];
252
+ if (!target) return null;
253
+ this.destinationCursor = nextIndex;
254
+ const resolved = await this.goToDestination({
255
+ kind: "href",
256
+ value: target.href
257
+ });
258
+ if (resolved != null) {
259
+ this.debugLog("goToAdjacentDestination:resolved", {
260
+ delta,
261
+ nextIndex,
262
+ href: target.href,
263
+ resolved
264
+ });
265
+ return resolved;
266
+ }
267
+ this.destinationCursor = nextIndex - step;
268
+ this.debugLog("goToAdjacentDestination:failed", {
269
+ delta,
270
+ nextIndex,
271
+ href: target.href
272
+ });
273
+ return null;
274
+ }
275
+ getDestinationNavigationState() {
276
+ const total = this.destinationSequence.length;
277
+ if (!total) {
278
+ return {
279
+ hasPrev: this.currentPage > 1,
280
+ hasNext: this.currentPage < this.getPageCount()
281
+ };
282
+ }
283
+ const cursor = this.destinationCursor >= 0 ? this.destinationCursor : this.findNearestDestinationIndexByPage(this.currentPage - 1);
284
+ return {
285
+ hasPrev: cursor > 0,
286
+ hasNext: cursor >= 0 && cursor < total - 1
287
+ };
47
288
  }
48
289
  setZoom(zoom) {
49
290
  this.zoom = Math.max(0.5, Math.min(3, zoom));
50
- this.renditions.forEach((rendition) => this.applyRenditionTheme(rendition));
51
291
  }
52
292
  getZoom() {
53
293
  return this.zoom;
@@ -71,45 +311,154 @@ var EPUBEngine = class extends BaseDocumentEngine {
71
311
  return null;
72
312
  }
73
313
  async renderPage(pageIndex, target, scale) {
74
- const scaleKey = Math.round(scale * 1e3);
75
- const element = target;
76
- if (!this.book || !element) return;
77
- const spineItem = this.spineItems[pageIndex];
78
- if (!spineItem) return;
79
- const width = element.clientWidth > 0 ? element.clientWidth : 640;
80
- const height = element.clientHeight > 0 ? element.clientHeight : 900;
81
- element.style.width = `${width}px`;
82
- element.style.height = `${height}px`;
83
- if (width >= 320 && height >= 480) this.pageSizes.set(pageIndex, { width, height });
84
- const renditionKey = `${pageIndex}:${scaleKey}`;
85
- let rendition = this.renditions.get(renditionKey);
86
- const currentTarget = this.renditionTargets.get(renditionKey);
87
- if (!rendition || currentTarget !== element) {
88
- if (rendition?.destroy) rendition.destroy();
89
- element.innerHTML = "";
90
- rendition = this.book.renderTo(element, {
91
- width,
92
- height,
93
- flow: "paginated",
94
- spread: "none"
95
- });
96
- this.renditions.set(renditionKey, rendition);
97
- this.renditionTargets.set(renditionKey, element);
98
- if (rendition?.hooks?.content?.register) {
99
- rendition.hooks.content.register((contents) => {
100
- const frame = contents?.document?.defaultView?.frameElement;
101
- if (frame) {
102
- frame.setAttribute("sandbox", "allow-scripts allow-same-origin");
314
+ let releaseCurrent = null;
315
+ const previousRender = this.renderLock;
316
+ this.renderLock = new Promise((resolve) => {
317
+ releaseCurrent = resolve;
318
+ });
319
+ await previousRender;
320
+ try {
321
+ const pageCount = this.getPageCount();
322
+ if (pageCount <= 0) return;
323
+ const safePageIndex = Math.max(0, Math.min(pageCount - 1, pageIndex));
324
+ const renderVersion = ++this.renderVersion;
325
+ const element = target;
326
+ if (!this.book || !element) return;
327
+ const width = element.clientWidth > 0 ? element.clientWidth : 640;
328
+ const viewportHeightHint = _EPUBEngine.USE_INTERNAL_IFRAME_SCROLL ? this.getViewportHeightHint(element) : null;
329
+ const rawHeight = viewportHeightHint ?? (element.clientHeight > 0 ? element.clientHeight : 900);
330
+ const normalizedHeight = _EPUBEngine.USE_INTERNAL_IFRAME_SCROLL ? Math.max(360, Math.min(4e3, rawHeight)) : Math.max(480, Math.min(1400, rawHeight));
331
+ const minA4Height = _EPUBEngine.USE_INTERNAL_IFRAME_SCROLL ? 0 : this.getA4MinHeight(width);
332
+ const seedHeight = _EPUBEngine.USE_INTERNAL_IFRAME_SCROLL ? normalizedHeight : Math.max(minA4Height, normalizedHeight);
333
+ if (this.isCoverPage(safePageIndex)) {
334
+ this.renderCoverPage(element, width, seedHeight, safePageIndex);
335
+ if (renderVersion === this.renderVersion) {
336
+ this.currentPage = safePageIndex + 1;
337
+ }
338
+ return;
339
+ }
340
+ const spineItem = this.getSpineItemForPage(safePageIndex);
341
+ if (!spineItem) return;
342
+ const displayTargets = [...this.getDisplayTargetsForSpineItem(spineItem)];
343
+ if (!displayTargets.length) return;
344
+ const defaultSectionIndex = typeof spineItem.index === "number" ? spineItem.index : null;
345
+ const pendingHrefDestination = this.pendingHrefDestination;
346
+ let consumedPendingHref = false;
347
+ if (pendingHrefDestination) {
348
+ const pendingPageIndex = await this.resolvePageIndexFromHref(
349
+ pendingHrefDestination
350
+ );
351
+ const pendingMatchesCurrentPage = pendingPageIndex === safePageIndex || this.isHrefMatchingSpineItem(pendingHrefDestination, spineItem);
352
+ if (pendingMatchesCurrentPage) {
353
+ consumedPendingHref = true;
354
+ displayTargets.unshift(
355
+ pendingHrefDestination,
356
+ this.decodeHref(pendingHrefDestination)
357
+ );
358
+ }
359
+ }
360
+ const uniqueTargets = this.uniqueDisplayTargets(displayTargets);
361
+ if (!uniqueTargets.length) return;
362
+ element.style.width = `${width}px`;
363
+ element.style.height = `${seedHeight}px`;
364
+ if (width >= 320 && seedHeight >= 480)
365
+ this.pageSizes.set(safePageIndex, { width, height: seedHeight });
366
+ let rendition = this.readerRendition;
367
+ if (!rendition || this.readerTarget !== element) {
368
+ this.disposeReader();
369
+ element.innerHTML = "";
370
+ rendition = this.createRendition(element, width, seedHeight);
371
+ this.readerRendition = rendition;
372
+ this.readerTarget = element;
373
+ } else if (typeof rendition.resize === "function" && rendition.manager?.resize) {
374
+ try {
375
+ rendition.resize(width, seedHeight);
376
+ } catch (error) {
377
+ this.disposeReader();
378
+ element.innerHTML = "";
379
+ rendition = this.createRendition(element, width, seedHeight);
380
+ this.readerRendition = rendition;
381
+ this.readerTarget = element;
382
+ }
383
+ }
384
+ if (rendition) {
385
+ const syncVersion = ++this.heightSyncVersion;
386
+ this.applyRenditionTheme(rendition);
387
+ if (renderVersion !== this.renderVersion) return;
388
+ const recentDestNav = Date.now() - this.lastDestinationNavTime < 200 && this.lastDestinationPageIndex === safePageIndex;
389
+ if (recentDestNav) {
390
+ this.debugLog("renderPage:skip-recent-dest-nav", {
391
+ safePageIndex,
392
+ msSince: Date.now() - this.lastDestinationNavTime
393
+ });
394
+ await this.syncSectionHeight(
395
+ rendition,
396
+ element,
397
+ safePageIndex,
398
+ width,
399
+ seedHeight,
400
+ defaultSectionIndex,
401
+ true
402
+ );
403
+ if (renderVersion !== this.renderVersion) return;
404
+ this.scheduleHeightSync(
405
+ syncVersion,
406
+ rendition,
407
+ element,
408
+ safePageIndex,
409
+ width,
410
+ seedHeight,
411
+ defaultSectionIndex,
412
+ true
413
+ );
414
+ if (renderVersion === this.renderVersion) {
415
+ this.currentPage = safePageIndex + 1;
103
416
  }
104
- });
417
+ } else {
418
+ const sectionIndex = await this.displayWithFallback(
419
+ rendition,
420
+ uniqueTargets,
421
+ () => renderVersion !== this.renderVersion
422
+ );
423
+ if (sectionIndex === void 0) return;
424
+ if (renderVersion !== this.renderVersion) return;
425
+ if (consumedPendingHref && pendingHrefDestination && pendingHrefDestination.includes("#")) {
426
+ const anchored = await this.displayDestinationWithRetry(
427
+ rendition,
428
+ pendingHrefDestination
429
+ );
430
+ this.debugLog("renderPage:anchor-second-pass", {
431
+ href: pendingHrefDestination,
432
+ anchored
433
+ });
434
+ if (renderVersion !== this.renderVersion) return;
435
+ }
436
+ await this.syncSectionHeight(
437
+ rendition,
438
+ element,
439
+ safePageIndex,
440
+ width,
441
+ seedHeight,
442
+ sectionIndex ?? defaultSectionIndex
443
+ );
444
+ if (renderVersion !== this.renderVersion) return;
445
+ this.scheduleHeightSync(
446
+ syncVersion,
447
+ rendition,
448
+ element,
449
+ safePageIndex,
450
+ width,
451
+ seedHeight,
452
+ sectionIndex ?? defaultSectionIndex
453
+ );
454
+ if (renderVersion === this.renderVersion) {
455
+ if (consumedPendingHref) this.pendingHrefDestination = null;
456
+ this.currentPage = safePageIndex + 1;
457
+ }
458
+ }
105
459
  }
106
- } else if (typeof rendition.resize === "function") {
107
- rendition.resize(width, height);
108
- }
109
- if (rendition) {
110
- this.applyRenditionTheme(rendition);
111
- const targetRef = spineItem.href || spineItem.idref || spineItem.cfiBase || pageIndex;
112
- await rendition.display(targetRef);
460
+ } finally {
461
+ releaseCurrent?.();
113
462
  }
114
463
  }
115
464
  async renderTextLayer(pageIndex, container, scale) {
@@ -118,20 +467,25 @@ var EPUBEngine = class extends BaseDocumentEngine {
118
467
  }
119
468
  async getTextContent(pageIndex) {
120
469
  if (!this.book) return [];
121
- const spineItem = this.spineItems[pageIndex];
470
+ if (this.isCoverPage(pageIndex)) return [];
471
+ const spineIndex = this.toSpineIndex(pageIndex);
472
+ if (spineIndex < 0) return [];
473
+ const spineItem = this.spineItems[spineIndex];
122
474
  if (!spineItem) return [];
123
475
  try {
124
476
  const section = this.book.spine.get(spineItem.idref || spineItem.href);
125
477
  const text = typeof section?.text === "function" ? await section.text() : "";
126
478
  if (!text) return [];
127
- return [{
128
- str: text,
129
- dir: "ltr",
130
- width: 0,
131
- height: 0,
132
- transform: [1, 0, 0, 1, 0, 0],
133
- fontName: "default"
134
- }];
479
+ return [
480
+ {
481
+ str: text,
482
+ dir: "ltr",
483
+ width: 0,
484
+ height: 0,
485
+ transform: [1, 0, 0, 1, 0, 0],
486
+ fontName: "default"
487
+ }
488
+ ];
135
489
  } catch {
136
490
  return [];
137
491
  }
@@ -141,36 +495,53 @@ var EPUBEngine = class extends BaseDocumentEngine {
141
495
  const nav = await this.book.loaded?.navigation;
142
496
  const toc = nav?.toc ?? [];
143
497
  if (!toc.length) return [];
144
- const mapItem = (item) => {
498
+ await this.ensureDestinationSequence();
499
+ const mapItem = async (item) => {
145
500
  const title = item.label || item.title || "";
146
- const pageIndex = this.getSpineIndexByHref(item.href || "");
147
- const children = Array.isArray(item.subitems) ? item.subitems.map(mapItem) : [];
501
+ const href = item.href || "";
502
+ const resolvedIndex = await this.resolvePageIndexFromHref(href);
503
+ const pageIndex = resolvedIndex ?? -1;
504
+ const children = Array.isArray(item.subitems) ? await Promise.all(item.subitems.map(mapItem)) : [];
148
505
  const outlineItem = { title, pageIndex };
506
+ if (href) {
507
+ outlineItem.dest = { kind: "href", value: href };
508
+ }
149
509
  if (children.length > 0) outlineItem.children = children;
150
510
  return outlineItem;
151
511
  };
152
- return toc.map(mapItem);
512
+ return await Promise.all(toc.map(mapItem));
153
513
  }
154
514
  async getPageIndex(dest) {
155
515
  if (!dest) return null;
156
- if (typeof dest === "string") return this.getSpineIndexByHref(dest);
157
- if (dest.kind === "href") return this.getSpineIndexByHref(dest.value);
158
- if (dest.kind === "pageIndex") return dest.value;
159
- if (dest.kind === "pageNumber") return Math.max(0, dest.value - 1);
516
+ if (typeof dest === "string")
517
+ return await this.resolvePageIndexFromHref(dest);
518
+ if (dest.kind === "href")
519
+ return await this.resolvePageIndexFromHref(dest.value);
520
+ if (dest.kind === "pageIndex")
521
+ return Math.max(0, Math.min(this.getPageCount() - 1, dest.value));
522
+ if (dest.kind === "pageNumber")
523
+ return Math.max(0, Math.min(this.getPageCount() - 1, dest.value - 1));
160
524
  return null;
161
525
  }
162
526
  destroy() {
163
- this.renditions.forEach((rendition) => rendition?.destroy?.());
164
- this.renditions.clear();
165
- this.renditionTargets.clear();
527
+ this.renderVersion += 1;
528
+ this.renderLock = Promise.resolve();
529
+ this.pendingHrefDestination = null;
530
+ this.destinationSequence = [];
531
+ this.destinationCursor = -1;
532
+ this.lastDestinationNavTime = 0;
533
+ this.lastDestinationPageIndex = null;
534
+ this.lastDestinationHref = null;
535
+ this.disposeReader();
166
536
  this.pageSizes.clear();
167
537
  if (this.book?.destroy) this.book.destroy();
168
538
  this.book = null;
169
539
  this.spineItems = [];
540
+ this.coverUrl = null;
170
541
  }
171
542
  applyRenditionTheme(rendition) {
172
543
  if (!rendition) return;
173
- const fontSize = `${Math.round(this.zoom * 100)}%`;
544
+ const fontSize = "100%";
174
545
  if (rendition.themes?.fontSize) {
175
546
  rendition.themes.fontSize(fontSize);
176
547
  } else if (rendition.themes?.override) {
@@ -179,13 +550,457 @@ var EPUBEngine = class extends BaseDocumentEngine {
179
550
  }
180
551
  getSpineIndexByHref(href) {
181
552
  const normalized = this.normalizeHref(href);
553
+ const decoded = this.decodeHref(normalized);
182
554
  if (!normalized) return -1;
183
- const index = this.spineItems.findIndex((item) => this.normalizeHref(item.href) === normalized);
184
- return index;
555
+ const candidates = new Set([normalized, decoded].filter(Boolean));
556
+ const exactIndex = this.spineItems.findIndex((item) => {
557
+ const itemHref = this.normalizeHref(item.href);
558
+ const itemDecoded = this.decodeHref(itemHref);
559
+ return candidates.has(itemHref) || candidates.has(itemDecoded);
560
+ });
561
+ if (exactIndex >= 0) return exactIndex;
562
+ return this.spineItems.findIndex((item) => {
563
+ const itemHref = this.normalizeHref(item.href);
564
+ if (!itemHref) return false;
565
+ const itemDecoded = this.decodeHref(itemHref);
566
+ for (const candidate of candidates) {
567
+ if (itemHref.endsWith(candidate) || candidate.endsWith(itemHref) || itemDecoded.endsWith(candidate) || candidate.endsWith(itemDecoded)) {
568
+ return true;
569
+ }
570
+ }
571
+ return false;
572
+ });
185
573
  }
186
574
  normalizeHref(href) {
575
+ if (!href) return "";
187
576
  return href.split("#")[0];
188
577
  }
578
+ decodeHref(href) {
579
+ if (!href) return "";
580
+ try {
581
+ return decodeURIComponent(href);
582
+ } catch {
583
+ return href;
584
+ }
585
+ }
586
+ getSectionFromHref(href) {
587
+ const normalized = this.normalizeHref(href);
588
+ if (!normalized || !this.book?.spine?.get) return null;
589
+ const decoded = this.decodeHref(normalized);
590
+ const candidates = [normalized, decoded];
591
+ for (const candidate of candidates) {
592
+ if (!candidate) continue;
593
+ try {
594
+ const section = this.book.spine.get(candidate);
595
+ if (section) return section;
596
+ } catch {
597
+ }
598
+ }
599
+ return null;
600
+ }
601
+ getSpineItemForPage(pageIndex) {
602
+ const spineIndex = this.toSpineIndex(pageIndex);
603
+ if (spineIndex < 0 || spineIndex >= this.spineItems.length) return null;
604
+ return this.spineItems[spineIndex] ?? null;
605
+ }
606
+ getSpineIndexForSection(section) {
607
+ if (!section) return -1;
608
+ const sectionIdRef = typeof section?.idref === "string" ? section.idref.trim() : "";
609
+ if (sectionIdRef) {
610
+ const idrefIndex = this.spineItems.findIndex(
611
+ (item) => typeof item?.idref === "string" && item.idref.trim() === sectionIdRef
612
+ );
613
+ if (idrefIndex >= 0) return idrefIndex;
614
+ }
615
+ const sectionHref = typeof section?.href === "string" ? this.normalizeHref(section.href) : "";
616
+ if (sectionHref) {
617
+ const hrefIndex = this.getSpineIndexByHref(sectionHref);
618
+ if (hrefIndex >= 0) return hrefIndex;
619
+ }
620
+ if (typeof section?.index === "number" && section.index >= 0) {
621
+ const directItem = this.spineItems[section.index];
622
+ if (directItem) {
623
+ const directHref = this.normalizeHref(directItem?.href ?? "");
624
+ const directIdRef = typeof directItem?.idref === "string" ? directItem.idref.trim() : "";
625
+ const hasSameHref = Boolean(sectionHref && directHref === sectionHref);
626
+ const hasSameIdRef = Boolean(
627
+ sectionIdRef && directIdRef && directIdRef === sectionIdRef
628
+ );
629
+ if (hasSameHref || hasSameIdRef) return section.index;
630
+ }
631
+ }
632
+ return -1;
633
+ }
634
+ getPageIndexFromSection(section) {
635
+ const spineIndex = this.getSpineIndexForSection(section);
636
+ if (spineIndex < 0) return null;
637
+ return this.toPageIndexFromSpine(spineIndex);
638
+ }
639
+ isHrefMatchingSpineItem(href, spineItem) {
640
+ const normalizedCandidate = this.normalizeHref(href);
641
+ if (!normalizedCandidate) return false;
642
+ const decodedCandidate = this.decodeHref(normalizedCandidate);
643
+ const itemHref = this.normalizeHref(spineItem?.href ?? "");
644
+ if (!itemHref) return false;
645
+ const itemDecoded = this.decodeHref(itemHref);
646
+ for (const candidate of [normalizedCandidate, decodedCandidate]) {
647
+ if (!candidate) continue;
648
+ if (itemHref === candidate || itemDecoded === candidate || itemHref.endsWith(candidate) || candidate.endsWith(itemHref) || itemDecoded.endsWith(candidate) || candidate.endsWith(itemDecoded)) {
649
+ return true;
650
+ }
651
+ }
652
+ return false;
653
+ }
654
+ uniqueDisplayTargets(targets) {
655
+ const deduped = [];
656
+ const seen = /* @__PURE__ */ new Set();
657
+ for (const target of targets) {
658
+ if (typeof target !== "string" && typeof target !== "number") continue;
659
+ const normalized = typeof target === "string" ? target.trim() : String(target).trim();
660
+ if (!normalized) continue;
661
+ const key = `${typeof target}:${normalized}`;
662
+ if (seen.has(key)) continue;
663
+ seen.add(key);
664
+ deduped.push(target);
665
+ }
666
+ return deduped;
667
+ }
668
+ getDisplayTargetsForSpineItem(spineItem) {
669
+ const targets = [];
670
+ const seen = /* @__PURE__ */ new Set();
671
+ const pushTarget = (value) => {
672
+ if (typeof value !== "string" && typeof value !== "number") return;
673
+ const normalized = typeof value === "string" ? value.trim() : String(value).trim();
674
+ if (!normalized) return;
675
+ const key = `${typeof value}:${normalized}`;
676
+ if (seen.has(key)) return;
677
+ seen.add(key);
678
+ targets.push(value);
679
+ };
680
+ pushTarget(spineItem?.href);
681
+ pushTarget(this.decodeHref(spineItem?.href ?? ""));
682
+ pushTarget(spineItem?.idref);
683
+ pushTarget(spineItem?.cfiBase);
684
+ if (typeof spineItem?.index === "number") pushTarget(spineItem.index);
685
+ const sectionFromHref = this.getSectionFromHref(spineItem?.href ?? "");
686
+ if (sectionFromHref) {
687
+ pushTarget(sectionFromHref.href);
688
+ pushTarget(sectionFromHref.idref);
689
+ pushTarget(sectionFromHref.cfiBase);
690
+ if (typeof sectionFromHref.index === "number")
691
+ pushTarget(sectionFromHref.index);
692
+ }
693
+ return targets;
694
+ }
695
+ normalizeDestinationKey(href) {
696
+ if (!href) return "";
697
+ const trimmed = href.trim();
698
+ if (!trimmed) return "";
699
+ return this.decodeHref(trimmed).toLowerCase();
700
+ }
701
+ findDestinationIndexByHref(href) {
702
+ const candidate = this.normalizeDestinationKey(href);
703
+ if (!candidate || !this.destinationSequence.length) return -1;
704
+ const exact = this.destinationSequence.findIndex(
705
+ (entry) => this.normalizeDestinationKey(entry.href) === candidate
706
+ );
707
+ if (exact >= 0) return exact;
708
+ return this.destinationSequence.findIndex((entry) => {
709
+ const key = this.normalizeDestinationKey(entry.href);
710
+ return key === candidate || key.endsWith(candidate) || candidate.endsWith(key);
711
+ });
712
+ }
713
+ findNearestDestinationIndexByPage(pageIndex) {
714
+ if (!this.destinationSequence.length) return -1;
715
+ const candidates = this.destinationSequence.map((entry, idx) => ({ idx, pageIndex: entry.pageIndex })).filter((entry) => entry.pageIndex <= pageIndex);
716
+ if (candidates.length) return candidates[candidates.length - 1].idx;
717
+ const firstNext = this.destinationSequence.findIndex(
718
+ (entry) => entry.pageIndex >= pageIndex
719
+ );
720
+ return firstNext >= 0 ? firstNext : this.destinationSequence.length - 1;
721
+ }
722
+ async ensureDestinationSequence() {
723
+ if (this.destinationSequence.length) return;
724
+ if (!this.book?.loaded?.navigation) return;
725
+ const nav = await this.book.loaded.navigation;
726
+ const toc = nav?.toc ?? [];
727
+ if (!Array.isArray(toc) || !toc.length) return;
728
+ const hrefs = [];
729
+ const walk = (items) => {
730
+ for (const item of items) {
731
+ const href = typeof item?.href === "string" ? item.href.trim() : "";
732
+ if (href) hrefs.push(href);
733
+ if (Array.isArray(item?.subitems) && item.subitems.length) {
734
+ walk(item.subitems);
735
+ }
736
+ }
737
+ };
738
+ walk(toc);
739
+ if (!hrefs.length) return;
740
+ const deduped = [];
741
+ const seen = /* @__PURE__ */ new Set();
742
+ for (const href of hrefs) {
743
+ const key = this.normalizeDestinationKey(href);
744
+ if (!key || seen.has(key)) continue;
745
+ seen.add(key);
746
+ deduped.push(href);
747
+ }
748
+ const sequence = [];
749
+ for (const href of deduped) {
750
+ const pageIndex = await this.resolvePageIndexFromHref(href);
751
+ if (pageIndex == null) continue;
752
+ sequence.push({ href, pageIndex });
753
+ }
754
+ this.destinationSequence = sequence;
755
+ if (this.destinationCursor < 0 && sequence.length) {
756
+ this.destinationCursor = this.findNearestDestinationIndexByPage(
757
+ this.currentPage - 1
758
+ );
759
+ }
760
+ }
761
+ updateDestinationCursor(href, pageIndex) {
762
+ if (!this.destinationSequence.length) {
763
+ void this.ensureDestinationSequence().then(() => {
764
+ if (!this.destinationSequence.length) return;
765
+ this.updateDestinationCursor(href, pageIndex);
766
+ });
767
+ return;
768
+ }
769
+ const byHref = this.findDestinationIndexByHref(href);
770
+ if (byHref >= 0) {
771
+ this.destinationCursor = byHref;
772
+ return;
773
+ }
774
+ if (typeof pageIndex === "number" && pageIndex >= 0) {
775
+ const byPage = this.findNearestDestinationIndexByPage(pageIndex);
776
+ if (byPage >= 0) this.destinationCursor = byPage;
777
+ }
778
+ }
779
+ getSectionFromTarget(target) {
780
+ if (!this.book?.spine?.get) return null;
781
+ try {
782
+ const section = this.book.spine.get(target);
783
+ if (section) return section;
784
+ } catch {
785
+ }
786
+ if (typeof target === "string") {
787
+ return this.getSectionFromHref(target);
788
+ }
789
+ return null;
790
+ }
791
+ getPageIndexFromRenditionLocation(rendition) {
792
+ const location = rendition?.currentLocation?.();
793
+ if (!location) return null;
794
+ const starts = Array.isArray(location) ? location.map((entry) => entry?.start).filter(Boolean) : [location?.start];
795
+ for (const start of starts) {
796
+ if (!start) continue;
797
+ const href = typeof start?.href === "string" ? this.normalizeHref(start.href) : "";
798
+ if (href) {
799
+ const hrefIndex = this.getSpineIndexByHref(href);
800
+ if (hrefIndex >= 0) return this.toPageIndexFromSpine(hrefIndex);
801
+ }
802
+ if (typeof start?.index === "number" && start.index >= 0) {
803
+ const section = this.getSectionFromTarget(start.index);
804
+ const sectionPageIndex = this.getPageIndexFromSection(section);
805
+ if (sectionPageIndex != null) return sectionPageIndex;
806
+ }
807
+ }
808
+ return null;
809
+ }
810
+ isNoSectionError(error) {
811
+ if (!error || typeof error !== "object") return false;
812
+ const message = "message" in error && typeof error.message === "string" ? error.message : "";
813
+ return message.includes("No Section Found");
814
+ }
815
+ isTransientDisplayError(error) {
816
+ if (!error || typeof error !== "object") return false;
817
+ const message = "message" in error && typeof error.message === "string" ? error.message : "";
818
+ if (!message) return false;
819
+ const normalized = message.toLowerCase();
820
+ return normalized.includes("cannot read properties of undefined") || normalized.includes("cannot read properties of null") || normalized.includes("reading 'package'") || normalized.includes('reading "package"');
821
+ }
822
+ async displayWithFallback(rendition, targets, isCancelled) {
823
+ for (const target of targets) {
824
+ if (isCancelled()) return null;
825
+ try {
826
+ await rendition.display(target);
827
+ if (isCancelled()) return null;
828
+ const section = this.getSectionFromTarget(target);
829
+ return typeof section?.index === "number" ? section.index : null;
830
+ } catch (error) {
831
+ if (this.isNoSectionError(error) || this.isTransientDisplayError(error)) {
832
+ continue;
833
+ }
834
+ throw error;
835
+ }
836
+ }
837
+ return void 0;
838
+ }
839
+ async displayDestinationWithRetry(rendition, href) {
840
+ const targets = this.uniqueDisplayTargets([href, this.decodeHref(href)]);
841
+ if (!targets.length) return false;
842
+ const hasAnchor = href.includes("#");
843
+ for (let attempt = 0; attempt < 3; attempt += 1) {
844
+ try {
845
+ const firstPass = await this.displayWithFallback(
846
+ rendition,
847
+ targets,
848
+ () => false
849
+ );
850
+ if (firstPass === void 0) {
851
+ this.debugLog("displayDestinationWithRetry:first-pass-miss", {
852
+ href,
853
+ attempt
854
+ });
855
+ continue;
856
+ }
857
+ if (!hasAnchor) return true;
858
+ await new Promise((resolve) => setTimeout(resolve, 0));
859
+ const secondPass = await this.displayWithFallback(
860
+ rendition,
861
+ targets,
862
+ () => false
863
+ );
864
+ if (secondPass !== void 0) return true;
865
+ this.debugLog("displayDestinationWithRetry:second-pass-miss", {
866
+ href,
867
+ attempt
868
+ });
869
+ } catch {
870
+ this.debugLog("displayDestinationWithRetry:error", { href, attempt });
871
+ }
872
+ await new Promise((resolve) => setTimeout(resolve, 40 * (attempt + 1)));
873
+ }
874
+ return false;
875
+ }
876
+ isDebugEnabled() {
877
+ try {
878
+ const globalFlag = Boolean(globalThis?.__PAPYRUS_EPUB_DEBUG__);
879
+ if (globalFlag) return true;
880
+ const localStorageRef = globalThis?.localStorage;
881
+ if (!localStorageRef) return false;
882
+ const persisted = localStorageRef.getItem("papyrus:epubDebug");
883
+ return persisted === "1" || persisted === "true";
884
+ } catch {
885
+ return false;
886
+ }
887
+ }
888
+ debugLog(message, payload) {
889
+ if (!this.isDebugEnabled()) return;
890
+ if (payload === void 0) {
891
+ console.log("[EPUBEngine]", message);
892
+ return;
893
+ }
894
+ console.log("[EPUBEngine]", message, payload);
895
+ }
896
+ async syncSectionHeight(rendition, element, pageIndex, width, seedHeight, targetSectionIndex, skipResize = false) {
897
+ if (_EPUBEngine.USE_INTERNAL_IFRAME_SCROLL) {
898
+ const fallbackHeight = Math.max(360, Math.ceil(seedHeight));
899
+ element.style.height = `${fallbackHeight}px`;
900
+ this.pageSizes.set(pageIndex, { width, height: fallbackHeight });
901
+ if (!skipResize && typeof rendition?.resize === "function" && rendition.manager?.resize) {
902
+ try {
903
+ rendition.resize(width, fallbackHeight);
904
+ } catch {
905
+ }
906
+ }
907
+ return;
908
+ }
909
+ const measureElementHeight = (elementToMeasure) => {
910
+ const measuredElement = elementToMeasure;
911
+ if (!measuredElement) return 0;
912
+ const rectHeight = typeof measuredElement.getBoundingClientRect === "function" ? measuredElement.getBoundingClientRect().height : 0;
913
+ return Math.max(
914
+ measuredElement.scrollHeight ?? 0,
915
+ measuredElement.offsetHeight ?? 0,
916
+ measuredElement.clientHeight ?? 0,
917
+ Number.isFinite(rectHeight) ? rectHeight : 0
918
+ );
919
+ };
920
+ const measureDocumentHeight = (doc) => {
921
+ if (!doc) return 0;
922
+ return Math.max(
923
+ measureElementHeight(doc.documentElement),
924
+ measureElementHeight(doc.body)
925
+ );
926
+ };
927
+ const measureContentHeight = (strictTarget) => {
928
+ let measured = 0;
929
+ const contents = typeof rendition?.getContents === "function" ? rendition.getContents() : [];
930
+ if (Array.isArray(contents)) {
931
+ for (const content of contents) {
932
+ if (strictTarget && targetSectionIndex !== null && typeof content?.sectionIndex === "number" && content.sectionIndex !== targetSectionIndex) {
933
+ continue;
934
+ }
935
+ const doc = content?.document;
936
+ if (!doc) continue;
937
+ measured = Math.max(measured, measureDocumentHeight(doc));
938
+ }
939
+ }
940
+ if (measured > 0) return measured;
941
+ const frameSelector = strictTarget && targetSectionIndex !== null ? `.epub-view[ref="${targetSectionIndex}"] iframe` : "iframe";
942
+ const frame = element.querySelector(
943
+ frameSelector
944
+ );
945
+ const fallbackFrame = frame ?? (strictTarget && targetSectionIndex !== null ? element.querySelector("iframe") : null);
946
+ const selectedFrame = fallbackFrame ?? frame;
947
+ const frameDoc = selectedFrame?.contentDocument;
948
+ if (!frameDoc) return 0;
949
+ return measureDocumentHeight(frameDoc);
950
+ };
951
+ let contentHeight = measureContentHeight(true);
952
+ if (contentHeight <= 0 && targetSectionIndex !== null) {
953
+ contentHeight = measureContentHeight(false);
954
+ }
955
+ if (contentHeight <= 0) {
956
+ await new Promise((resolve) => setTimeout(resolve, 0));
957
+ contentHeight = measureContentHeight(true);
958
+ if (contentHeight <= 0 && targetSectionIndex !== null) {
959
+ contentHeight = measureContentHeight(false);
960
+ }
961
+ }
962
+ const measuredTarget = contentHeight > 0 ? Math.ceil(contentHeight + _EPUBEngine.HEIGHT_PADDING) : Math.ceil(seedHeight);
963
+ const minA4Height = this.getA4MinHeight(width);
964
+ const unclampedTarget = Math.max(minA4Height, measuredTarget);
965
+ const targetHeight = Math.max(
966
+ minA4Height,
967
+ Math.min(_EPUBEngine.MAX_SECTION_HEIGHT, unclampedTarget)
968
+ );
969
+ if (targetHeight !== unclampedTarget) {
970
+ this.debugLog("syncSectionHeight:clamped", {
971
+ pageIndex,
972
+ measuredTarget,
973
+ max: _EPUBEngine.MAX_SECTION_HEIGHT
974
+ });
975
+ }
976
+ if (targetHeight <= 0) return;
977
+ element.style.height = `${targetHeight}px`;
978
+ this.pageSizes.set(pageIndex, { width, height: targetHeight });
979
+ if (!skipResize && typeof rendition?.resize === "function" && rendition.manager?.resize) {
980
+ try {
981
+ rendition.resize(width, targetHeight);
982
+ } catch {
983
+ }
984
+ }
985
+ }
986
+ async resolvePageIndexFromHref(href) {
987
+ const normalizedHref = href.trim();
988
+ if (!normalizedHref) return null;
989
+ const section = this.getSectionFromHref(normalizedHref);
990
+ const sectionPageIndex = this.getPageIndexFromSection(section);
991
+ if (sectionPageIndex != null) return sectionPageIndex;
992
+ const spineIndex = this.getSpineIndexByHref(
993
+ this.normalizeHref(normalizedHref)
994
+ );
995
+ return spineIndex >= 0 ? this.toPageIndexFromSpine(spineIndex) : null;
996
+ }
997
+ extractHrefDestination(dest) {
998
+ if (typeof dest === "string") return dest;
999
+ if (dest?.kind === "href" && typeof dest.value === "string") {
1000
+ return dest.value;
1001
+ }
1002
+ return null;
1003
+ }
189
1004
  isUriSource(source) {
190
1005
  return typeof source === "object" && source !== null && "uri" in source;
191
1006
  }
@@ -233,7 +1048,9 @@ var EPUBEngine = class extends BaseDocumentEngine {
233
1048
  decodeBase64(value) {
234
1049
  const clean = value.replace(/\s/g, "");
235
1050
  if (typeof atob !== "function") {
236
- throw new Error("[EPUBEngine] atob n\xE3o est\xE1 dispon\xEDvel para decodificar base64.");
1051
+ throw new Error(
1052
+ "[EPUBEngine] atob n\xE3o est\xE1 dispon\xEDvel para decodificar base64."
1053
+ );
237
1054
  }
238
1055
  const binary = atob(clean);
239
1056
  const len = binary.length;
@@ -252,6 +1069,372 @@ var EPUBEngine = class extends BaseDocumentEngine {
252
1069
  if (value.length < 16) return false;
253
1070
  return /^[A-Za-z0-9+/=]+$/.test(value);
254
1071
  }
1072
+ createRendition(element, width, height) {
1073
+ const rendition = this.book.renderTo(element, {
1074
+ width,
1075
+ height,
1076
+ flow: "scrolled-doc",
1077
+ spread: "none",
1078
+ method: "write",
1079
+ overflow: _EPUBEngine.USE_INTERNAL_IFRAME_SCROLL ? "auto" : "hidden"
1080
+ });
1081
+ this.registerContentHook(rendition);
1082
+ return rendition;
1083
+ }
1084
+ disposeReader() {
1085
+ const rendition = this.readerRendition;
1086
+ if (!rendition) return;
1087
+ try {
1088
+ rendition?.manager?.destroy?.();
1089
+ } catch {
1090
+ }
1091
+ this.readerRendition = null;
1092
+ this.readerTarget = null;
1093
+ this.heightSyncVersion += 1;
1094
+ }
1095
+ registerContentHook(rendition) {
1096
+ if (!rendition?.hooks?.content?.register) return;
1097
+ rendition.hooks.content.register((contents) => {
1098
+ try {
1099
+ const setImportantStyle = (node, property, value) => {
1100
+ if (!node) return;
1101
+ node.style.setProperty(property, value, "important");
1102
+ };
1103
+ const useInternalScroll = _EPUBEngine.USE_INTERNAL_IFRAME_SCROLL;
1104
+ const managerContainer = rendition?.manager?.container;
1105
+ const viewsContainer = rendition?.manager?.views?.container;
1106
+ if (managerContainer) {
1107
+ managerContainer.classList.add("papyrus-epub-scroll-host");
1108
+ managerContainer.style.overflow = useInternalScroll ? "auto" : "hidden";
1109
+ managerContainer.style.overflowY = useInternalScroll ? "auto" : "hidden";
1110
+ managerContainer.style.overflowX = "hidden";
1111
+ managerContainer.style.height = "100%";
1112
+ managerContainer.style.maxHeight = "100%";
1113
+ managerContainer.style.scrollbarWidth = useInternalScroll ? "thin" : "none";
1114
+ managerContainer.style.setProperty(
1115
+ "-webkit-overflow-scrolling",
1116
+ "touch"
1117
+ );
1118
+ managerContainer.style.setProperty("overscroll-behavior", "contain");
1119
+ }
1120
+ if (viewsContainer) {
1121
+ viewsContainer.style.overflow = useInternalScroll ? "visible" : "hidden";
1122
+ viewsContainer.style.overflowY = useInternalScroll ? "visible" : "hidden";
1123
+ viewsContainer.style.overflowX = "hidden";
1124
+ viewsContainer.style.minHeight = "100%";
1125
+ viewsContainer.style.scrollbarWidth = useInternalScroll ? "auto" : "none";
1126
+ }
1127
+ const frame = contents?.window?.frameElement;
1128
+ const mobileProbe = managerContainer ?? frame ?? contents?.document?.body;
1129
+ const mobileWidthHint = Math.max(
1130
+ managerContainer?.clientWidth ?? 0,
1131
+ frame?.clientWidth ?? 0,
1132
+ mobileProbe?.clientWidth ?? 0
1133
+ );
1134
+ const isMobileInternalScroll = Boolean(
1135
+ useInternalScroll && mobileProbe && this.isMobileViewport(mobileProbe, mobileWidthHint)
1136
+ );
1137
+ const contentOverflow = useInternalScroll ? "hidden" : "visible";
1138
+ const doc = contents?.document;
1139
+ const root = doc?.documentElement;
1140
+ const body = doc?.body;
1141
+ contents?.overflow?.(contentOverflow);
1142
+ contents?.overflowX?.("hidden");
1143
+ contents?.overflowY?.(contentOverflow);
1144
+ contents?.css?.("overflow", contentOverflow, true);
1145
+ contents?.css?.("overflow-y", contentOverflow, true);
1146
+ contents?.css?.("overflow-x", "hidden", true);
1147
+ contents?.css?.("height", "auto", true);
1148
+ contents?.css?.("max-height", "none", true);
1149
+ contents?.css?.("min-height", "100%", true);
1150
+ if (root) {
1151
+ setImportantStyle(root, "overflow", contentOverflow);
1152
+ setImportantStyle(root, "overflow-y", contentOverflow);
1153
+ setImportantStyle(root, "overflow-x", "hidden");
1154
+ setImportantStyle(root, "height", "auto");
1155
+ setImportantStyle(root, "min-height", "100%");
1156
+ setImportantStyle(root, "max-height", "none");
1157
+ setImportantStyle(root, "scrollbar-width", "none");
1158
+ setImportantStyle(root, "overscroll-behavior", "none");
1159
+ }
1160
+ if (body) {
1161
+ setImportantStyle(body, "overflow", contentOverflow);
1162
+ setImportantStyle(body, "overflow-y", contentOverflow);
1163
+ setImportantStyle(body, "overflow-x", "hidden");
1164
+ setImportantStyle(body, "height", "auto");
1165
+ setImportantStyle(body, "min-height", "100%");
1166
+ setImportantStyle(body, "max-height", "none");
1167
+ setImportantStyle(body, "scrollbar-width", "none");
1168
+ setImportantStyle(body, "overscroll-behavior", "none");
1169
+ if (isMobileInternalScroll) {
1170
+ setImportantStyle(body, "margin", "0");
1171
+ setImportantStyle(body, "padding", "0");
1172
+ }
1173
+ }
1174
+ if (useInternalScroll && managerContainer && doc && root) {
1175
+ const proxyMarker = "data-papyrus-scroll-proxy";
1176
+ if (!root.hasAttribute(proxyMarker)) {
1177
+ root.setAttribute(proxyMarker, "1");
1178
+ const scrollHost = managerContainer;
1179
+ const onWheel = (event) => {
1180
+ if (event.defaultPrevented) return;
1181
+ if (event.ctrlKey || event.metaKey) return;
1182
+ const deltaY = Number(event.deltaY) || 0;
1183
+ const deltaX = Number(event.deltaX) || 0;
1184
+ if (!deltaY && !deltaX) return;
1185
+ const previousTop = scrollHost.scrollTop;
1186
+ const previousLeft = scrollHost.scrollLeft;
1187
+ scrollHost.scrollTop += deltaY;
1188
+ scrollHost.scrollLeft += deltaX;
1189
+ const moved = scrollHost.scrollTop !== previousTop || scrollHost.scrollLeft !== previousLeft;
1190
+ if (moved && event.cancelable) event.preventDefault();
1191
+ };
1192
+ let lastTouchY = null;
1193
+ let lastTouchX = null;
1194
+ const onTouchStart = (event) => {
1195
+ if (event.touches.length !== 1) return;
1196
+ lastTouchY = event.touches[0].clientY;
1197
+ lastTouchX = event.touches[0].clientX;
1198
+ };
1199
+ const onTouchMove = (event) => {
1200
+ if (event.touches.length !== 1) return;
1201
+ const touch = event.touches[0];
1202
+ if (lastTouchY == null || lastTouchX == null) {
1203
+ lastTouchY = touch.clientY;
1204
+ lastTouchX = touch.clientX;
1205
+ return;
1206
+ }
1207
+ const deltaY = lastTouchY - touch.clientY;
1208
+ const deltaX = lastTouchX - touch.clientX;
1209
+ const previousTop = scrollHost.scrollTop;
1210
+ const previousLeft = scrollHost.scrollLeft;
1211
+ if (deltaY || deltaX) {
1212
+ scrollHost.scrollTop += deltaY;
1213
+ scrollHost.scrollLeft += deltaX;
1214
+ }
1215
+ const moved = scrollHost.scrollTop !== previousTop || scrollHost.scrollLeft !== previousLeft;
1216
+ if (moved && event.cancelable) event.preventDefault();
1217
+ lastTouchY = touch.clientY;
1218
+ lastTouchX = touch.clientX;
1219
+ };
1220
+ const onTouchEnd = () => {
1221
+ lastTouchY = null;
1222
+ lastTouchX = null;
1223
+ };
1224
+ doc.addEventListener("wheel", onWheel, { passive: false });
1225
+ doc.addEventListener("touchstart", onTouchStart, {
1226
+ passive: true
1227
+ });
1228
+ doc.addEventListener("touchmove", onTouchMove, {
1229
+ passive: false
1230
+ });
1231
+ doc.addEventListener("touchend", onTouchEnd, { passive: true });
1232
+ doc.addEventListener("touchcancel", onTouchEnd, {
1233
+ passive: true
1234
+ });
1235
+ }
1236
+ }
1237
+ if (isMobileInternalScroll && doc?.body) {
1238
+ const singleImage = this.getSingleImageForMobileLayout(doc);
1239
+ if (singleImage) {
1240
+ doc.body.style.display = "flex";
1241
+ doc.body.style.justifyContent = "center";
1242
+ doc.body.style.alignItems = "flex-start";
1243
+ singleImage.style.width = "100%";
1244
+ singleImage.style.maxWidth = "100%";
1245
+ singleImage.style.height = "auto";
1246
+ singleImage.style.maxHeight = "100%";
1247
+ singleImage.style.display = "block";
1248
+ singleImage.style.objectFit = "contain";
1249
+ }
1250
+ }
1251
+ if (frame) {
1252
+ if (useInternalScroll) {
1253
+ frame.setAttribute("scrolling", "no");
1254
+ setImportantStyle(frame, "overflow", "hidden");
1255
+ setImportantStyle(frame, "overflow-y", "hidden");
1256
+ setImportantStyle(frame, "overflow-x", "hidden");
1257
+ setImportantStyle(frame, "height", "auto");
1258
+ setImportantStyle(frame, "min-height", "100%");
1259
+ setImportantStyle(frame, "max-height", "none");
1260
+ setImportantStyle(frame, "width", "100%");
1261
+ setImportantStyle(frame, "max-width", "100%");
1262
+ setImportantStyle(frame, "display", "block");
1263
+ setImportantStyle(frame, "border", "0");
1264
+ } else {
1265
+ frame.setAttribute("scrolling", "no");
1266
+ setImportantStyle(frame, "overflow", "hidden");
1267
+ setImportantStyle(frame, "height", "auto");
1268
+ }
1269
+ }
1270
+ } catch {
1271
+ }
1272
+ });
1273
+ }
1274
+ scheduleHeightSync(syncVersion, rendition, element, pageIndex, width, fallbackHeight, targetSectionIndex, skipResize = false) {
1275
+ const run = () => {
1276
+ if (syncVersion !== this.heightSyncVersion) return;
1277
+ if (this.readerRendition !== rendition) return;
1278
+ if (this.readerTarget !== element) return;
1279
+ void this.syncSectionHeight(
1280
+ rendition,
1281
+ element,
1282
+ pageIndex,
1283
+ width,
1284
+ fallbackHeight,
1285
+ targetSectionIndex,
1286
+ skipResize
1287
+ );
1288
+ };
1289
+ setTimeout(run, 80);
1290
+ setTimeout(run, 260);
1291
+ setTimeout(run, 620);
1292
+ setTimeout(run, 1200);
1293
+ }
1294
+ getViewportHeightHint(element) {
1295
+ const viewerRoot = element.closest(".papyrus-viewer");
1296
+ const hostParent = element.parentElement;
1297
+ const measured = Math.max(
1298
+ viewerRoot?.clientHeight ?? 0,
1299
+ hostParent?.clientHeight ?? 0,
1300
+ element.clientHeight ?? 0
1301
+ );
1302
+ if (measured <= 0) return null;
1303
+ const viewportWidth = Math.max(
1304
+ viewerRoot?.clientWidth ?? 0,
1305
+ globalThis?.visualViewport?.width ?? 0,
1306
+ globalThis?.innerWidth ?? 0
1307
+ );
1308
+ const isMobileViewport = viewportWidth > 0 && viewportWidth <= _EPUBEngine.MOBILE_VIEWPORT_MAX_WIDTH_PX;
1309
+ if (!isMobileViewport) return null;
1310
+ let topbarOffset = 0;
1311
+ const shell = viewerRoot?.parentElement?.parentElement;
1312
+ if (shell) {
1313
+ const shellHeight = shell.getBoundingClientRect().height;
1314
+ const topbar = Array.from(shell.children).find(
1315
+ (child) => child.classList?.contains("papyrus-topbar")
1316
+ );
1317
+ const topbarHeight = topbar?.getBoundingClientRect().height ?? 0;
1318
+ const viewerLikelyIncludesTopbar = topbarHeight > 0 && shellHeight > 0 && measured >= shellHeight - 2;
1319
+ if (viewerLikelyIncludesTopbar) {
1320
+ topbarOffset = Math.ceil(topbarHeight);
1321
+ }
1322
+ }
1323
+ const adjusted = measured - topbarOffset - _EPUBEngine.INTERNAL_VIEWPORT_PADDING_PX;
1324
+ return Math.max(280, Math.floor(adjusted));
1325
+ }
1326
+ getLinearSpineItems(items) {
1327
+ const linearItems = items.filter((item) => item?.linear !== "no");
1328
+ if (!linearItems.length) return items;
1329
+ const deduped = [];
1330
+ for (const item of linearItems) {
1331
+ const prev = deduped[deduped.length - 1];
1332
+ const prevHref = this.normalizeHref(prev?.href ?? "");
1333
+ const currentHref = this.normalizeHref(item?.href ?? "");
1334
+ if (prevHref && currentHref && prevHref === currentHref) continue;
1335
+ deduped.push(item);
1336
+ }
1337
+ return deduped.length ? deduped : linearItems;
1338
+ }
1339
+ hasCoverPage() {
1340
+ return Boolean(this.coverUrl);
1341
+ }
1342
+ isCoverPage(pageIndex) {
1343
+ return this.hasCoverPage() && pageIndex === 0;
1344
+ }
1345
+ toSpineIndex(pageIndex) {
1346
+ return pageIndex - (this.hasCoverPage() ? 1 : 0);
1347
+ }
1348
+ toPageIndexFromSpine(spineIndex) {
1349
+ return spineIndex + (this.hasCoverPage() ? 1 : 0);
1350
+ }
1351
+ getA4MinHeight(width) {
1352
+ if (!Number.isFinite(width) || width <= 0) return 900;
1353
+ return Math.max(480, Math.ceil(width * _EPUBEngine.A4_RATIO));
1354
+ }
1355
+ renderCoverPage(element, width, height, pageIndex) {
1356
+ this.disposeReader();
1357
+ element.innerHTML = "";
1358
+ element.style.width = `${width}px`;
1359
+ element.style.height = `${height}px`;
1360
+ const isMobileViewport = this.isMobileViewport(element, width);
1361
+ const isLandscapeViewport = width > height;
1362
+ const wrapper = document.createElement("div");
1363
+ wrapper.style.width = "100%";
1364
+ wrapper.style.minHeight = `${height}px`;
1365
+ wrapper.style.display = "flex";
1366
+ wrapper.style.alignItems = "center";
1367
+ wrapper.style.justifyContent = "center";
1368
+ wrapper.style.background = "#fff";
1369
+ wrapper.style.padding = isMobileViewport ? "0" : "16px";
1370
+ wrapper.style.boxSizing = "border-box";
1371
+ if (isMobileViewport) {
1372
+ wrapper.style.overflow = "hidden";
1373
+ }
1374
+ const img = document.createElement("img");
1375
+ img.src = this.coverUrl ?? "";
1376
+ img.alt = "Capa";
1377
+ img.style.maxWidth = "100%";
1378
+ img.style.maxHeight = "100%";
1379
+ img.style.width = isMobileViewport ? "100%" : "auto";
1380
+ img.style.height = isMobileViewport ? "100%" : "auto";
1381
+ img.style.display = "block";
1382
+ img.style.objectFit = isMobileViewport && !isLandscapeViewport ? "cover" : "contain";
1383
+ img.style.boxShadow = isMobileViewport ? "none" : "0 16px 32px rgba(0,0,0,0.15)";
1384
+ img.style.borderRadius = isMobileViewport ? "0" : "8px";
1385
+ img.onload = () => {
1386
+ if (isMobileViewport) {
1387
+ const targetHeight2 = Math.max(280, Math.floor(height));
1388
+ wrapper.style.minHeight = `${targetHeight2}px`;
1389
+ element.style.height = `${targetHeight2}px`;
1390
+ this.pageSizes.set(pageIndex, { width, height: targetHeight2 });
1391
+ return;
1392
+ }
1393
+ const naturalWidth = img.naturalWidth || width;
1394
+ const naturalHeight = img.naturalHeight || height;
1395
+ if (naturalWidth <= 0 || naturalHeight <= 0) return;
1396
+ const displayedWidth = Math.min(naturalWidth, Math.max(1, width - 32));
1397
+ const scaledHeight = Math.round(
1398
+ naturalHeight / naturalWidth * displayedWidth
1399
+ );
1400
+ const targetHeight = Math.max(height, scaledHeight + 32);
1401
+ wrapper.style.minHeight = `${targetHeight}px`;
1402
+ element.style.height = `${targetHeight}px`;
1403
+ this.pageSizes.set(pageIndex, { width, height: targetHeight });
1404
+ };
1405
+ wrapper.appendChild(img);
1406
+ element.appendChild(wrapper);
1407
+ this.pageSizes.set(pageIndex, { width, height });
1408
+ }
1409
+ isMobileViewport(element, widthHint) {
1410
+ const viewerRoot = element.closest(".papyrus-viewer");
1411
+ const viewportWidth = Math.max(
1412
+ widthHint,
1413
+ viewerRoot?.clientWidth ?? 0,
1414
+ globalThis?.visualViewport?.width ?? 0,
1415
+ globalThis?.innerWidth ?? 0
1416
+ );
1417
+ const viewportHeight = Math.max(
1418
+ viewerRoot?.clientHeight ?? 0,
1419
+ globalThis?.visualViewport?.height ?? 0,
1420
+ globalThis?.innerHeight ?? 0
1421
+ );
1422
+ const isShortLandscape = viewportHeight > 0 && viewportHeight <= _EPUBEngine.MOBILE_SHORT_VIEWPORT_MAX_HEIGHT_PX && viewportWidth > viewportHeight;
1423
+ return Boolean(
1424
+ viewportWidth > 0 && (viewportWidth <= _EPUBEngine.MOBILE_VIEWPORT_MAX_WIDTH_PX || isShortLandscape)
1425
+ );
1426
+ }
1427
+ getSingleImageForMobileLayout(doc) {
1428
+ const body = doc.body;
1429
+ if (!body) return null;
1430
+ const images = Array.from(
1431
+ body.querySelectorAll("img")
1432
+ );
1433
+ if (images.length !== 1) return null;
1434
+ const textLength = (body.textContent ?? "").replace(/\s+/g, "").length;
1435
+ if (textLength > 48) return null;
1436
+ return images[0] ?? null;
1437
+ }
255
1438
  };
256
1439
  export {
257
1440
  EPUBEngine