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