@file-viewer/renderer-epub 2.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,160 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright
13
+ owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities
16
+ that control, are controlled by, or are under common control with that entity.
17
+ For the purposes of this definition, "control" means (i) the power, direct or
18
+ indirect, to cause the direction or management of such entity, whether by
19
+ contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
+ outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
23
+ permissions granted by this License.
24
+
25
+ "Source" form shall mean the preferred form for making modifications, including
26
+ but not limited to software source code, documentation source, and configuration
27
+ files.
28
+
29
+ "Object" form shall mean any form resulting from mechanical transformation or
30
+ translation of a Source form, including but not limited to compiled object code,
31
+ generated documentation, and conversions to other media types.
32
+
33
+ "Work" shall mean the work of authorship, whether in Source or Object form,
34
+ made available under the License, as indicated by a copyright notice that is
35
+ included in or attached to the work.
36
+
37
+ "Derivative Works" shall mean any work, whether in Source or Object form, that
38
+ is based on (or derived from) the Work and for which the editorial revisions,
39
+ annotations, elaborations, or other modifications represent, as a whole, an
40
+ original work of authorship. For the purposes of this License, Derivative Works
41
+ shall not include works that remain separable from, or merely link (or bind by
42
+ name) to the interfaces of, the Work and Derivative Works thereof.
43
+
44
+ "Contribution" shall mean any work of authorship, including the original version
45
+ of the Work and any modifications or additions to that Work or Derivative Works
46
+ thereof, that is intentionally submitted to Licensor for inclusion in the Work by
47
+ the copyright owner or by an individual or Legal Entity authorized to submit on
48
+ behalf of the copyright owner. For the purposes of this definition, "submitted"
49
+ means any form of electronic, verbal, or written communication sent to the
50
+ Licensor or its representatives, including but not limited to communication on
51
+ electronic mailing lists, source code control systems, and issue tracking systems
52
+ that are managed by, or on behalf of, the Licensor for the purpose of discussing
53
+ and improving the Work, but excluding communication that is conspicuously marked
54
+ or otherwise designated in writing by the copyright owner as "Not a
55
+ Contribution."
56
+
57
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
58
+ of whom a Contribution has been received by Licensor and subsequently
59
+ incorporated within the Work.
60
+
61
+ 2. Grant of Copyright License. Subject to the terms and conditions of this
62
+ License, each Contributor hereby grants to You a perpetual, worldwide,
63
+ non-exclusive, no-charge, royalty-free, irrevocable copyright license to
64
+ reproduce, prepare Derivative Works of, publicly display, publicly perform,
65
+ sublicense, and distribute the Work and such Derivative Works in Source or
66
+ Object form.
67
+
68
+ 3. Grant of Patent License. Subject to the terms and conditions of this License,
69
+ each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
70
+ no-charge, royalty-free, irrevocable (except as stated in this section) patent
71
+ license to make, have made, use, offer to sell, sell, import, and otherwise
72
+ transfer the Work, where such license applies only to those patent claims
73
+ licensable by such Contributor that are necessarily infringed by their
74
+ Contribution(s) alone or by combination of their Contribution(s) with the Work to
75
+ which such Contribution(s) was submitted. If You institute patent litigation
76
+ against any entity (including a cross-claim or counterclaim in a lawsuit)
77
+ alleging that the Work or a Contribution incorporated within the Work
78
+ constitutes direct or contributory patent infringement, then any patent licenses
79
+ granted to You under this License for that Work shall terminate as of the date
80
+ such litigation is filed.
81
+
82
+ 4. Redistribution. You may reproduce and distribute copies of the Work or
83
+ Derivative Works thereof in any medium, with or without modifications, and in
84
+ Source or Object form, provided that You meet the following conditions:
85
+
86
+ (a) You must give any other recipients of the Work or Derivative Works a copy of
87
+ this License; and
88
+
89
+ (b) You must cause any modified files to carry prominent notices stating that
90
+ You changed the files; and
91
+
92
+ (c) You must retain, in the Source form of any Derivative Works that You
93
+ distribute, all copyright, patent, trademark, and attribution notices from the
94
+ Source form of the Work, excluding those notices that do not pertain to any part
95
+ of the Derivative Works; and
96
+
97
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then
98
+ any Derivative Works that You distribute must include a readable copy of the
99
+ attribution notices contained within such NOTICE file, excluding those notices
100
+ that do not pertain to any part of the Derivative Works, in at least one of the
101
+ following places: within a NOTICE text file distributed as part of the Derivative
102
+ Works; within the Source form or documentation, if provided along with the
103
+ Derivative Works; or, within a display generated by the Derivative Works, if and
104
+ wherever such third-party notices normally appear. The contents of the NOTICE
105
+ file are for informational purposes only and do not modify the License. You may
106
+ add Your own attribution notices within Derivative Works that You distribute,
107
+ alongside or as an addendum to the NOTICE text from the Work, provided that such
108
+ additional attribution notices cannot be construed as modifying the License.
109
+
110
+ You may add Your own copyright statement to Your modifications and may provide
111
+ additional or different license terms and conditions for use, reproduction, or
112
+ distribution of Your modifications, or for any such Derivative Works as a whole,
113
+ provided Your use, reproduction, and distribution of the Work otherwise complies
114
+ with the conditions stated in this License.
115
+
116
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any
117
+ Contribution intentionally submitted for inclusion in the Work by You to the
118
+ Licensor shall be under the terms and conditions of this License, without any
119
+ additional terms or conditions. Notwithstanding the above, nothing herein shall
120
+ supersede or modify the terms of any separate license agreement you may have
121
+ executed with Licensor regarding such Contributions.
122
+
123
+ 6. Trademarks. This License does not grant permission to use the trade names,
124
+ trademarks, service marks, or product names of the Licensor, except as required
125
+ for reasonable and customary use in describing the origin of the Work and
126
+ reproducing the content of the NOTICE file.
127
+
128
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
129
+ writing, Licensor provides the Work (and each Contributor provides its
130
+ Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
131
+ KIND, either express or implied, including, without limitation, any warranties or
132
+ conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
133
+ PARTICULAR PURPOSE. You are solely responsible for determining the
134
+ appropriateness of using or redistributing the Work and assume any risks
135
+ associated with Your exercise of permissions under this License.
136
+
137
+ 8. Limitation of Liability. In no event and under no legal theory, whether in
138
+ tort (including negligence), contract, or otherwise, unless required by
139
+ applicable law (such as deliberate and grossly negligent acts) or agreed to in
140
+ writing, shall any Contributor be liable to You for damages, including any
141
+ direct, indirect, special, incidental, or consequential damages of any character
142
+ arising as a result of this License or out of the use or inability to use the
143
+ Work (including but not limited to damages for loss of goodwill, work stoppage,
144
+ computer failure or malfunction, or any and all other commercial damages or
145
+ losses), even if such Contributor has been advised of the possibility of such
146
+ damages.
147
+
148
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or
149
+ Derivative Works thereof, You may choose to offer, and charge a fee for,
150
+ acceptance of support, warranty, indemnity, or other liability obligations and/or
151
+ rights consistent with this License. However, in accepting such obligations, You
152
+ may act only on Your own behalf and on Your sole responsibility, not on behalf of
153
+ any other Contributor, and only if You agree to indemnify, defend, and hold each
154
+ Contributor harmless for any liability incurred by, or claims asserted against,
155
+ such Contributor by reason of your accepting any such warranty or additional
156
+ liability.
157
+
158
+ END OF TERMS AND CONDITIONS
159
+
160
+ Copyright 2026 Flyfish Viewer
package/README.en.md ADDED
@@ -0,0 +1,40 @@
1
+ # @file-viewer/renderer-epub
2
+
3
+ Standalone ebook renderer package for Flyfish File Viewer. It handles `.epub` parsing, table-of-contents navigation, scrolling reading, previous/next navigation, reading progress, and `.umd` mobile ebook metadata, TOC, and zlib text blocks.
4
+
5
+ ## Usage
6
+
7
+ ```ts
8
+ import FileViewer from '@file-viewer/vue3'
9
+ import { ebookRenderer } from '@file-viewer/renderer-epub'
10
+
11
+ const options = {
12
+ builtinRenderers: 'none',
13
+ renderers: ebookRenderer,
14
+ }
15
+ ```
16
+
17
+ You can also compose it with other renderers:
18
+
19
+ ```ts
20
+ import { ebookRenderer } from '@file-viewer/renderer-epub'
21
+ import { pdfRenderer } from '@file-viewer/renderer-pdf'
22
+ import { archiveRenderer } from '@file-viewer/renderer-archive'
23
+
24
+ const options = {
25
+ builtinRenderers: 'none',
26
+ renderers: [pdfRenderer, archiveRenderer, ebookRenderer],
27
+ }
28
+ ```
29
+
30
+ ## Capabilities
31
+
32
+ - Parses `.epub` packages, OPF metadata, navigation, and chapter resources with `epubjs`.
33
+ - Parses `.umd` mobile ebook containers with the project parser and inflates text blocks through `pako`.
34
+ - Uses scrolling reading mode for compatibility, avoiding blank content in browsers that struggle with very wide paginated EPUB layouts.
35
+ - Supports TOC visibility, chapter jumping, previous/next navigation, and reading progress.
36
+ - Does not depend on any online service or public CDN, making it suitable for intranet knowledge bases, training materials, and long-form attachment preview.
37
+
38
+ ## Migration Note
39
+
40
+ The core package no longer bundles the EPUB / UMD renderer and no longer installs `epubjs` or `pako` directly. Install this renderer explicitly, or use `@file-viewer/preset-all`, when ebook preview is required.
package/README.md ADDED
@@ -0,0 +1,40 @@
1
+ # @file-viewer/renderer-epub
2
+
3
+ Flyfish File Viewer 的独立电子书 renderer 包。它负责 `.epub` 文件解析、目录展示、滚动阅读、上一页/下一页导航和阅读进度同步,也负责 `.umd` 移动电子书的元数据、目录和 zlib 正文解析。
4
+
5
+ ## 用法
6
+
7
+ ```ts
8
+ import FileViewer from '@file-viewer/vue3'
9
+ import { ebookRenderer } from '@file-viewer/renderer-epub'
10
+
11
+ const options = {
12
+ builtinRenderers: 'none',
13
+ renderers: ebookRenderer,
14
+ }
15
+ ```
16
+
17
+ 也可以与其他 renderer 组合:
18
+
19
+ ```ts
20
+ import { ebookRenderer } from '@file-viewer/renderer-epub'
21
+ import { pdfRenderer } from '@file-viewer/renderer-pdf'
22
+ import { archiveRenderer } from '@file-viewer/renderer-archive'
23
+
24
+ const options = {
25
+ builtinRenderers: 'none',
26
+ renderers: [pdfRenderer, archiveRenderer, ebookRenderer],
27
+ }
28
+ ```
29
+
30
+ ## 能力边界
31
+
32
+ - `.epub` 使用 `epubjs` 解析 EPUB 包、OPF 元数据、导航目录和章节资源。
33
+ - `.umd` 使用项目内解析器读取早期移动电子书封装,并通过 `pako` 解压正文段。
34
+ - 阅读区采用滚动文档模式,兼容性优先,避免部分浏览器在超宽分页布局下出现正文白板。
35
+ - 支持目录窗格显隐、章节跳转、上一页/下一页和阅读进度展示。
36
+ - 不绑定任何在线服务或公共 CDN,适合内网知识库、培训资料和长文档附件预览。
37
+
38
+ ## 迁移说明
39
+
40
+ `@file-viewer/core` 已不再内置 EPUB / UMD renderer,也不再直接安装 `epubjs` 或 `pako`。需要电子书预览时,请显式安装本包,或直接使用 `@file-viewer/preset-all` 聚合能力。
package/dist/epub.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import type { FileViewerRenderedInstance } from '@file-viewer/core';
2
+ export default function renderEpub(buffer: ArrayBuffer, target: HTMLDivElement): Promise<FileViewerRenderedInstance>;
package/dist/epub.js ADDED
@@ -0,0 +1,331 @@
1
+ const epubStyle = `
2
+ .epub-viewer{width:100%;height:100%;display:flex;flex-direction:column;overflow:hidden;background:#eef1f4;color:#172033;box-sizing:border-box}
3
+ .epub-viewer *{box-sizing:border-box}
4
+ .epub-toolbar{flex-shrink:0;display:grid;grid-template-columns:40px minmax(0,1fr) auto;align-items:center;gap:12px;padding:12px 14px;border-bottom:1px solid rgba(15,23,42,.08);background:rgba(255,255,255,.92)}
5
+ .epub-title{min-width:0;display:flex;flex-direction:column;gap:3px}
6
+ .epub-title strong,.epub-title span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
7
+ .epub-title strong{font-size:14px}
8
+ .epub-title span{color:#64748b;font-size:12px}
9
+ .epub-icon-button,.epub-button{height:36px;border:1px solid rgba(15,23,42,.08);background:#fff;color:#172033;font:inherit;cursor:pointer}
10
+ .epub-icon-button{width:40px;display:inline-flex;align-items:center;justify-content:center;border-radius:8px}
11
+ .epub-icon-button span,.epub-icon-button span::before,.epub-icon-button span::after{width:16px;height:2px;display:block;border-radius:999px;background:currentColor}
12
+ .epub-icon-button span{position:relative}
13
+ .epub-icon-button span::before,.epub-icon-button span::after{content:'';position:absolute;left:0}
14
+ .epub-icon-button span::before{top:-5px}
15
+ .epub-icon-button span::after{top:5px}
16
+ .epub-icon-button.active{border-color:rgba(37,99,235,.24);background:rgba(37,99,235,.08);color:#1d4ed8}
17
+ .epub-actions{display:flex;align-items:center;gap:8px}
18
+ .epub-button{min-width:68px;padding:0 12px;border-radius:8px;font-size:13px;font-weight:700}
19
+ .epub-button:disabled{color:#94a3b8;cursor:not-allowed}
20
+ .epub-progress{min-width:58px;color:#64748b;font-size:12px;text-align:center}
21
+ .epub-body{flex:1;min-height:0;display:grid;grid-template-columns:minmax(180px,240px) minmax(0,1fr)}
22
+ .epub-viewer--toc-hidden .epub-body{grid-template-columns:minmax(0,1fr)}
23
+ .epub-toc{min-width:0;min-height:0;display:flex;flex-direction:column;border-right:1px solid rgba(15,23,42,.08);background:rgba(255,255,255,.8)}
24
+ .epub-toc[hidden]{display:none}
25
+ .epub-toc-head{flex-shrink:0;display:flex;justify-content:space-between;gap:8px;padding:12px;color:#172033;font-size:13px}
26
+ .epub-toc-head span{color:#64748b}
27
+ .epub-toc-list{flex:1;min-height:0;overflow:auto;padding:0 8px 10px}
28
+ .epub-toc-item{width:100%;min-height:34px;border:0;border-radius:8px;background:transparent;color:#475569;font:inherit;font-size:12px;text-align:left;cursor:pointer}
29
+ .epub-toc-item:hover,.epub-toc-item.active{background:rgba(37,99,235,.08);color:#1d4ed8}
30
+ .epub-stage-wrap{position:relative;min-width:0;min-height:0;padding:18px;overflow:hidden}
31
+ .epub-stage{width:100%;height:100%;overflow-x:hidden;overflow-y:auto;border-radius:8px;background:#fff;box-shadow:0 18px 45px rgba(15,23,42,.12),inset 0 0 0 1px rgba(15,23,42,.06)}
32
+ .epub-stage .epub-container{width:100%!important;max-width:100%;overflow-x:hidden!important;overflow-y:auto!important}
33
+ .epub-stage iframe{max-width:100%}
34
+ .epub-state{position:absolute;inset:18px;display:flex;align-items:center;justify-content:center;border-radius:8px;background:rgba(255,255,255,.92);color:#64748b;font-size:14px}
35
+ .epub-state[hidden]{display:none!important}
36
+ .epub-state.error{color:#b42318}
37
+ .file-viewer[data-viewer-theme='dark'] .epub-viewer{background:#172033;color:#e5eef8}
38
+ .file-viewer[data-viewer-theme='dark'] .epub-toolbar,.file-viewer[data-viewer-theme='dark'] .epub-toc,.file-viewer[data-viewer-theme='dark'] .epub-stage{background:#fff;color:#172033}
39
+ @media (prefers-color-scheme:dark){.file-viewer[data-viewer-theme='system'] .epub-viewer{background:#172033;color:#e5eef8}.file-viewer[data-viewer-theme='system'] .epub-toolbar,.file-viewer[data-viewer-theme='system'] .epub-toc,.file-viewer[data-viewer-theme='system'] .epub-stage{background:#fff;color:#172033}}
40
+ @media (max-width:720px){.epub-toolbar{grid-template-columns:40px minmax(0,1fr)}.epub-actions{grid-column:1/-1;justify-content:space-between}.epub-body{position:relative;grid-template-columns:minmax(0,1fr)}.epub-toc{position:absolute;z-index:5;top:0;bottom:0;left:0;width:min(82vw,280px);box-shadow:18px 0 40px rgba(15,23,42,.16)}.epub-stage-wrap{padding:12px}}
41
+ `;
42
+ const createStyle = () => {
43
+ const style = document.createElement('style');
44
+ style.textContent = epubStyle;
45
+ return style;
46
+ };
47
+ const createElement = (tagName, className, text) => {
48
+ const element = document.createElement(tagName);
49
+ if (className) {
50
+ element.className = className;
51
+ }
52
+ if (text !== undefined) {
53
+ element.textContent = text;
54
+ }
55
+ return element;
56
+ };
57
+ const normalizeLabel = (value, fallback) => {
58
+ if (typeof value === 'string' && value.trim()) {
59
+ return value.trim();
60
+ }
61
+ return fallback;
62
+ };
63
+ const flattenToc = (items, depth = 0) => {
64
+ if (!Array.isArray(items)) {
65
+ return [];
66
+ }
67
+ return items.flatMap((item, index) => {
68
+ const node = item;
69
+ const href = typeof node.href === 'string' ? node.href : '';
70
+ const label = normalizeLabel(node.label || node.title, `章节 ${index + 1}`);
71
+ const subitems = flattenToc(node.subitems || node.children, depth + 1);
72
+ if (!href) {
73
+ return subitems;
74
+ }
75
+ return [{
76
+ depth,
77
+ href,
78
+ id: `${depth}-${index}-${href}`,
79
+ label,
80
+ }, ...subitems];
81
+ });
82
+ };
83
+ const pickInitialHref = (items) => {
84
+ var _a;
85
+ const chapterLike = items.find(item => {
86
+ const label = item.label.toLowerCase();
87
+ return /(^|\s)(chapter|part|book|prologue|preface|introduction)\b/.test(label)
88
+ || /第[一二三四五六七八九十百千0-9]+[章节回部卷篇]/.test(item.label);
89
+ });
90
+ if (chapterLike) {
91
+ return chapterLike.href;
92
+ }
93
+ const readable = items.find(item => {
94
+ const text = `${item.label} ${item.href}`.toLowerCase();
95
+ return !/(cover|titlepage|title-page|copyright|license|toc|contents|nav|table-of-contents|wrap0000)/.test(text);
96
+ });
97
+ return (readable === null || readable === void 0 ? void 0 : readable.href) || ((_a = items[0]) === null || _a === void 0 ? void 0 : _a.href);
98
+ };
99
+ export default async function renderEpub(buffer, target) {
100
+ let book;
101
+ let rendition;
102
+ let disposed = false;
103
+ let tocOpen = true;
104
+ let status = 'loading';
105
+ let title = 'EPUB 电子书';
106
+ let author = '';
107
+ let tocItems = [];
108
+ let currentHref = '';
109
+ let progress = null;
110
+ let atStart = true;
111
+ let atEnd = false;
112
+ const timers = new Set();
113
+ const cleanups = [];
114
+ const root = createElement('div', 'epub-viewer');
115
+ const toolbar = createElement('div', 'epub-toolbar');
116
+ const tocButton = createElement('button', 'epub-icon-button');
117
+ tocButton.type = 'button';
118
+ tocButton.title = '目录';
119
+ tocButton.append(createElement('span'));
120
+ const titleRoot = createElement('div', 'epub-title');
121
+ const titleText = createElement('strong', undefined, title);
122
+ const subtitleText = createElement('span', undefined, '阅读中');
123
+ titleRoot.append(titleText, subtitleText);
124
+ const actions = createElement('div', 'epub-actions');
125
+ const prevButton = createElement('button', 'epub-button', '上一页');
126
+ const progressText = createElement('span', 'epub-progress', '阅读中');
127
+ const nextButton = createElement('button', 'epub-button', '下一页');
128
+ prevButton.type = 'button';
129
+ nextButton.type = 'button';
130
+ actions.append(prevButton, progressText, nextButton);
131
+ toolbar.append(tocButton, titleRoot, actions);
132
+ const body = createElement('div', 'epub-body');
133
+ const toc = createElement('aside', 'epub-toc');
134
+ const tocHead = createElement('div', 'epub-toc-head');
135
+ const tocCount = createElement('span', undefined, '0 项');
136
+ tocHead.append(createElement('strong', undefined, '目录'), tocCount);
137
+ const tocList = createElement('div', 'epub-toc-list');
138
+ toc.append(tocHead, tocList);
139
+ const stageWrap = createElement('main', 'epub-stage-wrap');
140
+ const stage = createElement('div', 'epub-stage');
141
+ const state = createElement('div', 'epub-state', '正在解析 EPUB...');
142
+ stageWrap.append(stage, state);
143
+ body.append(toc, stageWrap);
144
+ root.append(toolbar, body);
145
+ target.replaceChildren(createStyle(), root);
146
+ const listen = (element, event, listener) => {
147
+ element.addEventListener(event, listener);
148
+ cleanups.push(() => element.removeEventListener(event, listener));
149
+ };
150
+ const currentChapter = () => {
151
+ var _a;
152
+ if (!currentHref) {
153
+ return '';
154
+ }
155
+ const exact = tocItems.find(item => item.href === currentHref);
156
+ if (exact) {
157
+ return exact.label;
158
+ }
159
+ return ((_a = tocItems.find(item => currentHref.includes(item.href.split('#')[0]))) === null || _a === void 0 ? void 0 : _a.label) || '';
160
+ };
161
+ const progressLabel = () => {
162
+ if (typeof progress === 'number') {
163
+ return `${progress}%`;
164
+ }
165
+ return currentChapter() || '阅读中';
166
+ };
167
+ const syncUi = () => {
168
+ root.classList.toggle('epub-viewer--toc-hidden', !tocOpen);
169
+ toc.hidden = !tocOpen;
170
+ tocButton.classList.toggle('active', tocOpen);
171
+ titleText.textContent = title;
172
+ subtitleText.textContent = author || progressLabel();
173
+ progressText.textContent = progressLabel();
174
+ prevButton.disabled = status !== 'ready' || atStart;
175
+ nextButton.disabled = status !== 'ready' || atEnd;
176
+ state.hidden = status === 'ready';
177
+ state.classList.toggle('error', status === 'error');
178
+ tocCount.textContent = `${tocItems.length} 项`;
179
+ Array.from(tocList.querySelectorAll('.epub-toc-item')).forEach(button => {
180
+ button.classList.toggle('active', button.dataset.href === currentHref);
181
+ });
182
+ };
183
+ const renderToc = () => {
184
+ tocList.replaceChildren();
185
+ tocItems.forEach(item => {
186
+ const button = createElement('button', 'epub-toc-item', item.label);
187
+ button.type = 'button';
188
+ button.dataset.href = item.href;
189
+ button.style.paddingLeft = `${12 + item.depth * 14}px`;
190
+ listen(button, 'click', () => {
191
+ void (rendition === null || rendition === void 0 ? void 0 : rendition.display(item.href));
192
+ tocOpen = false;
193
+ syncUi();
194
+ });
195
+ tocList.append(button);
196
+ });
197
+ syncUi();
198
+ };
199
+ const updateLocation = (epubLocation) => {
200
+ var _a, _b;
201
+ atStart = Boolean(epubLocation === null || epubLocation === void 0 ? void 0 : epubLocation.atStart);
202
+ atEnd = Boolean(epubLocation === null || epubLocation === void 0 ? void 0 : epubLocation.atEnd);
203
+ currentHref = ((_a = epubLocation === null || epubLocation === void 0 ? void 0 : epubLocation.start) === null || _a === void 0 ? void 0 : _a.href) || '';
204
+ if (typeof ((_b = epubLocation === null || epubLocation === void 0 ? void 0 : epubLocation.start) === null || _b === void 0 ? void 0 : _b.percentage) === 'number') {
205
+ progress = Math.round(epubLocation.start.percentage * 100);
206
+ }
207
+ syncUi();
208
+ };
209
+ const wait = (ms) => new Promise(resolve => {
210
+ const timer = window.setTimeout(() => {
211
+ timers.delete(timer);
212
+ resolve(undefined);
213
+ }, ms);
214
+ timers.add(timer);
215
+ });
216
+ const hasReadableFrame = () => {
217
+ var _a;
218
+ try {
219
+ const iframe = stage.querySelector('iframe');
220
+ const frameBody = (_a = iframe === null || iframe === void 0 ? void 0 : iframe.contentDocument) === null || _a === void 0 ? void 0 : _a.body;
221
+ if (!frameBody) {
222
+ return false;
223
+ }
224
+ return Boolean(frameBody.innerText.trim() || frameBody.querySelector('img, svg, canvas'));
225
+ }
226
+ catch {
227
+ return false;
228
+ }
229
+ };
230
+ const waitForReadableFrame = async () => {
231
+ for (let index = 0; index < 20; index += 1) {
232
+ if (disposed || hasReadableFrame()) {
233
+ return hasReadableFrame();
234
+ }
235
+ await wait(100);
236
+ }
237
+ return hasReadableFrame();
238
+ };
239
+ const openBook = async () => {
240
+ status = 'loading';
241
+ state.textContent = '正在解析 EPUB...';
242
+ syncUi();
243
+ try {
244
+ const { default: ePub } = await import('epubjs');
245
+ if (disposed) {
246
+ return;
247
+ }
248
+ book = ePub(buffer.slice(0), {
249
+ openAs: 'binary',
250
+ replacements: 'blobUrl',
251
+ });
252
+ rendition = book.renderTo(stage, {
253
+ allowScriptedContent: false,
254
+ flow: 'scrolled',
255
+ height: '100%',
256
+ manager: 'continuous',
257
+ resizeOnOrientationChange: true,
258
+ spread: 'none',
259
+ width: '100%',
260
+ });
261
+ rendition.themes.default({
262
+ body: {
263
+ color: '#172033',
264
+ fontFamily: 'Georgia, "Times New Roman", serif',
265
+ lineHeight: '1.72',
266
+ padding: '0 8px',
267
+ },
268
+ img: {
269
+ maxWidth: '100%',
270
+ },
271
+ html: {
272
+ height: 'auto',
273
+ overflow: 'auto',
274
+ },
275
+ });
276
+ rendition.on('relocated', updateLocation);
277
+ await book.ready;
278
+ const metadata = await book.loaded.metadata.catch(() => undefined);
279
+ title = normalizeLabel(metadata === null || metadata === void 0 ? void 0 : metadata.title, title);
280
+ author = normalizeLabel(metadata === null || metadata === void 0 ? void 0 : metadata.creator, '');
281
+ const navigation = await book.loaded.navigation.catch(() => undefined);
282
+ tocItems = flattenToc(navigation === null || navigation === void 0 ? void 0 : navigation.toc);
283
+ renderToc();
284
+ await rendition.display(pickInitialHref(tocItems));
285
+ if (!await waitForReadableFrame()) {
286
+ throw new Error('EPUB 正文渲染未完成,请刷新后重试');
287
+ }
288
+ if (disposed) {
289
+ return;
290
+ }
291
+ status = 'ready';
292
+ syncUi();
293
+ void book.locations.generate(1200).catch(() => undefined);
294
+ }
295
+ catch (error) {
296
+ console.error(error);
297
+ status = 'error';
298
+ state.textContent = error instanceof Error ? error.message : String(error);
299
+ syncUi();
300
+ }
301
+ };
302
+ listen(tocButton, 'click', () => {
303
+ tocOpen = !tocOpen;
304
+ syncUi();
305
+ });
306
+ listen(prevButton, 'click', () => {
307
+ void (rendition === null || rendition === void 0 ? void 0 : rendition.prev());
308
+ });
309
+ listen(nextButton, 'click', () => {
310
+ void (rendition === null || rendition === void 0 ? void 0 : rendition.next());
311
+ });
312
+ syncUi();
313
+ void openBook();
314
+ return {
315
+ $el: root,
316
+ unmount() {
317
+ disposed = true;
318
+ timers.forEach(timer => window.clearTimeout(timer));
319
+ timers.clear();
320
+ if (rendition) {
321
+ rendition.off('relocated', updateLocation);
322
+ rendition.destroy();
323
+ rendition = undefined;
324
+ }
325
+ book === null || book === void 0 ? void 0 : book.destroy();
326
+ book = undefined;
327
+ cleanups.splice(0).forEach(cleanup => cleanup());
328
+ target.replaceChildren();
329
+ },
330
+ };
331
+ }
@@ -0,0 +1,7 @@
1
+ import { type FileRenderHandler, type FileViewerRenderedInstance, type FileViewerRendererPlugin, type RendererDefinition } from '@file-viewer/core';
2
+ export declare const ebookRendererDefinition: RendererDefinition;
3
+ export declare const umdRendererDefinition: RendererDefinition;
4
+ export declare const renderFileViewerEpub: FileRenderHandler<FileViewerRenderedInstance, HTMLDivElement>;
5
+ export declare const renderFileViewerUmd: FileRenderHandler<FileViewerRenderedInstance, HTMLDivElement>;
6
+ export declare const ebookRenderer: FileViewerRendererPlugin<FileRenderHandler<FileViewerRenderedInstance, HTMLDivElement>>;
7
+ export default ebookRenderer;
package/dist/index.js ADDED
@@ -0,0 +1,26 @@
1
+ import { DEFAULT_RENDERER_DEFINITIONS, } from '@file-viewer/core';
2
+ const epubDefinition = DEFAULT_RENDERER_DEFINITIONS.find(definition => definition.id === 'epub');
3
+ const umdDefinition = DEFAULT_RENDERER_DEFINITIONS.find(definition => definition.id === 'umd');
4
+ if (!epubDefinition || !umdDefinition) {
5
+ throw new Error('@file-viewer/renderer-epub could not locate the shared ebook format definitions.');
6
+ }
7
+ export const ebookRendererDefinition = epubDefinition;
8
+ export const umdRendererDefinition = umdDefinition;
9
+ export const renderFileViewerEpub = (buffer, target) => import('./epub.js').then(({ default: renderEpub }) => renderEpub(buffer, target));
10
+ export const renderFileViewerUmd = (buffer, target) => import('./umd.js').then(({ default: renderUmd }) => renderUmd(buffer, target));
11
+ export const ebookRenderer = {
12
+ id: 'file-viewer-renderer-epub',
13
+ label: 'Flyfish File Viewer ebook renderer',
14
+ definitions: [ebookRendererDefinition, umdRendererDefinition],
15
+ handlers: [
16
+ {
17
+ rendererId: ebookRendererDefinition.id,
18
+ handler: renderFileViewerEpub,
19
+ },
20
+ {
21
+ rendererId: umdRendererDefinition.id,
22
+ handler: renderFileViewerUmd,
23
+ },
24
+ ],
25
+ };
26
+ export default ebookRenderer;
@@ -0,0 +1,30 @@
1
+ export type UmdBookKind = 'text' | 'comic' | 'mixed' | 'unknown';
2
+ export interface UmdImage {
3
+ bytes: Uint8Array;
4
+ extension: string;
5
+ id: string;
6
+ mimeType: string;
7
+ }
8
+ export interface UmdChapter {
9
+ content: string;
10
+ end: number;
11
+ id: string;
12
+ images: UmdImage[];
13
+ start: number;
14
+ title: string;
15
+ }
16
+ export interface UmdBook {
17
+ author: string;
18
+ category: string;
19
+ chapters: UmdChapter[];
20
+ contentLength: number;
21
+ cover?: UmdImage;
22
+ kind: UmdBookKind;
23
+ publishedAt: string;
24
+ publisher: string;
25
+ rawType: number;
26
+ title: string;
27
+ vendor: string;
28
+ warnings: string[];
29
+ }
30
+ export declare const parseUmdBook: (buffer: ArrayBuffer) => UmdBook;