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