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