Expose API
- Vorherrschende Sprache
- TypeScript
- Sterne
- 395
- Forks
- 39
- Ø Merge
- 7 Std. 7 Min.
- Gemergte PRs (30 T.)
- 12
Beschreibung
First of all, thank you for open-sourcing the package! A greater alternative to react-pdf-viewer, and even apryse or nutrient.
I’d like to request a better way to expose and interact with the internal Viewer APIs **outside of the `` component context**.
Right now, I need to manually wire up imperative handles with forwardRef and useImperativeHandle to make the usePdf values and methods (like zoom, currentPage, zoomFitWidth, etc.) accessible from outside. Here’s an example of the current workaround I’m using:
```tsx
import { GlobalWorkerOptions } from "pdfjs-dist";
import {
Root,
Pages,
Page,
CanvasLayer,
TextLayer,
usePdf,
} from "@anaralabs/lector";
import "pdfjs-dist/web/pdf_viewer.css";
import {
CSSProperties,
forwardRef,
useImperativeHandle,
ForwardedRef,
} from "react";
import ZoomPanel from "./components/ZoomPanel";
// Configure PDF.js worker
GlobalWorkerOptions.workerSrc = new URL(
"pdfjs-dist/build/pdf.worker.mjs",
import.meta.url
).toString();
// Define the ref interface for the exposed API
export interface LectorRef {
currentPage: number;
zoom: number;
setZoom: (zoom: number | ((prev: number) => number)) => void;
zoomFitWidth: () => void;
}
type Props = {
docUrl: string;
style?: CSSProperties;
};
// Inner component that uses usePdf and exposes the API
interface LectorViewerInnerProps {
style: CSSProperties;
forwardedRef: ForwardedRef;
}
const LectorViewerInner = ({ style, forwardedRef }: LectorViewerInnerProps) => {
// Now safe to use usePdf because this is a child of Root
const pdfStore = usePdf((store) => ({
currentPage: store.currentPage,
zoom: store.zoom,
setZoom: store.updateZoom,
zoomFitWidth: store.zoomFitWidth,
}));
// Expose the API through the ref
useImperativeHandle(forwardedRef, () => ({
currentPage: pdfStore.currentPage,
zoom: pdfStore.zoom,
setZoom: pdfStore.setZoom,
zoomFitWidth: pdfStore.zoomFitWidth,
}));
return (
<>
);
};
// Main component
const LectorViewer = forwardRef(({ docUrl, style }, ref) => {
return (
Loading...}
style={{ height: "100%", width: "100%", position: "relative", ...style }}
>
);
});
export default LectorViewer;
```
Is there a better way to implement that?
Thanks again for the amazing work!
Beitragsleitfaden
Bewertung
Dieses Issue wurde noch nicht bewertet.