@kyrven/react-pdf-viewer 0.0.0-stage → 0.4.0-beta.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.
Files changed (185) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +22 -2
  3. package/THIRD-PARTY/ab_glyph_rasterizer-0.1.10/LICENSE +176 -0
  4. package/THIRD-PARTY/adler2-2.0.1/LICENSE-0BSD +12 -0
  5. package/THIRD-PARTY/adler2-2.0.1/LICENSE-APACHE +201 -0
  6. package/THIRD-PARTY/adler2-2.0.1/LICENSE-MIT +23 -0
  7. package/THIRD-PARTY/alloc-no-stdlib-2.0.4/LICENSE +12 -0
  8. package/THIRD-PARTY/alloc-stdlib-0.2.4/LICENSE +12 -0
  9. package/THIRD-PARTY/alloc-stdlib-0.2.4/README.md +205 -0
  10. package/THIRD-PARTY/arrayvec-0.7.8/LICENSE-APACHE +201 -0
  11. package/THIRD-PARTY/arrayvec-0.7.8/LICENSE-MIT +25 -0
  12. package/THIRD-PARTY/autocfg-1.5.1/LICENSE-APACHE +201 -0
  13. package/THIRD-PARTY/autocfg-1.5.1/LICENSE-MIT +25 -0
  14. package/THIRD-PARTY/bitflags-2.13.2/LICENSE-APACHE +201 -0
  15. package/THIRD-PARTY/bitflags-2.13.2/LICENSE-MIT +25 -0
  16. package/THIRD-PARTY/brotli-8.0.4/LICENSE.BSD-3-Clause +12 -0
  17. package/THIRD-PARTY/brotli-8.0.4/LICENSE.MIT +19 -0
  18. package/THIRD-PARTY/brotli-decompressor-5.0.3/LICENSE +12 -0
  19. package/THIRD-PARTY/bytemuck-1.25.2/LICENSE-APACHE +61 -0
  20. package/THIRD-PARTY/bytemuck-1.25.2/LICENSE-MIT +9 -0
  21. package/THIRD-PARTY/bytemuck-1.25.2/LICENSE-ZLIB +11 -0
  22. package/THIRD-PARTY/bytemuck_derive-1.12.1/LICENSE-APACHE +61 -0
  23. package/THIRD-PARTY/bytemuck_derive-1.12.1/LICENSE-MIT +9 -0
  24. package/THIRD-PARTY/bytemuck_derive-1.12.1/LICENSE-ZLIB +11 -0
  25. package/THIRD-PARTY/byteorder-lite-0.1.0/LICENSE-MIT +21 -0
  26. package/THIRD-PARTY/byteorder-lite-0.1.0/UNLICENSE +24 -0
  27. package/THIRD-PARTY/cfg-if-1.0.5/LICENSE-APACHE +201 -0
  28. package/THIRD-PARTY/cfg-if-1.0.5/LICENSE-MIT +25 -0
  29. package/THIRD-PARTY/color-0.3.3/LICENSE-APACHE +176 -0
  30. package/THIRD-PARTY/color-0.3.3/LICENSE-MIT +19 -0
  31. package/THIRD-PARTY/crc32fast-1.5.5/LICENSE-APACHE +202 -0
  32. package/THIRD-PARTY/crc32fast-1.5.5/LICENSE-MIT +21 -0
  33. package/THIRD-PARTY/euclid-0.22.14/COPYRIGHT +5 -0
  34. package/THIRD-PARTY/euclid-0.22.14/LICENSE-APACHE +201 -0
  35. package/THIRD-PARTY/euclid-0.22.14/LICENSE-MIT +25 -0
  36. package/THIRD-PARTY/fastrand-2.5.0/LICENSE-APACHE +201 -0
  37. package/THIRD-PARTY/fastrand-2.5.0/LICENSE-MIT +23 -0
  38. package/THIRD-PARTY/fdeflate-0.3.7/LICENSE-APACHE +177 -0
  39. package/THIRD-PARTY/fdeflate-0.3.7/LICENSE-MIT +25 -0
  40. package/THIRD-PARTY/fearless_simd-0.7.0/LICENSE-APACHE +176 -0
  41. package/THIRD-PARTY/fearless_simd-0.7.0/LICENSE-MIT +25 -0
  42. package/THIRD-PARTY/fearless_simd-1.2.0/LICENSE-APACHE +176 -0
  43. package/THIRD-PARTY/fearless_simd-1.2.0/LICENSE-MIT +25 -0
  44. package/THIRD-PARTY/flate2-1.1.11/LICENSE-APACHE +201 -0
  45. package/THIRD-PARTY/flate2-1.1.11/LICENSE-MIT +25 -0
  46. package/THIRD-PARTY/foldhash-0.2.0/LICENSE +19 -0
  47. package/THIRD-PARTY/font-types-0.12.7/LICENSE-APACHE +67 -0
  48. package/THIRD-PARTY/font-types-0.12.7/LICENSE-MIT +25 -0
  49. package/THIRD-PARTY/glifo-0.4.0/LICENSE-APACHE +176 -0
  50. package/THIRD-PARTY/glifo-0.4.0/LICENSE-MIT +25 -0
  51. package/THIRD-PARTY/guillotiere-0.7.0/LICENSE-APACHE +13 -0
  52. package/THIRD-PARTY/guillotiere-0.7.0/LICENSE-MIT +20 -0
  53. package/THIRD-PARTY/hashbrown-0.17.1/LICENSE-APACHE +201 -0
  54. package/THIRD-PARTY/hashbrown-0.17.1/LICENSE-MIT +25 -0
  55. package/THIRD-PARTY/hayro-0.9.0/LICENSE-APACHE +177 -0
  56. package/THIRD-PARTY/hayro-0.9.0/LICENSE-MIT +7 -0
  57. package/THIRD-PARTY/hayro-0.9.0/NOTICE.md +190 -0
  58. package/THIRD-PARTY/hayro-ccitt-0.5.0/LICENSE-APACHE +177 -0
  59. package/THIRD-PARTY/hayro-ccitt-0.5.0/LICENSE-MIT +7 -0
  60. package/THIRD-PARTY/hayro-cmap-0.1.1/LICENSE-APACHE +177 -0
  61. package/THIRD-PARTY/hayro-cmap-0.1.1/LICENSE-MIT +7 -0
  62. package/THIRD-PARTY/hayro-cmap-0.1.1/asset-LICENSE.txt +28 -0
  63. package/THIRD-PARTY/hayro-font-0.5.0/LICENSE-APACHE +177 -0
  64. package/THIRD-PARTY/hayro-font-0.5.0/LICENSE-MIT +7 -0
  65. package/THIRD-PARTY/hayro-font-0.5.0/asset-LICENSE_FOXIT +27 -0
  66. package/THIRD-PARTY/hayro-font-0.5.0/asset-attribution.md +11 -0
  67. package/THIRD-PARTY/hayro-interpret-0.9.0/CGATS_LICENSE.txt +116 -0
  68. package/THIRD-PARTY/hayro-interpret-0.9.0/LICENSE-APACHE +177 -0
  69. package/THIRD-PARTY/hayro-interpret-0.9.0/LICENSE-MIT +7 -0
  70. package/THIRD-PARTY/hayro-jbig2-0.4.0/LICENSE-APACHE +177 -0
  71. package/THIRD-PARTY/hayro-jbig2-0.4.0/LICENSE-MIT +7 -0
  72. package/THIRD-PARTY/hayro-jpeg2000-0.5.0/LICENSE-APACHE +177 -0
  73. package/THIRD-PARTY/hayro-jpeg2000-0.5.0/LICENSE-MIT +7 -0
  74. package/THIRD-PARTY/hayro-jpeg2000-0.5.0/asset-LICENSE.txt +116 -0
  75. package/THIRD-PARTY/hayro-postscript-0.2.0/LICENSE-APACHE +177 -0
  76. package/THIRD-PARTY/hayro-postscript-0.2.0/LICENSE-MIT +7 -0
  77. package/THIRD-PARTY/hayro-syntax-0.9.0/LICENSE-APACHE +177 -0
  78. package/THIRD-PARTY/hayro-syntax-0.9.0/LICENSE-MIT +7 -0
  79. package/THIRD-PARTY/image-0.25.10/LICENSE-APACHE +177 -0
  80. package/THIRD-PARTY/image-0.25.10/LICENSE-MIT +25 -0
  81. package/THIRD-PARTY/kurbo-0.13.1/LICENSE-APACHE +202 -0
  82. package/THIRD-PARTY/kurbo-0.13.1/LICENSE-MIT +25 -0
  83. package/THIRD-PARTY/linebender_resource_handle-0.1.1/LICENSE-APACHE +176 -0
  84. package/THIRD-PARTY/linebender_resource_handle-0.1.1/LICENSE-MIT +19 -0
  85. package/THIRD-PARTY/log-0.4.35/LICENSE-APACHE +201 -0
  86. package/THIRD-PARTY/log-0.4.35/LICENSE-MIT +25 -0
  87. package/THIRD-PARTY/memchr-2.8.3/COPYING +3 -0
  88. package/THIRD-PARTY/memchr-2.8.3/LICENSE-MIT +21 -0
  89. package/THIRD-PARTY/memchr-2.8.3/UNLICENSE +24 -0
  90. package/THIRD-PARTY/miniz_oxide-0.8.9/LICENSE +25 -0
  91. package/THIRD-PARTY/miniz_oxide-0.8.9/LICENSE-APACHE.md +177 -0
  92. package/THIRD-PARTY/miniz_oxide-0.8.9/LICENSE-MIT.md +24 -0
  93. package/THIRD-PARTY/miniz_oxide-0.8.9/LICENSE-ZLIB.md +14 -0
  94. package/THIRD-PARTY/miniz_oxide-0.9.1/LICENSE +25 -0
  95. package/THIRD-PARTY/miniz_oxide-0.9.1/LICENSE-APACHE.md +177 -0
  96. package/THIRD-PARTY/miniz_oxide-0.9.1/LICENSE-MIT.md +24 -0
  97. package/THIRD-PARTY/miniz_oxide-0.9.1/LICENSE-ZLIB.md +14 -0
  98. package/THIRD-PARTY/moxcms-0.8.1/LICENSE-APACHE.md +201 -0
  99. package/THIRD-PARTY/moxcms-0.8.1/LICENSE.md +26 -0
  100. package/THIRD-PARTY/num-traits-0.2.19/LICENSE-APACHE +201 -0
  101. package/THIRD-PARTY/num-traits-0.2.19/LICENSE-MIT +25 -0
  102. package/THIRD-PARTY/once_cell-1.21.4/LICENSE-APACHE +201 -0
  103. package/THIRD-PARTY/once_cell-1.21.4/LICENSE-MIT +23 -0
  104. package/THIRD-PARTY/peniko-0.6.1/LICENSE-APACHE +203 -0
  105. package/THIRD-PARTY/peniko-0.6.1/LICENSE-MIT +25 -0
  106. package/THIRD-PARTY/phf-0.13.1/LICENSE +20 -0
  107. package/THIRD-PARTY/phf_generator-0.13.1/LICENSE +20 -0
  108. package/THIRD-PARTY/phf_macros-0.13.1/LICENSE +20 -0
  109. package/THIRD-PARTY/phf_shared-0.13.1/LICENSE +20 -0
  110. package/THIRD-PARTY/pic-scale-0.7.14/LICENSE-APACHE.md +201 -0
  111. package/THIRD-PARTY/pic-scale-0.7.14/LICENSE.md +26 -0
  112. package/THIRD-PARTY/png-0.18.1/LICENSE-APACHE +201 -0
  113. package/THIRD-PARTY/png-0.18.1/LICENSE-MIT +25 -0
  114. package/THIRD-PARTY/polycool-0.4.0/LICENSE-APACHE +202 -0
  115. package/THIRD-PARTY/polycool-0.4.0/LICENSE-MIT +25 -0
  116. package/THIRD-PARTY/proc-macro2-1.0.107/LICENSE-APACHE +176 -0
  117. package/THIRD-PARTY/proc-macro2-1.0.107/LICENSE-MIT +23 -0
  118. package/THIRD-PARTY/pxfm-0.1.30/LICENSE-APACHE.md +201 -0
  119. package/THIRD-PARTY/pxfm-0.1.30/LICENSE.md +26 -0
  120. package/THIRD-PARTY/quote-1.0.47/LICENSE-APACHE +176 -0
  121. package/THIRD-PARTY/quote-1.0.47/LICENSE-MIT +23 -0
  122. package/THIRD-PARTY/read-fonts-0.41.0/LICENSE-APACHE +67 -0
  123. package/THIRD-PARTY/read-fonts-0.41.0/LICENSE-MIT +25 -0
  124. package/THIRD-PARTY/read-fonts-0.46.0/LICENSE-APACHE +67 -0
  125. package/THIRD-PARTY/read-fonts-0.46.0/LICENSE-MIT +25 -0
  126. package/THIRD-PARTY/rust-dependencies.csv +81 -0
  127. package/THIRD-PARTY/rustc-hash-2.1.3/LICENSE-APACHE +176 -0
  128. package/THIRD-PARTY/rustc-hash-2.1.3/LICENSE-MIT +23 -0
  129. package/THIRD-PARTY/simd-adler32-0.3.10/LICENSE.md +21 -0
  130. package/THIRD-PARTY/siphasher-1.0.4/COPYING +7 -0
  131. package/THIRD-PARTY/siphasher-1.0.4/LICENSE-APACHE +202 -0
  132. package/THIRD-PARTY/siphasher-1.0.4/LICENSE-MIT +17 -0
  133. package/THIRD-PARTY/skrifa-0.44.0/LICENSE-APACHE +67 -0
  134. package/THIRD-PARTY/skrifa-0.44.0/LICENSE-MIT +25 -0
  135. package/THIRD-PARTY/skrifa-0.49.0/LICENSE-APACHE +67 -0
  136. package/THIRD-PARTY/skrifa-0.49.0/LICENSE-MIT +25 -0
  137. package/THIRD-PARTY/smallvec-1.16.6/LICENSE-APACHE +201 -0
  138. package/THIRD-PARTY/smallvec-1.16.6/LICENSE-MIT +25 -0
  139. package/THIRD-PARTY/stable_deref_trait-1.2.1/LICENSE-APACHE +201 -0
  140. package/THIRD-PARTY/stable_deref_trait-1.2.1/LICENSE-MIT +25 -0
  141. package/THIRD-PARTY/syn-2.0.119/LICENSE-APACHE +176 -0
  142. package/THIRD-PARTY/syn-2.0.119/LICENSE-MIT +23 -0
  143. package/THIRD-PARTY/syn-3.0.10/LICENSE-APACHE +176 -0
  144. package/THIRD-PARTY/syn-3.0.10/LICENSE-MIT +23 -0
  145. package/THIRD-PARTY/synstructure-0.14.0/LICENSE +7 -0
  146. package/THIRD-PARTY/thiserror-2.0.21/LICENSE-APACHE +176 -0
  147. package/THIRD-PARTY/thiserror-2.0.21/LICENSE-MIT +23 -0
  148. package/THIRD-PARTY/thiserror-impl-2.0.21/LICENSE-APACHE +176 -0
  149. package/THIRD-PARTY/thiserror-impl-2.0.21/LICENSE-MIT +23 -0
  150. package/THIRD-PARTY/unicode-ident-1.0.27/LICENSE-APACHE +176 -0
  151. package/THIRD-PARTY/unicode-ident-1.0.27/LICENSE-MIT +23 -0
  152. package/THIRD-PARTY/unicode-ident-1.0.27/LICENSE-UNICODE +39 -0
  153. package/THIRD-PARTY/vello_common-0.3.0/LICENSE-APACHE +176 -0
  154. package/THIRD-PARTY/vello_common-0.3.0/LICENSE-MIT +25 -0
  155. package/THIRD-PARTY/vello_cpu-0.3.0/LICENSE-APACHE +176 -0
  156. package/THIRD-PARTY/vello_cpu-0.3.0/LICENSE-MIT +25 -0
  157. package/THIRD-PARTY/wasm-cargo-tree.txt +151 -0
  158. package/THIRD-PARTY/yoke-0.8.4/LICENSE +46 -0
  159. package/THIRD-PARTY/yoke-derive-0.8.4/LICENSE +46 -0
  160. package/THIRD-PARTY/zerofrom-0.1.8/LICENSE +46 -0
  161. package/THIRD-PARTY/zerofrom-derive-0.1.8/LICENSE +46 -0
  162. package/THIRD-PARTY/zlib-rs-0.6.8/LICENSE +19 -0
  163. package/THIRD-PARTY/zune-core-0.5.3/LICENSE-APACHE +201 -0
  164. package/THIRD-PARTY/zune-core-0.5.3/LICENSE-MIT +21 -0
  165. package/THIRD-PARTY/zune-core-0.5.3/LICENSE-ZLIB +19 -0
  166. package/THIRD-PARTY/zune-jpeg-0.5.15/LICENSE-APACHE +201 -0
  167. package/THIRD-PARTY/zune-jpeg-0.5.15/LICENSE-MIT +21 -0
  168. package/THIRD-PARTY/zune-jpeg-0.5.15/LICENSE-ZLIB +19 -0
  169. package/dist-lib/PdfViewer.d.ts +22 -0
  170. package/dist-lib/PdfViewer.js +89 -0
  171. package/dist-lib/document.d.ts +15 -0
  172. package/dist-lib/document.js +130 -0
  173. package/dist-lib/engine/hayro.wasm +0 -0
  174. package/dist-lib/engine/pdf.worker.mjs +71 -0
  175. package/dist-lib/index.d.ts +4 -0
  176. package/dist-lib/index.js +9 -0
  177. package/dist-lib/pages.d.ts +9 -0
  178. package/dist-lib/pages.js +184 -0
  179. package/dist-lib/source.d.ts +2 -0
  180. package/dist-lib/source.js +51 -0
  181. package/dist-lib/static.d.ts +2 -0
  182. package/dist-lib/static.js +1 -0
  183. package/dist-lib/viewer.css +84 -0
  184. package/package.json +49 -4
  185. package/scripts/hayro-assets.mjs +8 -0
@@ -0,0 +1,89 @@
1
+ 'use client';
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useEffect, useId, useRef, useState } from 'react';
4
+ import { mountPages } from './pages.js';
5
+ import { openPdf } from './document.js';
6
+ import './viewer.css';
7
+ const boundedZoom = (value) => Number.isFinite(value) ? Math.max(0.25, Math.min(3, value)) : 1;
8
+ export function PdfViewer({ src, assetsUrl, engine, options, onLoad, onPageChange, onError, }) {
9
+ const [page, setPage] = useState(1);
10
+ const [count, setCount] = useState(0);
11
+ const [zoom, setZoom] = useState(1);
12
+ const [error, setError] = useState('');
13
+ const viewport = useRef(null);
14
+ const view = useRef(null);
15
+ const callbacks = useRef({ onLoad, onPageChange, onError });
16
+ const pageInputId = useId();
17
+ const initialZoom = boundedZoom(options?.initialZoom ?? 1);
18
+ const initialLayout = options?.layout ?? 'continuous';
19
+ const [layout, setLayout] = useState(initialLayout);
20
+ useEffect(() => setLayout(initialLayout), [initialLayout]);
21
+ const continuous = layout === 'continuous';
22
+ const { maxFileBytes, maxPages } = options ?? {};
23
+ const toolbar = options?.toolbar ?? ['page', 'zoom', 'settings'];
24
+ const requestedCache = options?.maxCachedPages ?? 6;
25
+ const cacheLimit = Number.isFinite(requestedCache)
26
+ ? Math.min(6, Math.max(1, Math.floor(requestedCache)))
27
+ : 6;
28
+ const display = useRef({ continuous, cacheLimit });
29
+ useEffect(() => {
30
+ display.current = { continuous, cacheLimit };
31
+ view.current?.configure(continuous, cacheLimit);
32
+ }, [continuous, cacheLimit]);
33
+ useEffect(() => {
34
+ callbacks.current = { onLoad, onPageChange, onError };
35
+ }, [onLoad, onPageChange, onError]);
36
+ useEffect(() => {
37
+ const node = viewport.current;
38
+ if (!node)
39
+ return;
40
+ const abort = new AbortController();
41
+ let close;
42
+ setError('');
43
+ setPage(1);
44
+ setCount(0);
45
+ setZoom(initialZoom);
46
+ const fail = (reason) => {
47
+ if (abort.signal.aborted)
48
+ return;
49
+ const failure = reason instanceof Error ? reason : new Error(String(reason));
50
+ setError(failure.message);
51
+ callbacks.current.onError?.(failure);
52
+ };
53
+ void openPdf(src, assetsUrl ?? '/hayro/', abort.signal, maxFileBytes, maxPages, assetsUrl ? undefined : engine)
54
+ .then((document) => {
55
+ if (abort.signal.aborted) {
56
+ document.close();
57
+ return;
58
+ }
59
+ close = document.close;
60
+ if (!document.pageCount)
61
+ throw new Error('El documento no contiene páginas.');
62
+ view.current = mountPages(node, document, display.current.continuous, display.current.cacheLimit, initialZoom, (number) => {
63
+ setPage(number);
64
+ callbacks.current.onPageChange?.(number);
65
+ }, fail);
66
+ setCount(document.pageCount);
67
+ callbacks.current.onLoad?.(document.pageCount);
68
+ callbacks.current.onPageChange?.(1);
69
+ })
70
+ .catch(fail);
71
+ return () => {
72
+ abort.abort();
73
+ view.current?.destroy();
74
+ view.current = null;
75
+ close?.();
76
+ };
77
+ }, [src, engine, assetsUrl, initialZoom, maxFileBytes, maxPages]);
78
+ function changeZoom(amount) {
79
+ const updated = boundedZoom(zoom + amount);
80
+ setZoom(updated);
81
+ view.current?.setZoom(updated);
82
+ }
83
+ return (_jsxs("section", { className: "krpdf", "aria-label": "Visor PDF", children: [toolbar.length > 0 && (_jsxs("div", { className: "krpdf-controls", children: [toolbar.includes('page') && (_jsxs("form", { onSubmit: (event) => {
84
+ event.preventDefault();
85
+ const number = Number(new FormData(event.currentTarget).get('page'));
86
+ if (Number.isInteger(number) && number > 0)
87
+ view.current?.goTo(number);
88
+ }, children: [_jsx("button", { type: "button", disabled: page <= 1 || !count, onClick: () => view.current?.goTo(page - 1), "aria-label": "P\u00E1gina anterior", children: "\u2039" }), _jsx("label", { htmlFor: pageInputId, children: "P\u00E1gina" }), _jsx("input", { id: pageInputId, disabled: !count, name: "page", type: "number", min: 1, max: count || 1, defaultValue: page }, page), _jsxs("span", { children: ["/ ", count || '—'] }), _jsx("button", { type: "button", disabled: page >= count, onClick: () => view.current?.goTo(page + 1), "aria-label": "P\u00E1gina siguiente", children: "\u203A" })] })), toolbar.includes('zoom') && (_jsxs("div", { role: "group", "aria-label": "Zoom", children: [_jsx("button", { type: "button", disabled: !count || zoom <= 0.25, onClick: () => changeZoom(-0.25), "aria-label": "Reducir zoom", children: "\u2212" }), _jsxs("span", { children: [Math.round(zoom * 100), " %"] }), _jsx("button", { type: "button", disabled: !count || zoom >= 3, onClick: () => changeZoom(0.25), "aria-label": "Aumentar zoom", children: "+" })] })), toolbar.includes('settings') && (_jsxs("details", { className: "krpdf-settings", children: [_jsx("summary", { children: "Opciones" }), _jsxs("label", { children: ["Vista", _jsxs("select", { value: layout, onChange: event => setLayout(event.currentTarget.value === 'single' ? 'single' : 'continuous'), children: [_jsx("option", { value: "continuous", children: "Scroll continuo" }), _jsx("option", { value: "single", children: "Una p\u00E1gina" })] })] })] }))] })), error && (_jsx("p", { className: "krpdf-message", role: "alert", children: error })), !error && !count && (_jsx("p", { className: "krpdf-message", role: "status", children: "Abriendo PDF\u2026" })), _jsx("div", { ref: viewport, className: "krpdf-viewport", style: { height: options?.height }, tabIndex: 0, "aria-label": "P\u00E1ginas del PDF" })] }));
89
+ }
@@ -0,0 +1,15 @@
1
+ import { type PdfSource } from './source.js';
2
+ export type { PdfSource } from './source.js';
3
+ export type EngineAssets = {
4
+ workerUrl: string;
5
+ wasmUrl: string;
6
+ };
7
+ export declare function openPdf(source: PdfSource, assetsUrl: string, signal: AbortSignal, maxFileBytes?: number, maxPages?: number, engine?: EngineAssets): Promise<{
8
+ pageCount: number;
9
+ render: (number: number, zoom: number, abort: AbortSignal) => Promise<{
10
+ canvas: HTMLCanvasElement;
11
+ width: number;
12
+ height: number;
13
+ }>;
14
+ close: () => void;
15
+ }>;
@@ -0,0 +1,130 @@
1
+ import { readPdf } from './source.js';
2
+ const MiB = 1024 * 1024;
3
+ const deadline = 30_000;
4
+ function bounded(value, maximum) {
5
+ if (value === undefined)
6
+ return maximum;
7
+ if (!Number.isSafeInteger(value) || value < 1)
8
+ throw new Error('El límite debe ser un entero positivo.');
9
+ return Math.min(value, maximum);
10
+ }
11
+ export async function openPdf(source, assetsUrl, signal, maxFileBytes, maxPages, engine) {
12
+ signal.throwIfAborted();
13
+ const limit = bounded(maxPages, 2000);
14
+ const base = new URL(assetsUrl.replace(/\/?$/, '/'), document.baseURI);
15
+ const url = engine ? new URL(engine.workerUrl, document.baseURI) : new URL('pdf.worker.mjs', base);
16
+ const wasm = engine ? new URL(engine.wasmUrl, document.baseURI) : new URL('hayro.wasm', base);
17
+ for (const asset of [url, wasm]) {
18
+ if (asset.origin !== location.origin || !['https:', 'http:'].includes(asset.protocol)) {
19
+ throw new Error('Los recursos del motor deben servirse desde el mismo origen.');
20
+ }
21
+ }
22
+ let file = await readPdf(source, bounded(maxFileBytes, 64 * MiB), signal);
23
+ signal.throwIfAborted();
24
+ let worker;
25
+ let pending;
26
+ let closed = false;
27
+ function stop(error) {
28
+ worker?.terminate();
29
+ worker = undefined;
30
+ pending?.(error);
31
+ }
32
+ function close() {
33
+ closed = true;
34
+ file = undefined;
35
+ stop(new DOMException('Documento cerrado.', 'AbortError'));
36
+ signal.removeEventListener('abort', close);
37
+ }
38
+ signal.addEventListener('abort', close, { once: true });
39
+ function request(payload, expires, abort) {
40
+ if (closed)
41
+ throw new DOMException('Documento cerrado.', 'AbortError');
42
+ abort?.throwIfAborted();
43
+ if (pending)
44
+ throw new Error('Hay una operación PDF en curso.');
45
+ const port = worker ??= new Worker(url, { type: 'module' });
46
+ return new Promise((resolve, reject) => {
47
+ const interrupted = () => stop(abort?.reason);
48
+ const timer = setTimeout(() => stop(new Error('El motor PDF superó los 30 segundos.')), Math.max(0, expires - performance.now()));
49
+ function cleanup() {
50
+ clearTimeout(timer);
51
+ abort?.removeEventListener('abort', interrupted);
52
+ port.onmessage = port.onerror = port.onmessageerror = null;
53
+ pending = undefined;
54
+ }
55
+ pending = error => {
56
+ cleanup();
57
+ reject(error);
58
+ };
59
+ abort?.addEventListener('abort', interrupted, { once: true });
60
+ port.onerror = event => {
61
+ event.preventDefault();
62
+ stop(new Error('No se pudo ejecutar el worker de Hayro.'));
63
+ };
64
+ port.onmessageerror = () => stop(new Error('Respuesta del worker ilegible.'));
65
+ port.onmessage = ({ data }) => {
66
+ cleanup();
67
+ if (data.error)
68
+ reject(new Error(data.error));
69
+ else
70
+ resolve(data);
71
+ };
72
+ try {
73
+ port.postMessage(payload);
74
+ }
75
+ catch (error) {
76
+ stop(error);
77
+ }
78
+ });
79
+ }
80
+ async function open(expires, abort) {
81
+ const start = performance.now();
82
+ const result = await request({ kind: 'open', file, limit, wasmUrl: wasm.href }, expires, abort);
83
+ performance.measure('hayro:open', { start, end: performance.now(), detail: result.metrics });
84
+ return result.pageCount;
85
+ }
86
+ try {
87
+ const pageCount = await open(performance.now() + deadline);
88
+ let rendering = false;
89
+ async function render(number, zoom, abort) {
90
+ if (!Number.isInteger(number) || number < 1 || number > pageCount)
91
+ throw new Error('Página fuera de rango.');
92
+ if (rendering)
93
+ throw new Error('Ya hay un render en curso.');
94
+ rendering = true;
95
+ const start = performance.now();
96
+ const end = start + deadline;
97
+ try {
98
+ if (!worker)
99
+ await open(end, abort);
100
+ const result = await request({
101
+ kind: 'render', number, scale: zoom * (window.devicePixelRatio || 1),
102
+ }, end, abort);
103
+ const drawStart = performance.now();
104
+ const canvas = document.createElement('canvas');
105
+ canvas.width = result.pixelWidth;
106
+ canvas.height = result.pixelHeight;
107
+ const context = canvas.getContext('2d');
108
+ if (!context)
109
+ throw new Error('Canvas 2D no disponible.');
110
+ context.putImageData(new ImageData(result.pixels, canvas.width, canvas.height), 0, 0);
111
+ canvas.setAttribute('role', 'img');
112
+ canvas.setAttribute('aria-label', `Página ${number}`);
113
+ const drawn = performance.now();
114
+ performance.measure('hayro:render', { start, end: drawn, detail: {
115
+ ...result.metrics, drawMs: drawn - drawStart,
116
+ receiveMs: Math.max(0, performance.timeOrigin + drawStart - result.metrics.sentAt),
117
+ } });
118
+ return { canvas, width: result.width, height: result.height };
119
+ }
120
+ finally {
121
+ rendering = false;
122
+ }
123
+ }
124
+ return { pageCount, render, close };
125
+ }
126
+ catch (error) {
127
+ close();
128
+ throw error;
129
+ }
130
+ }
Binary file
@@ -0,0 +1,71 @@
1
+ let engine
2
+ const decoder = new TextDecoder()
3
+ const now = () => performance.timeOrigin + performance.now()
4
+
5
+ async function open({ file, limit, wasmUrl: resource }) {
6
+ if (!file.size || file.size > 64 * 1024 * 1024) throw new Error('Tamaño de PDF fuera de límite.')
7
+ const start = performance.now()
8
+ const wasmUrl = new URL(resource)
9
+ const [wasm, input] = await Promise.all([
10
+ WebAssembly.instantiateStreaming(fetch(wasmUrl, { mode: 'same-origin', redirect: 'error' }), {})
11
+ .then(({ instance }) => ({ engine: instance.exports, initMs: performance.now() - start })),
12
+ file.arrayBuffer(),
13
+ ])
14
+ engine = wasm.engine
15
+ const copyStart = performance.now()
16
+ const offset = engine.pdf_allocate(input.byteLength)
17
+ new Uint8Array(engine.memory.buffer, offset, input.byteLength).set(new Uint8Array(input))
18
+ const inputCopyMs = performance.now() - copyStart
19
+ const parseStart = performance.now()
20
+ const pageCount = engine.pdf_open(limit)
21
+ const parseMs = performance.now() - parseStart
22
+ if (pageCount < 1) {
23
+ throw new Error({
24
+ '-1': 'PDF inválido o truncado.',
25
+ '-2': 'Cantidad de páginas fuera de límite.',
26
+ '-3': 'PDF cifrado o contraseña requerida.',
27
+ }[pageCount] || 'No se pudo abrir el PDF.')
28
+ }
29
+ const { transferSize, encodedBodySize, decodedBodySize } =
30
+ performance.getEntriesByName(wasmUrl.href).at(-1) ?? {}
31
+ return { pageCount, metrics: {
32
+ initMs: wasm.initMs, parseMs, inputCopyMs, transferSize, encodedBodySize, decodedBodySize,
33
+ wasmMemory: engine.memory.buffer.byteLength,
34
+ } }
35
+ }
36
+
37
+ function render({ number, scale }) {
38
+ const start = performance.now()
39
+ const dimensions = engine.pdf_render(number - 1, scale)
40
+ const rasterMs = performance.now() - start
41
+ if (!dimensions) throw new Error('Dimensiones o página fuera de límite.')
42
+ const pixelWidth = dimensions & 0xffff
43
+ const pixelHeight = dimensions >>> 16
44
+ const copyStart = performance.now()
45
+ const wasmPixels = new Uint8ClampedArray(
46
+ engine.memory.buffer, engine.pixel_pointer(), pixelWidth * pixelHeight * 4,
47
+ )
48
+ // WASM memory cannot be transferred. The copied buffer is transferable.
49
+ const pixels = wasmPixels.slice()
50
+ const copyMs = performance.now() - copyStart
51
+ engine.release_pixels()
52
+ const warnings = decoder.decode(new Uint8Array(
53
+ engine.memory.buffer, engine.warnings_pointer(), engine.warnings_length(),
54
+ ))
55
+ return {
56
+ width: engine.pdf_width(), height: engine.pdf_height(), pixelWidth, pixelHeight, pixels,
57
+ metrics: { number, rasterMs, copyMs, warnings, pixelBytes: pixels.byteLength,
58
+ wasmMemory: engine.memory.buffer.byteLength, sentAt: now() },
59
+ }
60
+ }
61
+
62
+ self.onmessage = async ({ data }) => {
63
+ try {
64
+ const result = data.kind === 'open' ? await open(data) : render(data)
65
+ self.postMessage(result, result.pixels ? [result.pixels.buffer] : [])
66
+ } catch (error) {
67
+ self.postMessage({ error: error instanceof Error ? error.message : String(error) })
68
+ }
69
+ }
70
+
71
+
@@ -0,0 +1,4 @@
1
+ import { type PdfViewerProps } from './PdfViewer.js';
2
+ export declare function PdfViewer(props: PdfViewerProps): import("react").JSX.Element;
3
+ export type { PdfViewerProps, PdfViewerOptions } from './PdfViewer.js';
4
+ export type { PdfSource } from './source.js';
@@ -0,0 +1,9 @@
1
+ 'use client';
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { PdfViewer as Viewer } from './PdfViewer.js';
4
+ const workerUrl = new URL('@kyrven/react-pdf-viewer/pdf.worker.mjs?no-inline', import.meta.url).href;
5
+ const wasmUrl = new URL('@kyrven/react-pdf-viewer/hayro.wasm', import.meta.url).href;
6
+ const engine = { workerUrl, wasmUrl };
7
+ export function PdfViewer(props) {
8
+ return _jsx(Viewer, { ...props, engine: engine });
9
+ }
@@ -0,0 +1,9 @@
1
+ import type { openPdf } from './document.js';
2
+ type OpenPdf = Awaited<ReturnType<typeof openPdf>>;
3
+ export declare function mountPages(viewport: HTMLDivElement, { render, pageCount }: OpenPdf, continuous: boolean, cacheLimit: number, initialZoom: number, onPage: (page: number) => void, onError: (error: Error) => void): {
4
+ goTo: (number: number) => void;
5
+ configure(nextContinuous: boolean, nextCacheLimit: number): void;
6
+ setZoom(value: number): void;
7
+ destroy(): void;
8
+ };
9
+ export {};
@@ -0,0 +1,184 @@
1
+ export function mountPages(viewport, { render, pageCount }, continuous, cacheLimit, initialZoom, onPage, onError) {
2
+ const strip = document.createElement('div');
3
+ strip.className = 'krpdf-strip';
4
+ viewport.append(strip);
5
+ const sizes = new Map();
6
+ const cache = new Set();
7
+ let sheets = [];
8
+ let page = 1;
9
+ let zoom = initialZoom;
10
+ let frame = 0;
11
+ let disposed = false;
12
+ let running;
13
+ function sizeSheet(sheet, number) {
14
+ const { width, height } = sizes.get(number) ?? { width: 612, height: 792 };
15
+ sheet.element.style.width = `${width * zoom}px`;
16
+ sheet.element.style.height = `${height * zoom}px`;
17
+ }
18
+ function release(sheet) {
19
+ if (sheet.canvas) {
20
+ sheet.canvas.width = sheet.canvas.height = 0;
21
+ sheet.canvas.remove();
22
+ sheet.canvas = undefined;
23
+ }
24
+ cache.delete(sheet);
25
+ }
26
+ function goTo(number) {
27
+ const target = Math.min(pageCount, Math.max(1, number));
28
+ if (target !== page) {
29
+ page = target;
30
+ onPage(page);
31
+ }
32
+ if (continuous) {
33
+ viewport.scrollTop = page > 1 ? sheets[page - 1].element.offsetTop : 0;
34
+ schedule();
35
+ }
36
+ else {
37
+ rebuild();
38
+ }
39
+ }
40
+ function rebuild() {
41
+ running?.abort.abort();
42
+ for (const sheet of cache)
43
+ release(sheet);
44
+ const fragment = document.createDocumentFragment();
45
+ sheets = Array.from({ length: continuous ? pageCount : 1 }, (_, index) => {
46
+ const number = continuous ? index + 1 : page;
47
+ const element = document.createElement('div');
48
+ element.className = 'krpdf-sheet';
49
+ element.dataset.page = String(number);
50
+ const sheet = { element };
51
+ sizeSheet(sheet, number);
52
+ fragment.append(element);
53
+ return sheet;
54
+ });
55
+ strip.replaceChildren(fragment);
56
+ sizeBottomPadding();
57
+ viewport.scrollTop = continuous && page > 1 ? sheets[page - 1].element.offsetTop : 0;
58
+ schedule();
59
+ }
60
+ function schedule() {
61
+ if (!disposed && !frame)
62
+ frame = requestAnimationFrame(renderVisible);
63
+ }
64
+ function sizeBottomPadding() {
65
+ if (!continuous)
66
+ strip.style.paddingBottom = '';
67
+ if (continuous) {
68
+ const lastSheet = sheets[sheets.length - 1].element;
69
+ strip.style.paddingBottom = `${Math.max(12, viewport.clientHeight - lastSheet.offsetHeight)}px`;
70
+ }
71
+ }
72
+ function wantedPages() {
73
+ if (!continuous)
74
+ return [page];
75
+ const top = viewport.scrollTop;
76
+ const bottom = top + viewport.clientHeight;
77
+ let first = 0;
78
+ let last = sheets.length - 1;
79
+ while (first < last) {
80
+ const middle = Math.floor((first + last) / 2);
81
+ const { offsetTop, offsetHeight } = sheets[middle].element;
82
+ if (offsetTop + offsetHeight <= top)
83
+ first = middle + 1;
84
+ else
85
+ last = middle;
86
+ }
87
+ if (first + 1 !== page) {
88
+ page = first + 1;
89
+ onPage(page);
90
+ }
91
+ const wanted = [page];
92
+ for (let i = first + 1; i < sheets.length && wanted.length < cacheLimit; i++) {
93
+ if (sheets[i].element.offsetTop >= bottom)
94
+ break;
95
+ wanted.push(i + 1);
96
+ }
97
+ const after = wanted[wanted.length - 1] + 1;
98
+ if (after <= pageCount)
99
+ wanted.push(after);
100
+ if (page > 1)
101
+ wanted.push(page - 1);
102
+ return wanted.slice(0, cacheLimit);
103
+ }
104
+ function renderVisible() {
105
+ frame = 0;
106
+ const wanted = wantedPages();
107
+ const getSheet = (number) => sheets[continuous ? number - 1 : 0];
108
+ const kept = new Set(wanted.map(getSheet));
109
+ for (const sheet of cache)
110
+ if (!kept.has(sheet))
111
+ release(sheet);
112
+ if (running) {
113
+ if (!wanted.includes(running.number))
114
+ running.abort.abort();
115
+ return;
116
+ }
117
+ const number = wanted.find((value) => !getSheet(value).canvas && !getSheet(value).failed);
118
+ if (number === undefined)
119
+ return;
120
+ const sheet = getSheet(number);
121
+ const abort = new AbortController();
122
+ running = { number, abort };
123
+ void render(number, zoom, abort.signal)
124
+ .then((result) => {
125
+ if (abort.signal.aborted) {
126
+ result.canvas.width = result.canvas.height = 0;
127
+ return;
128
+ }
129
+ sizes.set(number, { width: result.width, height: result.height });
130
+ sizeSheet(sheet, number);
131
+ if (number === pageCount)
132
+ sizeBottomPadding();
133
+ sheet.canvas = result.canvas;
134
+ sheet.element.append(result.canvas);
135
+ cache.add(sheet);
136
+ })
137
+ .catch((reason) => {
138
+ if (abort.signal.aborted)
139
+ return;
140
+ sheet.failed = true;
141
+ const error = reason instanceof Error ? reason.message : String(reason);
142
+ onError(new Error(`Página ${number} · ${error}`));
143
+ })
144
+ .finally(() => {
145
+ running = undefined;
146
+ schedule();
147
+ });
148
+ }
149
+ rebuild();
150
+ const resize = new ResizeObserver(() => {
151
+ sizeBottomPadding();
152
+ schedule();
153
+ });
154
+ resize.observe(viewport);
155
+ viewport.addEventListener('scroll', schedule, { passive: true });
156
+ return {
157
+ goTo,
158
+ configure(nextContinuous, nextCacheLimit) {
159
+ cacheLimit = nextCacheLimit;
160
+ if (continuous === nextContinuous)
161
+ schedule();
162
+ else {
163
+ continuous = nextContinuous;
164
+ rebuild();
165
+ }
166
+ },
167
+ setZoom(value) {
168
+ if (value === zoom)
169
+ return;
170
+ zoom = value;
171
+ rebuild();
172
+ },
173
+ destroy() {
174
+ disposed = true;
175
+ running?.abort.abort();
176
+ cancelAnimationFrame(frame);
177
+ resize.disconnect();
178
+ viewport.removeEventListener('scroll', schedule);
179
+ for (const sheet of cache)
180
+ release(sheet);
181
+ strip.remove();
182
+ },
183
+ };
184
+ }
@@ -0,0 +1,2 @@
1
+ export type PdfSource = Blob | Uint8Array | string | URL;
2
+ export declare function readPdf(source: PdfSource, maximum: number, signal: AbortSignal): Promise<Blob>;
@@ -0,0 +1,51 @@
1
+ export async function readPdf(source, maximum, signal) {
2
+ function check(size) {
3
+ if (size > maximum)
4
+ throw new Error('El PDF supera el límite de bytes.');
5
+ }
6
+ if (source instanceof Blob || source instanceof Uint8Array) {
7
+ const size = source instanceof Blob ? source.size : source.byteLength;
8
+ check(size);
9
+ if (!size)
10
+ throw new Error('El PDF está vacío.');
11
+ return source instanceof Blob ? source : new Blob([new Uint8Array(source)]);
12
+ }
13
+ const url = new URL(source, document.baseURI);
14
+ if (!['http:', 'https:', 'blob:'].includes(url.protocol))
15
+ throw new Error('URL de PDF no admitida.');
16
+ const download = new AbortController();
17
+ const cancel = () => download.abort(signal.reason);
18
+ signal.throwIfAborted();
19
+ signal.addEventListener('abort', cancel, { once: true });
20
+ const timer = setTimeout(() => download.abort(new Error('Tiempo de descarga del PDF agotado.')), 60_000);
21
+ try {
22
+ const response = await fetch(url, { signal: download.signal });
23
+ if (!response.ok || !response.body)
24
+ throw new Error(`No se pudo descargar el PDF (HTTP ${response.status}).`);
25
+ check(Number(response.headers.get('content-length')));
26
+ const reader = response.body.getReader();
27
+ const chunks = [];
28
+ let count = 0;
29
+ try {
30
+ for (;;) {
31
+ const { value, done } = await reader.read();
32
+ if (done)
33
+ break;
34
+ count += value.byteLength;
35
+ check(count);
36
+ chunks.push(new Uint8Array(value));
37
+ }
38
+ }
39
+ finally {
40
+ reader.releaseLock();
41
+ }
42
+ if (!count)
43
+ throw new Error('El PDF está vacío.');
44
+ return new Blob(chunks, { type: 'application/pdf' });
45
+ }
46
+ finally {
47
+ clearTimeout(timer);
48
+ download.abort();
49
+ signal.removeEventListener('abort', cancel);
50
+ }
51
+ }
@@ -0,0 +1,2 @@
1
+ export { PdfViewer, type PdfViewerProps, type PdfViewerOptions } from './PdfViewer.js';
2
+ export type { PdfSource } from './document.js';
@@ -0,0 +1 @@
1
+ export { PdfViewer } from './PdfViewer.js';
@@ -0,0 +1,84 @@
1
+ .krpdf {
2
+ --krpdf-surface: #fff;
3
+ --krpdf-border: #a9b7ca;
4
+ --krpdf-text: #202b42;
5
+ --krpdf-backdrop: #e4ebf4;
6
+ border: 1px solid var(--krpdf-border);
7
+ border-radius: 0.65rem;
8
+ overflow: hidden;
9
+ min-width: 0;
10
+ color: var(--krpdf-text);
11
+ background: var(--krpdf-surface);
12
+ }
13
+
14
+ .krpdf-controls,
15
+ .krpdf-controls form,
16
+ .krpdf-controls [role='group'] {
17
+ display: flex;
18
+ align-items: center;
19
+ gap: 0.35rem;
20
+ }
21
+ .krpdf-controls {
22
+ flex-wrap: wrap;
23
+ padding: 0.55rem 0.7rem;
24
+ column-gap: 0.85rem;
25
+ }
26
+ .krpdf-controls button,
27
+ .krpdf-controls input {
28
+ font: inherit;
29
+ color: inherit;
30
+ border: 1px solid var(--krpdf-border);
31
+ border-radius: 0.35rem;
32
+ background: var(--krpdf-surface);
33
+ min-height: 2.1rem;
34
+ padding: 0.2rem 0.4rem;
35
+ }
36
+ .krpdf-controls button {
37
+ min-width: 2.1rem;
38
+ cursor: pointer;
39
+ }
40
+ .krpdf-controls button:disabled {
41
+ opacity: 0.5;
42
+ cursor: default;
43
+ }
44
+ .krpdf-controls input {
45
+ width: 3.4rem;
46
+ }
47
+ .krpdf-message {
48
+ padding: 0.45rem 0.7rem;
49
+ margin: 0;
50
+ }
51
+ .krpdf-viewport {
52
+ position: relative;
53
+ overflow: auto;
54
+ height: min(65vh, 46rem);
55
+ background: var(--krpdf-backdrop);
56
+ }
57
+ .krpdf-strip {
58
+ position: relative;
59
+ box-sizing: border-box;
60
+ width: max-content;
61
+ min-width: 100%;
62
+ display: flex;
63
+ flex-direction: column;
64
+ align-items: center;
65
+ gap: 0.8rem;
66
+ padding: 0.8rem;
67
+ }
68
+ .krpdf-sheet {
69
+ position: relative;
70
+ background: #fff;
71
+ flex: none;
72
+ box-shadow: 0 1px 8px #23365435;
73
+ }
74
+ .krpdf-sheet canvas {
75
+ position: absolute;
76
+ inset: 0;
77
+ display: block;
78
+ width: 100%;
79
+ height: 100%;
80
+ }
81
+ .krpdf-settings { margin-inline-start: auto; }
82
+ .krpdf-settings summary { cursor: pointer; padding: .4rem; }
83
+ .krpdf-settings label { display: flex; align-items: center; gap: .5rem; padding: .4rem; }
84
+ .krpdf-settings select { font: inherit; color: inherit; background: var(--krpdf-surface); }