@pdf-viewer/react
Version:
The PDF Viewer component for React and Next.js
65 lines (64 loc) • 2.26 kB
JavaScript
import { useState as a, useRef as N, useEffect as C } from "react";
import * as S from "pdfjs-dist";
import { getThumbnailViewport as U } from "../getThumbnailViewport.js";
import { useConfigContext as V } from "../../contexts/ConfigContext.js";
import { useDocumentPasswordContext as j } from "../../contexts/DocumentPasswordContext.js";
const z = (l, o, I = {}) => {
const [r, q] = a(), { workerUrlAdded: k } = V(), [y, x] = a(/* @__PURE__ */ new Map()), i = N(), [R, f] = a(0), [m, L] = a(!1), { password: d, passwordError: T, setPasswordError: g, passwordRequired: P, setPasswordRequired: c } = j(), { onLoadError: p, onLoaded: w } = I;
return C(() => {
if (!k || !l)
return;
f(0), i.current = Date.now();
const t = i.current, E = {
url: l,
cMapPacked: (o == null ? void 0 : o.isCompressed) ?? !0,
...(o == null ? void 0 : o.url) && { cMapUrl: o.url },
...d && { password: d }
}, n = S.getDocument(E);
n.onProgress = (s) => {
if (t === i.current) {
const { loaded: b, total: u } = s, D = u ? Math.min(100, Math.round(b / u * 100)) : 0;
f(D);
}
}, L(!0);
const e = n.promise.then((s) => (t === i.current && (q(s), f(100)), w && w(s), c(!1), g(""), s)).catch((s) => {
s instanceof Error && s.name === "PasswordException" ? (c(!0), g(s.message || "Password required")) : s instanceof Error && s.name === "InvalidPDFException" && d ? (c(!0), g("Incorrect password")) : p && p(s);
}).finally(() => {
L(!1);
});
return () => {
e.finally(() => {
n.destroy();
});
};
}, [l, k, d, p, w]), C(() => {
if (P)
return;
const t = /* @__PURE__ */ new Map();
if (!r || m) {
x(t);
return;
}
const E = r.numPages, n = [];
for (let e = 1; e <= E; e++) {
const s = r.getPage(e);
n.push(s);
}
Promise.all(n).then((e) => {
e.map((s) => {
const { thumbnailViewport: b, scale: u } = U(s);
t.set(s.pageNumber, { page: s, thumbnailViewport: b, thumbnailScale: u });
}), x(t);
});
}, [r, m, P]), {
pdf: r,
pages: y,
loading: m,
loadingProgress: R,
passwordRequired: P,
passwordError: T
};
};
export {
z as useLoadPdf
};