Latest repo

This commit is contained in:
Marc
2025-06-02 16:42:16 +00:00
parent 53ddf1a329
commit cde5fae175
27907 changed files with 3875388 additions and 1 deletions

21
node_modules/react-pdf/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 20172024 Wojciech Maj
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

642
node_modules/react-pdf/README.md generated vendored Normal file
View File

@@ -0,0 +1,642 @@
[![npm](https://img.shields.io/npm/v/react-pdf.svg)](https://www.npmjs.com/package/react-pdf) ![downloads](https://img.shields.io/npm/dt/react-pdf.svg) [![CI](https://github.com/wojtekmaj/react-pdf/actions/workflows/ci.yml/badge.svg)](https://github.com/wojtekmaj/react-pdf/actions)
# React-PDF
Display PDFs in your React app as easily as if they were images.
## Lost?
This package is used to _display_ existing PDFs. If you wish to _create_ PDFs using React, you may be looking for [@react-pdf/renderer](https://www.npmjs.com/package/@react-pdf/renderer).
## tl;dr
- Install by executing `npm install react-pdf` or `yarn add react-pdf`.
- Import by adding `import { Document } from 'react-pdf'`.
- Use by adding `<Document file="..." />`. `file` can be a URL, base64 content, Uint8Array, and more.
- Put `<Page />` components inside `<Document />` to render pages.
## Demo
A minimal demo page can be found in `sample` directory.
[Online demo](https://projects.wojtekmaj.pl/react-pdf/) is also available!
## Before you continue
React-PDF is under constant development. This documentation is written for React-PDF 9.x branch. If you want to see documentation for other versions of React-PDF, use dropdown on top of GitHub page to switch to an appropriate tag. Here are quick links to the newest docs from each branch:
- [v8.x](https://github.com/wojtekmaj/react-pdf/blob/v8.x/packages/react-pdf/README.md)
- [v7.x](https://github.com/wojtekmaj/react-pdf/blob/v7.x/packages/react-pdf/README.md)
- [v6.x](https://github.com/wojtekmaj/react-pdf/blob/v6.x/README.md)
- [v5.x](https://github.com/wojtekmaj/react-pdf/blob/v5.x/README.md)
- [v4.x](https://github.com/wojtekmaj/react-pdf/blob/v4.x/README.md)
- [v3.x](https://github.com/wojtekmaj/react-pdf/blob/v3.x/README.md)
- [v2.x](https://github.com/wojtekmaj/react-pdf/blob/v2.x/README.md)
- [v1.x](https://github.com/wojtekmaj/react-pdf/blob/v1.x/README.md)
## Getting started
### Compatibility
#### Browser support
React-PDF supports all modern browsers. It is tested with the latest versions of Chrome, Edge, Safari, Firefox, and Opera.
The following browsers are supported out of the box in React-PDF v9:
- Chrome ≥119
- Edge ≥119
- Safari ≥17.4
- Firefox ≥121
You may extend the list of supported browsers by providing additional polyfills (e.g. for `Array.prototype.at`, `Promise.allSettled` or `Promise.withResolvers`) and either configuring your bundler to transpile `pdfjs-dist` or using [legacy PDF.js worker](#legacy-pdfjs-worker).
If you need to support older browsers, you will need to use React-PDF v6 or earlier.
#### React
To use the latest version of React-PDF, your project needs to use React 16.8 or later.
If you use an older version of React, please refer to the table below to a find suitable React-PDF version.
| React version | Newest compatible React-PDF version |
| ------------- | ----------------------------------- |
| ≥16.8 | latest |
| ≥16.3 | 5.x |
| ≥15.5 | 4.x |
#### Preact
React-PDF may be used with Preact.
### Installation
Add React-PDF to your project by executing `npm install react-pdf` or `yarn add react-pdf`.
#### Next.js
If you use Next.js without Turbopack enabled, add the following to your `next.config.js`:
```diff
module.exports = {
+ webpack: (config) => {
+ config.resolve.alias.canvas = false;
+ return config;
+ },
}
```
If you use Next.js with Turbopack enabled, add `empty-module.ts` file:
```ts
export default {};
```
and add the following to your `next.config.js`:
```diff
module.exports = {
+ experimental: {
+ turbo: {
+ resolveAlias: {
+ canvas: './empty-module.ts',
+ },
+ },
+ },
};
```
If you use Next.js prior to v15 (v15.0.0-canary.53, specifically), you may need to add the following to your `next.config.js`:
```diff
module.exports = {
+ swcMinify: false,
}
```
### Configure PDF.js worker
For React-PDF to work, PDF.js worker needs to be provided. You have several options.
#### Import worker (recommended)
For most cases, the following example will work:
```ts
import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
'pdfjs-dist/build/pdf.worker.min.mjs',
import.meta.url,
).toString();
```
> [!NOTE]
> In Next.js:
>
> - Using App Router, make sure to add `'use client';` to the top of the file.
> - Using Pages Router, make sure to [disable SSR](https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading#with-no-ssr) when importing the component you're using this code in.
> [!NOTE]
> pnpm requires an `.npmrc` file with `public-hoist-pattern[]=pdfjs-dist` for this to work.
<details>
<summary>See more examples</summary>
##### Parcel 2
For Parcel 2, you need to use a slightly different code:
```diff
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
- 'pdfjs-dist/build/pdf.worker.min.mjs',
+ 'npm:pdfjs-dist/build/pdf.worker.min.mjs',
import.meta.url,
).toString();
```
</details>
#### Copy worker to public directory
You will have to make sure on your own that `pdf.worker.mjs` file from `pdfjs-dist/build` is copied to your project's output folder.
For example, you could use a custom script like:
```ts
import path from 'node:path';
import fs from 'node:fs';
const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
const pdfWorkerPath = path.join(pdfjsDistPath, 'build', 'pdf.worker.mjs');
fs.cpSync(pdfWorkerPath, './dist/pdf.worker.mjs', { recursive: true });
```
#### Use external CDN
```ts
import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs`;
```
#### Legacy PDF.js worker
If you need to support older browsers, you may use legacy PDF.js worker. To do so, follow the instructions above, but replace `/build/` with `legacy/build/` in PDF.js worker import path, for example:
```diff
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
- 'pdfjs-dist/build/pdf.worker.min.mjs',
+ 'pdfjs-dist/legacy/build/pdf.worker.min.mjs',
import.meta.url,
).toString();
```
or:
```diff
-pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs`;
+pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/legacy/build/pdf.worker.min.mjs`;
```
### Usage
Here's an example of basic usage:
```tsx
import { useState } from 'react';
import { Document, Page } from 'react-pdf';
function MyApp() {
const [numPages, setNumPages] = useState<number>();
const [pageNumber, setPageNumber] = useState<number>(1);
function onDocumentLoadSuccess({ numPages }: { numPages: number }): void {
setNumPages(numPages);
}
return (
<div>
<Document file="somefile.pdf" onLoadSuccess={onDocumentLoadSuccess}>
<Page pageNumber={pageNumber} />
</Document>
<p>
Page {pageNumber} of {numPages}
</p>
</div>
);
}
```
Check the [sample directory](https://github.com/wojtekmaj/react-pdf/tree/main/sample) in this repository for a full working example. For more examples and more advanced use cases, check [Recipes](https://github.com/wojtekmaj/react-pdf/wiki/Recipes) in [React-PDF Wiki](https://github.com/wojtekmaj/react-pdf/wiki/).
### Support for annotations
If you want to use annotations (e.g. links) in PDFs rendered by React-PDF, then you would need to include stylesheet necessary for annotations to be correctly displayed like so:
```ts
import 'react-pdf/dist/Page/AnnotationLayer.css';
```
### Support for text layer
If you want to use text layer in PDFs rendered by React-PDF, then you would need to include stylesheet necessary for text layer to be correctly displayed like so:
```ts
import 'react-pdf/dist/Page/TextLayer.css';
```
### Support for non-latin characters
If you want to ensure that PDFs with non-latin characters will render perfectly, or you have encountered the following warning:
```
Warning: The CMap "baseUrl" parameter must be specified, ensure that the "cMapUrl" and "cMapPacked" API parameters are provided.
```
then you would also need to include cMaps in your build and tell React-PDF where they are.
#### Copying cMaps
First, you need to copy cMaps from `pdfjs-dist` (React-PDF's dependency - it should be in your `node_modules` if you have React-PDF installed). cMaps are located in `pdfjs-dist/cmaps`.
##### Vite
Add [`vite-plugin-static-copy`](https://www.npmjs.com/package/vite-plugin-static-copy) by executing `npm install vite-plugin-static-copy --save-dev` or `yarn add vite-plugin-static-copy --dev` and add the following to your Vite config:
```diff
+import path from 'node:path';
+import { createRequire } from 'node:module';
-import { defineConfig } from 'vite';
+import { defineConfig, normalizePath } from 'vite';
+import { viteStaticCopy } from 'vite-plugin-static-copy';
+const require = createRequire(import.meta.url);
+
+const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
+const cMapsDir = normalizePath(path.join(pdfjsDistPath, 'cmaps'));
export default defineConfig({
plugins: [
+ viteStaticCopy({
+ targets: [
+ {
+ src: cMapsDir,
+ dest: '',
+ },
+ ],
+ }),
]
});
```
##### Webpack
Add [`copy-webpack-plugin`](https://www.npmjs.com/package/copy-webpack-plugin) by executing `npm install copy-webpack-plugin --save-dev` or `yarn add copy-webpack-plugin --dev` and add the following to your Webpack config:
```diff
+import path from 'node:path';
+import CopyWebpackPlugin from 'copy-webpack-plugin';
+const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
+const cMapsDir = path.join(pdfjsDistPath, 'cmaps');
module.exports = {
plugins: [
+ new CopyWebpackPlugin({
+ patterns: [
+ {
+ from: cMapsDir,
+ to: 'cmaps/'
+ },
+ ],
+ }),
],
};
```
##### Other tools
If you use other bundlers, you will have to make sure on your own that cMaps are copied to your project's output folder.
For example, you could use a custom script like:
```ts
import path from 'node:path';
import fs from 'node:fs';
const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
const cMapsDir = path.join(pdfjsDistPath, 'cmaps');
fs.cpSync(cMapsDir, 'dist/cmaps/', { recursive: true });
```
#### Setting up React-PDF
Now that you have cMaps in your build, pass required options to Document component by using `options` prop, like so:
```ts
// Outside of React component
const options = {
cMapUrl: '/cmaps/',
};
// Inside of React component
<Document options={options} />;
```
> [!NOTE]
> Make sure to define `options` object outside of your React component, and use `useMemo` if you can't.
Alternatively, you could use cMaps from external CDN:
```tsx
// Outside of React component
import { pdfjs } from 'react-pdf';
const options = {
cMapUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/cmaps/`,
};
// Inside of React component
<Document options={options} />;
```
### Support for standard fonts
If you want to support PDFs using standard fonts (deprecated in PDF 1.5, but still around), ot you have encountered the following warning:
```
The standard font "baseUrl" parameter must be specified, ensure that the "standardFontDataUrl" API parameter is provided.
```
then you would also need to include standard fonts in your build and tell React-PDF where they are.
#### Copying fonts
First, you need to copy standard fonts from `pdfjs-dist` (React-PDF's dependency - it should be in your `node_modules` if you have React-PDF installed). Standard fonts are located in `pdfjs-dist/standard_fonts`.
##### Vite
Add [`vite-plugin-static-copy`](https://www.npmjs.com/package/vite-plugin-static-copy) by executing `npm install vite-plugin-static-copy --save-dev` or `yarn add vite-plugin-static-copy --dev` and add the following to your Vite config:
```diff
+import path from 'node:path';
+import { createRequire } from 'node:module';
-import { defineConfig } from 'vite';
+import { defineConfig, normalizePath } from 'vite';
+import { viteStaticCopy } from 'vite-plugin-static-copy';
+const require = createRequire(import.meta.url);
+const standardFontsDir = normalizePath(
+ path.join(path.dirname(require.resolve('pdfjs-dist/package.json')), 'standard_fonts')
+);
export default defineConfig({
plugins: [
+ viteStaticCopy({
+ targets: [
+ {
+ src: standardFontsDir,
+ dest: '',
+ },
+ ],
+ }),
]
});
```
##### Webpack
Add [`copy-webpack-plugin`](https://www.npmjs.com/package/copy-webpack-plugin) by executing `npm install copy-webpack-plugin --save-dev` or `yarn add copy-webpack-plugin --dev` and add the following to your Webpack config:
```diff
+import path from 'node:path';
+import CopyWebpackPlugin from 'copy-webpack-plugin';
+const standardFontsDir = path.join(path.dirname(require.resolve('pdfjs-dist/package.json')), 'standard_fonts');
module.exports = {
plugins: [
+ new CopyWebpackPlugin({
+ patterns: [
+ {
+ from: standardFontsDir,
+ to: 'standard_fonts/'
+ },
+ ],
+ }),
],
};
```
##### Other tools
If you use other bundlers, you will have to make sure on your own that standard fonts are copied to your project's output folder.
For example, you could use a custom script like:
```ts
import path from 'node:path';
import fs from 'node:fs';
const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
const standardFontsDir = path.join(pdfjsDistPath, 'standard_fonts');
fs.cpSync(standardFontsDir, 'dist/standard_fonts/', { recursive: true });
```
#### Setting up React-PDF
Now that you have standard fonts in your build, pass required options to Document component by using `options` prop, like so:
```tsx
// Outside of React component
const options = {
standardFontDataUrl: '/standard_fonts/',
};
// Inside of React component
<Document options={options} />;
```
> [!NOTE]
> Make sure to define `options` object outside of your React component, and use `useMemo` if you can't.
Alternatively, you could use standard fonts from external CDN:
```tsx
// Outside of React component
import { pdfjs } from 'react-pdf';
const options = {
standardFontDataUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/standard_fonts`,
};
// Inside of React component
<Document options={options} />;
```
## User guide
### Document
Loads a document passed using `file` prop.
#### Props
| Prop name | Description | Default value | Example values |
| ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| className | Class name(s) that will be added to rendered element along with the default `react-pdf__Document`. | n/a | <ul><li>String:<br />`"custom-class-name-1 custom-class-name-2"`</li><li>Array of strings:<br />`["custom-class-name-1", "custom-class-name-2"]`</li></ul> |
| error | What the component should display in case of an error. | `"Failed to load PDF file."` | <ul><li>String:<br />`"An error occurred!"`</li><li>React element:<br />`<p>An error occurred!</p>`</li><li>Function:<br />`this.renderError`</li></ul> |
| externalLinkRel | Link rel for links rendered in annotations. | `"noopener noreferrer nofollow"` | One of valid [values for `rel` attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-rel).<ul><li>`"noopener"`</li><li>`"noreferrer"`</li><li>`"nofollow"`</li><li>`"noopener noreferrer"`</li></ul> |
| externalLinkTarget | Link target for external links rendered in annotations. | unset, which means that default behavior will be used | One of valid [values for `target` attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-target).<ul><li>`"_self"`</li><li>`"_blank"`</li><li>`"_parent"`</li><li>`"_top"`</li></ul> |
| file | What PDF should be displayed.<br />Its value can be an URL, a file (imported using `import … from …` or from file input form element), or an object with parameters (`url` - URL; `data` - data, preferably Uint8Array; `range` - PDFDataRangeTransport.<br />**Warning**: Since equality check (`===`) is used to determine if `file` object has changed, it must be memoized by setting it in component's state, `useMemo` or other similar technique. | n/a | <ul><li>URL:<br />`"https://example.com/sample.pdf"`</li><li>File:<br />`import importedPdf from '../static/sample.pdf'` and then<br />`sample`</li><li>Parameter object:<br />`{ url: 'https://example.com/sample.pdf' }`</ul> |
| imageResourcesPath | The path used to prefix the src attributes of annotation SVGs. | n/a (pdf.js will fallback to an empty string) | `"/public/images/"` |
| inputRef | A prop that behaves like [ref](https://reactjs.org/docs/refs-and-the-dom.html), but it's passed to main `<div>` rendered by `<Document>` component. | n/a | <ul><li>Function:<br />`(ref) => { this.myDocument = ref; }`</li><li>Ref created using `createRef`:<br />`this.ref = createRef();`<br />…<br />`inputRef={this.ref}`</li><li>Ref created using `useRef`:<br />`const ref = useRef();`<br />…<br />`inputRef={ref}`</li></ul> |
| loading | What the component should display while loading. | `"Loading PDF…"` | <ul><li>String:<br />`"Please wait!"`</li><li>React element:<br />`<p>Please wait!</p>`</li><li>Function:<br />`this.renderLoader`</li></ul> |
| noData | What the component should display in case of no data. | `"No PDF file specified."` | <ul><li>String:<br />`"Please select a file."`</li><li>React element:<br />`<p>Please select a file.</p>`</li><li>Function:<br />`this.renderNoData`</li></ul> |
| onItemClick | Function called when an outline item or a thumbnail has been clicked. Usually, you would like to use this callback to move the user wherever they requested to. | n/a | `({ dest, pageIndex, pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!')` |
| onLoadError | Function called in case of an error while loading a document. | n/a | `(error) => alert('Error while loading document! ' + error.message)` |
| onLoadProgress | Function called, potentially multiple times, as the loading progresses. | n/a | `({ loaded, total }) => alert('Loading a document: ' + (loaded / total) * 100 + '%')` |
| onLoadSuccess | Function called when the document is successfully loaded. | n/a | `(pdf) => alert('Loaded a file with ' + pdf.numPages + ' pages!')` |
| onPassword | Function called when a password-protected PDF is loaded. | Function that prompts the user for password. | `(callback) => callback('s3cr3t_p4ssw0rd')` |
| onSourceError | Function called in case of an error while retrieving document source from `file` prop. | n/a | `(error) => alert('Error while retrieving document source! ' + error.message)` |
| onSourceSuccess | Function called when document source is successfully retrieved from `file` prop. | n/a | `() => alert('Document source retrieved!')` |
| options | An object in which additional parameters to be passed to PDF.js can be defined. Most notably:<ul><li>`cMapUrl`;</li><li>`httpHeaders` - custom request headers, e.g. for authorization);</li><li>`withCredentials` - a boolean to indicate whether or not to include cookies in the request (defaults to `false`)</li></ul>For a full list of possible parameters, check [PDF.js documentation on DocumentInitParameters](https://mozilla.github.io/pdf.js/api/draft/module-pdfjsLib.html#~DocumentInitParameters).<br /><br />**Note**: Make sure to define options object outside of your React component, and use `useMemo` if you can't. | n/a | `{ cMapUrl: '/cmaps/' }` |
| renderMode | Rendering mode of the document. Can be `"canvas"`, `"custom"` or `"none"`. If set to `"custom"`, `customRenderer` must also be provided. | `"canvas"` | `"custom"` |
| rotate | Rotation of the document in degrees. If provided, will change rotation globally, even for the pages which were given `rotate` prop of their own. `90` = rotated to the right, `180` = upside down, `270` = rotated to the left. | n/a | `90` |
### Page
Displays a page. Should be placed inside `<Document />`. Alternatively, it can have `pdf` prop passed, which can be obtained from `<Document />`'s `onLoadSuccess` callback function, however some advanced functions like rendering annotations and linking between pages inside a document may not be working correctly.
#### Props
| Prop name | Description | Default value | Example values |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| canvasBackground | Canvas background color. Any valid `canvas.fillStyle` can be used. | n/a | `"transparent"` |
| canvasRef | A prop that behaves like [ref](https://reactjs.org/docs/refs-and-the-dom.html), but it's passed to `<canvas>` rendered by `<Canvas>` component. | n/a | <ul><li>Function:<br />`(ref) => { this.myCanvas = ref; }`</li><li>Ref created using `createRef`:<br />`this.ref = createRef();`<br />…<br />`inputRef={this.ref}`</li><li>Ref created using `useRef`:<br />`const ref = useRef();`<br />…<br />`inputRef={ref}`</li></ul> |
| className | Class name(s) that will be added to rendered element along with the default `react-pdf__Page`. | n/a | <ul><li>String:<br />`"custom-class-name-1 custom-class-name-2"`</li><li>Array of strings:<br />`["custom-class-name-1", "custom-class-name-2"]`</li></ul> |
| customRenderer | Function that customizes how a page is rendered. You must set `renderMode` to `"custom"` to use this prop. | n/a | `MyCustomRenderer` |
| customTextRenderer | Function that customizes how a text layer is rendered. | n/a | ``({ str, itemIndex }) => str.replace(/ipsum/g, value => `<mark>${value}</mark>`)`` |
| devicePixelRatio | The ratio between physical pixels and device-independent pixels (DIPs) on the current device. | `window.devicePixelRatio` | `1` |
| error | What the component should display in case of an error. | `"Failed to load the page."` | <ul><li>String:<br />`"An error occurred!"`</li><li>React element:<br />`<p>An error occurred!</p>`</li><li>Function:<br />`this.renderError`</li></ul> |
| height | Page height. If neither `height` nor `width` are defined, page will be rendered at the size defined in PDF. If you define `width` and `height` at the same time, `height` will be ignored. If you define `height` and `scale` at the same time, the height will be multiplied by a given factor. | Page's default height | `300` |
| imageResourcesPath | The path used to prefix the src attributes of annotation SVGs. | n/a (pdf.js will fallback to an empty string) | `"/public/images/"` |
| inputRef | A prop that behaves like [ref](https://reactjs.org/docs/refs-and-the-dom.html), but it's passed to main `<div>` rendered by `<Page>` component. | n/a | <ul><li>Function:<br />`(ref) => { this.myPage = ref; }`</li><li>Ref created using `createRef`:<br />`this.ref = createRef();`<br />…<br />`inputRef={this.ref}`</li><li>Ref created using `useRef`:<br />`const ref = useRef();`<br />…<br />`inputRef={ref}`</li></ul> |
| loading | What the component should display while loading. | `"Loading page…"` | <ul><li>String:<br />`"Please wait!"`</li><li>React element:<br />`<p>Please wait!</p>`</li><li>Function:<br />`this.renderLoader`</li></ul> |
| noData | What the component should display in case of no data. | `"No page specified."` | <ul><li>String:<br />`"Please select a page."`</li><li>React element:<br />`<p>Please select a page.</p>`</li><li>Function:<br />`this.renderNoData`</li></ul> |
| onGetAnnotationsError | Function called in case of an error while loading annotations. | n/a | `(error) => alert('Error while loading annotations! ' + error.message)` |
| onGetAnnotationsSuccess | Function called when annotations are successfully loaded. | n/a | `(annotations) => alert('Now displaying ' + annotations.length + ' annotations!')` |
| onGetStructTreeError | Function called in case of an error while loading structure tree. | n/a | `(error) => alert('Error while loading structure tree! ' + error.message)` |
| onGetStructTreeSuccess | Function called when structure tree is successfully loaded. | n/a | `(structTree) => alert(JSON.stringify(structTree))` |
| onGetTextError | Function called in case of an error while loading text layer items. | n/a | `(error) => alert('Error while loading text layer items! ' + error.message)` |
| onGetTextSuccess | Function called when text layer items are successfully loaded. | n/a | `({ items, styles }) => alert('Now displaying ' + items.length + ' text layer items!')` |
| onLoadError | Function called in case of an error while loading the page. | n/a | `(error) => alert('Error while loading page! ' + error.message)` |
| onLoadSuccess | Function called when the page is successfully loaded. | n/a | `(page) => alert('Now displaying a page number ' + page.pageNumber + '!')` |
| onRenderAnnotationLayerError | Function called in case of an error while rendering the annotation layer. | n/a | `(error) => alert('Error while loading annotation layer! ' + error.message)` |
| onRenderAnnotationLayerSuccess | Function called when annotations are successfully rendered on the screen. | n/a | `() => alert('Rendered the annotation layer!')` |
| onRenderError | Function called in case of an error while rendering the page. | n/a | `(error) => alert('Error while loading page! ' + error.message)` |
| onRenderSuccess | Function called when the page is successfully rendered on the screen. | n/a | `() => alert('Rendered the page!')` |
| onRenderTextLayerError | Function called in case of an error while rendering the text layer. | n/a | `(error) => alert('Error while rendering text layer! ' + error.message)` |
| onRenderTextLayerSuccess | Function called when the text layer is successfully rendered on the screen. | n/a | `() => alert('Rendered the text layer!')` |
| pageIndex | Which page from PDF file should be displayed, by page index. Ignored if `pageNumber` prop is provided. | `0` | `1` |
| pageNumber | Which page from PDF file should be displayed, by page number. If provided, `pageIndex` prop will be ignored. | `1` | `2` |
| pdf | pdf object obtained from `<Document />`'s `onLoadSuccess` callback function. | (automatically obtained from parent `<Document />`) | `pdf` |
| renderAnnotationLayer | Whether annotations (e.g. links) should be rendered. | `true` | `false` |
| renderForms | Whether forms should be rendered. `renderAnnotationLayer` prop must be set to `true`. | `false` | `true` |
| renderMode | Rendering mode of the document. Can be `"canvas"`, `"custom"` or `"none"`. If set to `"custom"`, `customRenderer` must also be provided. | `"canvas"` | `"custom"` |
| renderTextLayer | Whether a text layer should be rendered. | `true` | `false` |
| rotate | Rotation of the page in degrees. `90` = rotated to the right, `180` = upside down, `270` = rotated to the left. | Page's default setting, usually `0` | `90` |
| scale | Page scale. | `1` | `0.5` |
| width | Page width. If neither `height` nor `width` are defined, page will be rendered at the size defined in PDF. If you define `width` and `height` at the same time, `height` will be ignored. If you define `width` and `scale` at the same time, the width will be multiplied by a given factor. | Page's default width | `300` |
### Outline
Displays an outline (table of contents). Should be placed inside `<Document />`. Alternatively, it can have `pdf` prop passed, which can be obtained from `<Document />`'s `onLoadSuccess` callback function.
#### Props
| Prop name | Description | Default value | Example values |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| className | Class name(s) that will be added to rendered element along with the default `react-pdf__Outline`. | n/a | <ul><li>String:<br />`"custom-class-name-1 custom-class-name-2"`</li><li>Array of strings:<br />`["custom-class-name-1", "custom-class-name-2"]`</li></ul> |
| inputRef | A prop that behaves like [ref](https://reactjs.org/docs/refs-and-the-dom.html), but it's passed to main `<div>` rendered by `<Outline>` component. | n/a | <ul><li>Function:<br />`(ref) => { this.myOutline = ref; }`</li><li>Ref created using `createRef`:<br />`this.ref = createRef();`<br />…<br />`inputRef={this.ref}`</li><li>Ref created using `useRef`:<br />`const ref = useRef();`<br />…<br />`inputRef={ref}`</li></ul> |
| onItemClick | Function called when an outline item has been clicked. Usually, you would like to use this callback to move the user wherever they requested to. | n/a | `({ dest, pageIndex, pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!')` |
| onLoadError | Function called in case of an error while retrieving the outline. | n/a | `(error) => alert('Error while retrieving the outline! ' + error.message)` |
| onLoadSuccess | Function called when the outline is successfully retrieved. | n/a | `(outline) => alert('The outline has been successfully retrieved.')` |
### Thumbnail
Displays a thumbnail of a page. Does not render the annotation layer or the text layer. Does not register itself as a link target, so the user will not be scrolled to a Thumbnail component when clicked on an internal link (e.g. in Table of Contents). When clicked, attempts to navigate to the page clicked (similarly to a link in Outline). Should be placed inside `<Document />`. Alternatively, it can have `pdf` prop passed, which can be obtained from `<Document />`'s `onLoadSuccess` callback function.
#### Props
Props are the same as in `<Page />` component, but certain annotation layer and text layer-related props are not available:
- customTextRenderer
- onGetAnnotationsError
- onGetAnnotationsSuccess
- onGetTextError
- onGetTextSuccess
- onRenderAnnotationLayerError
- onRenderAnnotationLayerSuccess
- onRenderTextLayerError
- onRenderTextLayerSuccess
- renderAnnotationLayer
- renderForms
- renderTextLayer
On top of that, additional props are available:
| Prop name | Description | Default value | Example values |
| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| className | Class name(s) that will be added to rendered element along with the default `react-pdf__Thumbnail`. | n/a | <ul><li>String:<br />`"custom-class-name-1 custom-class-name-2"`</li><li>Array of strings:<br />`["custom-class-name-1", "custom-class-name-2"]`</li></ul> |
| onItemClick | Function called when a thumbnail has been clicked. Usually, you would like to use this callback to move the user wherever they requested to. | n/a | `({ dest, pageIndex, pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!')` |
## Useful links
- [React-PDF Wiki](https://github.com/wojtekmaj/react-pdf/wiki/)
## License
The MIT License.
## Author
<table>
<tr>
<td >
<img src="https://avatars.githubusercontent.com/u/5426427?v=4&s=128" width="64" height="64" alt="Wojciech Maj">
</td>
<td>
<a href="https://github.com/wojtekmaj">Wojciech Maj</a>
</td>
</tr>
</table>
## Thank you
This project wouldn't be possible without the awesome work of [Niklas Närhinen](https://github.com/nnarhinen) who created its original version and without Mozilla, author of [pdf.js](http://mozilla.github.io/pdf.js). Thank you!
### Sponsors
Thank you to all our sponsors! [Become a sponsor](https://opencollective.com/react-pdf-wojtekmaj#sponsor) and get your image on our README on GitHub.
<a href="https://opencollective.com/react-pdf-wojtekmaj#sponsors" target="_blank"><img src="https://opencollective.com/react-pdf-wojtekmaj/sponsors.svg?width=890"></a>
### Backers
Thank you to all our backers! [Become a backer](https://opencollective.com/react-pdf-wojtekmaj#backer) and get your image on our README on GitHub.
<a href="https://opencollective.com/react-pdf-wojtekmaj#backers" target="_blank"><img src="https://opencollective.com/react-pdf-wojtekmaj/backers.svg?width=890"></a>
### Top Contributors
Thank you to all our contributors that helped on this project!
![Top Contributors](https://opencollective.com/react-pdf/contributors.svg?width=890&button=false)

160
node_modules/react-pdf/dist/cjs/Document.d.ts generated vendored Normal file
View File

@@ -0,0 +1,160 @@
import LinkService from './LinkService.js';
import type { EventProps } from 'make-event-props';
import type { ClassName, DocumentCallback, ExternalLinkRel, ExternalLinkTarget, File, ImageResourcesPath, NodeOrRenderer, OnDocumentLoadError, OnDocumentLoadProgress, OnDocumentLoadSuccess, OnError, OnItemClickArgs, OnPasswordCallback, Options, PasswordResponse, RenderMode, ScrollPageIntoViewArgs } from './shared/types.js';
type OnItemClick = (args: OnItemClickArgs) => void;
type OnPassword = (callback: OnPasswordCallback, reason: PasswordResponse) => void;
type OnSourceError = OnError;
type OnSourceSuccess = () => void;
export type DocumentProps = {
children?: React.ReactNode;
/**
* Class name(s) that will be added to rendered element along with the default `react-pdf__Document`.
*
* @example 'custom-class-name-1 custom-class-name-2'
* @example ['custom-class-name-1', 'custom-class-name-2']
*/
className?: ClassName;
/**
* What the component should display in case of an error.
*
* @default 'Failed to load PDF file.'
* @example 'An error occurred!'
* @example <p>An error occurred!</p>
* @example {this.renderError}
*/
error?: NodeOrRenderer;
/**
* Link rel for links rendered in annotations.
*
* @default 'noopener noreferrer nofollow'
*/
externalLinkRel?: ExternalLinkRel;
/**
* Link target for external links rendered in annotations.
*/
externalLinkTarget?: ExternalLinkTarget;
/**
* What PDF should be displayed.
*
* Its value can be an URL, a file (imported using `import … from …` or from file input form element), or an object with parameters (`url` - URL; `data` - data, preferably Uint8Array; `range` - PDFDataRangeTransport.
*
* **Warning**: Since equality check (`===`) is used to determine if `file` object has changed, it must be memoized by setting it in component's state, `useMemo` or other similar technique.
*
* @example 'https://example.com/sample.pdf'
* @example importedPdf
* @example { url: 'https://example.com/sample.pdf' }
*/
file?: File;
/**
* The path used to prefix the src attributes of annotation SVGs.
*
* @default ''
* @example '/public/images/'
*/
imageResourcesPath?: ImageResourcesPath;
/**
* A prop that behaves like [ref](https://reactjs.org/docs/refs-and-the-dom.html), but it's passed to main `<div>` rendered by `<Document>` component.
*
* @example (ref) => { this.myDocument = ref; }
* @example this.ref
* @example ref
*/
inputRef?: React.Ref<HTMLDivElement | null>;
/**
* What the component should display while loading.
*
* @default 'Loading PDF…'
* @example 'Please wait!'
* @example <p>Please wait!</p>
* @example {this.renderLoader}
*/
loading?: NodeOrRenderer;
/**
* What the component should display in case of no data.
*
* @default 'No PDF file specified.'
* @example 'Please select a file.'
* @example <p>Please select a file.</p>
* @example {this.renderNoData}
*/
noData?: NodeOrRenderer;
/**
* Function called when an outline item or a thumbnail has been clicked. Usually, you would like to use this callback to move the user wherever they requested to.
*
* @example ({ dest, pageIndex, pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!')
*/
onItemClick?: OnItemClick;
/**
* Function called in case of an error while loading a document.
*
* @example (error) => alert('Error while loading document! ' + error.message)
*/
onLoadError?: OnDocumentLoadError;
/**
* Function called, potentially multiple times, as the loading progresses.
*
* @example ({ loaded, total }) => alert('Loading a document: ' + (loaded / total) * 100 + '%')
*/
onLoadProgress?: OnDocumentLoadProgress;
/**
* Function called when the document is successfully loaded.
*
* @example (pdf) => alert('Loaded a file with ' + pdf.numPages + ' pages!')
*/
onLoadSuccess?: OnDocumentLoadSuccess;
/**
* Function called when a password-protected PDF is loaded.
*
* @example (callback) => callback('s3cr3t_p4ssw0rd')
*/
onPassword?: OnPassword;
/**
* Function called in case of an error while retrieving document source from `file` prop.
*
* @example (error) => alert('Error while retrieving document source! ' + error.message)
*/
onSourceError?: OnSourceError;
/**
* Function called when document source is successfully retrieved from `file` prop.
*
* @example () => alert('Document source retrieved!')
*/
onSourceSuccess?: OnSourceSuccess;
/**
* An object in which additional parameters to be passed to PDF.js can be defined. Most notably:
* - `cMapUrl`;
* - `httpHeaders` - custom request headers, e.g. for authorization);
* - `withCredentials` - a boolean to indicate whether or not to include cookies in the request (defaults to `false`)
*
* For a full list of possible parameters, check [PDF.js documentation on DocumentInitParameters](https://mozilla.github.io/pdf.js/api/draft/module-pdfjsLib.html#~DocumentInitParameters).
*
* **Note**: Make sure to define options object outside of your React component, and use `useMemo` if you can't.
*
* @example { cMapUrl: '/cmaps/' }
*/
options?: Options;
/**
* Rendering mode of the document. Can be `"canvas"`, `"custom"` or `"none"``. If set to `"custom"`, `customRenderer` must also be provided.
*
* @default 'canvas'
* @example 'custom'
*/
renderMode?: RenderMode;
/**
* Rotation of the document in degrees. If provided, will change rotation globally, even for the pages which were given `rotate` prop of their own. `90` = rotated to the right, `180` = upside down, `270` = rotated to the left.
*
* @example 90
*/
rotate?: number | null;
} & EventProps<DocumentCallback | false | undefined>;
/**
* Loads a document passed using `file` prop.
*/
declare const Document: React.ForwardRefExoticComponent<DocumentProps & React.RefAttributes<{
linkService: React.RefObject<LinkService>;
pages: React.RefObject<HTMLDivElement[]>;
viewer: React.RefObject<{
scrollPageIntoView: (args: ScrollPageIntoViewArgs) => void;
}>;
}>>;
export default Document;

344
node_modules/react-pdf/dist/cjs/Document.js generated vendored Normal file
View File

@@ -0,0 +1,344 @@
"use strict";
'use client';
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const make_event_props_1 = __importDefault(require("make-event-props"));
const make_cancellable_promise_1 = __importDefault(require("make-cancellable-promise"));
const clsx_1 = __importDefault(require("clsx"));
const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
const warning_1 = __importDefault(require("warning"));
const dequal_1 = require("dequal");
const pdfjs = __importStar(require("pdfjs-dist"));
const DocumentContext_js_1 = __importDefault(require("./DocumentContext.js"));
const Message_js_1 = __importDefault(require("./Message.js"));
const LinkService_js_1 = __importDefault(require("./LinkService.js"));
const PasswordResponses_js_1 = __importDefault(require("./PasswordResponses.js"));
const utils_js_1 = require("./shared/utils.js");
const useResolver_js_1 = __importDefault(require("./shared/hooks/useResolver.js"));
const { PDFDataRangeTransport } = pdfjs;
const defaultOnPassword = (callback, reason) => {
switch (reason) {
case PasswordResponses_js_1.default.NEED_PASSWORD: {
const password = prompt('Enter the password to open this PDF file.');
callback(password);
break;
}
case PasswordResponses_js_1.default.INCORRECT_PASSWORD: {
const password = prompt('Invalid password. Please try again.');
callback(password);
break;
}
default:
}
};
function isParameterObject(file) {
return (typeof file === 'object' &&
file !== null &&
('data' in file || 'range' in file || 'url' in file));
}
/**
* Loads a document passed using `file` prop.
*/
const Document = (0, react_1.forwardRef)(function Document(_a, ref) {
var { children, className, error = 'Failed to load PDF file.', externalLinkRel, externalLinkTarget, file, inputRef, imageResourcesPath, loading = 'Loading PDF…', noData = 'No PDF file specified.', onItemClick, onLoadError: onLoadErrorProps, onLoadProgress, onLoadSuccess: onLoadSuccessProps, onPassword = defaultOnPassword, onSourceError: onSourceErrorProps, onSourceSuccess: onSourceSuccessProps, options, renderMode, rotate } = _a, otherProps = __rest(_a, ["children", "className", "error", "externalLinkRel", "externalLinkTarget", "file", "inputRef", "imageResourcesPath", "loading", "noData", "onItemClick", "onLoadError", "onLoadProgress", "onLoadSuccess", "onPassword", "onSourceError", "onSourceSuccess", "options", "renderMode", "rotate"]);
const [sourceState, sourceDispatch] = (0, useResolver_js_1.default)();
const { value: source, error: sourceError } = sourceState;
const [pdfState, pdfDispatch] = (0, useResolver_js_1.default)();
const { value: pdf, error: pdfError } = pdfState;
const linkService = (0, react_1.useRef)(new LinkService_js_1.default());
const pages = (0, react_1.useRef)([]);
const prevFile = (0, react_1.useRef)(undefined);
const prevOptions = (0, react_1.useRef)(undefined);
if (file && file !== prevFile.current && isParameterObject(file)) {
(0, warning_1.default)(!(0, dequal_1.dequal)(file, prevFile.current), `File prop passed to <Document /> changed, but it's equal to previous one. This might result in unnecessary reloads. Consider memoizing the value passed to "file" prop.`);
prevFile.current = file;
}
// Detect non-memoized changes in options prop
if (options && options !== prevOptions.current) {
(0, warning_1.default)(!(0, dequal_1.dequal)(options, prevOptions.current), `Options prop passed to <Document /> changed, but it's equal to previous one. This might result in unnecessary reloads. Consider memoizing the value passed to "options" prop.`);
prevOptions.current = options;
}
const viewer = (0, react_1.useRef)({
// Handling jumping to internal links target
scrollPageIntoView: (args) => {
const { dest, pageNumber, pageIndex = pageNumber - 1 } = args;
// First, check if custom handling of onItemClick was provided
if (onItemClick) {
onItemClick({ dest, pageIndex, pageNumber });
return;
}
// If not, try to look for target page within the <Document>.
const page = pages.current[pageIndex];
if (page) {
// Scroll to the page automatically
page.scrollIntoView();
return;
}
(0, warning_1.default)(false, `An internal link leading to page ${pageNumber} was clicked, but neither <Document> was provided with onItemClick nor it was able to find the page within itself. Either provide onItemClick to <Document> and handle navigating by yourself or ensure that all pages are rendered within <Document>.`);
},
});
(0, react_1.useImperativeHandle)(ref, () => ({
linkService,
pages,
viewer,
}), []);
/**
* Called when a document source is resolved correctly
*/
function onSourceSuccess() {
if (onSourceSuccessProps) {
onSourceSuccessProps();
}
}
/**
* Called when a document source failed to be resolved correctly
*/
function onSourceError() {
if (!sourceError) {
// Impossible, but TypeScript doesn't know that
return;
}
(0, warning_1.default)(false, sourceError.toString());
if (onSourceErrorProps) {
onSourceErrorProps(sourceError);
}
}
function resetSource() {
sourceDispatch({ type: 'RESET' });
}
// biome-ignore lint/correctness/useExhaustiveDependencies: See https://github.com/biomejs/biome/issues/3080
(0, react_1.useEffect)(resetSource, [file, sourceDispatch]);
const findDocumentSource = (0, react_1.useCallback)(() => __awaiter(this, void 0, void 0, function* () {
if (!file) {
return null;
}
// File is a string
if (typeof file === 'string') {
if ((0, utils_js_1.isDataURI)(file)) {
const fileByteString = (0, utils_js_1.dataURItoByteString)(file);
return { data: fileByteString };
}
(0, utils_js_1.displayCORSWarning)();
return { url: file };
}
// File is PDFDataRangeTransport
if (file instanceof PDFDataRangeTransport) {
return { range: file };
}
// File is an ArrayBuffer
if ((0, utils_js_1.isArrayBuffer)(file)) {
return { data: file };
}
/**
* The cases below are browser-only.
* If you're running on a non-browser environment, these cases will be of no use.
*/
if (utils_js_1.isBrowser) {
// File is a Blob
if ((0, utils_js_1.isBlob)(file)) {
const data = yield (0, utils_js_1.loadFromFile)(file);
return { data };
}
}
// At this point, file must be an object
(0, tiny_invariant_1.default)(typeof file === 'object', 'Invalid parameter in file, need either Uint8Array, string or a parameter object');
(0, tiny_invariant_1.default)(isParameterObject(file), 'Invalid parameter object: need either .data, .range or .url');
// File .url is a string
if ('url' in file && typeof file.url === 'string') {
if ((0, utils_js_1.isDataURI)(file.url)) {
const { url } = file, otherParams = __rest(file, ["url"]);
const fileByteString = (0, utils_js_1.dataURItoByteString)(url);
return Object.assign({ data: fileByteString }, otherParams);
}
(0, utils_js_1.displayCORSWarning)();
}
return file;
}), [file]);
(0, react_1.useEffect)(() => {
const cancellable = (0, make_cancellable_promise_1.default)(findDocumentSource());
cancellable.promise
.then((nextSource) => {
sourceDispatch({ type: 'RESOLVE', value: nextSource });
})
.catch((error) => {
sourceDispatch({ type: 'REJECT', error });
});
return () => {
(0, utils_js_1.cancelRunningTask)(cancellable);
};
}, [findDocumentSource, sourceDispatch]);
// biome-ignore lint/correctness/useExhaustiveDependencies: Ommitted callbacks so they are not called every time they change
(0, react_1.useEffect)(() => {
if (typeof source === 'undefined') {
return;
}
if (source === false) {
onSourceError();
return;
}
onSourceSuccess();
}, [source]);
/**
* Called when a document is read successfully
*/
function onLoadSuccess() {
if (!pdf) {
// Impossible, but TypeScript doesn't know that
return;
}
if (onLoadSuccessProps) {
onLoadSuccessProps(pdf);
}
pages.current = new Array(pdf.numPages);
linkService.current.setDocument(pdf);
}
/**
* Called when a document failed to read successfully
*/
function onLoadError() {
if (!pdfError) {
// Impossible, but TypeScript doesn't know that
return;
}
(0, warning_1.default)(false, pdfError.toString());
if (onLoadErrorProps) {
onLoadErrorProps(pdfError);
}
}
// biome-ignore lint/correctness/useExhaustiveDependencies: useEffect intentionally triggered on source change
(0, react_1.useEffect)(function resetDocument() {
pdfDispatch({ type: 'RESET' });
}, [pdfDispatch, source]);
// biome-ignore lint/correctness/useExhaustiveDependencies: Ommitted callbacks so they are not called every time they change
(0, react_1.useEffect)(function loadDocument() {
if (!source) {
return;
}
const documentInitParams = options
? Object.assign(Object.assign({}, source), options) : source;
const destroyable = pdfjs.getDocument(documentInitParams);
if (onLoadProgress) {
destroyable.onProgress = onLoadProgress;
}
if (onPassword) {
destroyable.onPassword = onPassword;
}
const loadingTask = destroyable;
const loadingPromise = loadingTask.promise
.then((nextPdf) => {
pdfDispatch({ type: 'RESOLVE', value: nextPdf });
})
.catch((error) => {
if (loadingTask.destroyed) {
return;
}
pdfDispatch({ type: 'REJECT', error });
});
return () => {
loadingPromise.finally(() => loadingTask.destroy());
};
}, [options, pdfDispatch, source]);
// biome-ignore lint/correctness/useExhaustiveDependencies: Ommitted callbacks so they are not called every time they change
(0, react_1.useEffect)(() => {
if (typeof pdf === 'undefined') {
return;
}
if (pdf === false) {
onLoadError();
return;
}
onLoadSuccess();
}, [pdf]);
(0, react_1.useEffect)(function setupLinkService() {
linkService.current.setViewer(viewer.current);
linkService.current.setExternalLinkRel(externalLinkRel);
linkService.current.setExternalLinkTarget(externalLinkTarget);
}, [externalLinkRel, externalLinkTarget]);
const registerPage = (0, react_1.useCallback)((pageIndex, ref) => {
pages.current[pageIndex] = ref;
}, []);
const unregisterPage = (0, react_1.useCallback)((pageIndex) => {
delete pages.current[pageIndex];
}, []);
const childContext = (0, react_1.useMemo)(() => ({
imageResourcesPath,
linkService: linkService.current,
onItemClick,
pdf,
registerPage,
renderMode,
rotate,
unregisterPage,
}), [imageResourcesPath, onItemClick, pdf, registerPage, renderMode, rotate, unregisterPage]);
const eventProps = (0, react_1.useMemo)(() => (0, make_event_props_1.default)(otherProps, () => pdf),
// biome-ignore lint/correctness/useExhaustiveDependencies: FIXME
[otherProps, pdf]);
function renderChildren() {
return (0, jsx_runtime_1.jsx)(DocumentContext_js_1.default.Provider, { value: childContext, children: children });
}
function renderContent() {
if (!file) {
return (0, jsx_runtime_1.jsx)(Message_js_1.default, { type: "no-data", children: typeof noData === 'function' ? noData() : noData });
}
if (pdf === undefined || pdf === null) {
return ((0, jsx_runtime_1.jsx)(Message_js_1.default, { type: "loading", children: typeof loading === 'function' ? loading() : loading }));
}
if (pdf === false) {
return (0, jsx_runtime_1.jsx)(Message_js_1.default, { type: "error", children: typeof error === 'function' ? error() : error });
}
return renderChildren();
}
return ((0, jsx_runtime_1.jsx)("div", Object.assign({ className: (0, clsx_1.default)('react-pdf__Document', className),
// Assertion is needed for React 18 compatibility
ref: inputRef, style: {
['--scale-factor']: '1',
} }, eventProps, { children: renderContent() })));
});
exports.default = Document;

3
node_modules/react-pdf/dist/cjs/DocumentContext.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
import type { DocumentContextType } from './shared/types.js';
declare const documentContext: React.Context<DocumentContextType>;
export default documentContext;

6
node_modules/react-pdf/dist/cjs/DocumentContext.js generated vendored Normal file
View File

@@ -0,0 +1,6 @@
"use strict";
'use client';
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = require("react");
const documentContext = (0, react_1.createContext)(null);
exports.default = documentContext;

39
node_modules/react-pdf/dist/cjs/LinkService.d.ts generated vendored Normal file
View File

@@ -0,0 +1,39 @@
import type { PDFDocumentProxy } from 'pdfjs-dist';
import type { Dest, ExternalLinkRel, ExternalLinkTarget, ScrollPageIntoViewArgs } from './shared/types.js';
import type { IPDFLinkService } from 'pdfjs-dist/types/web/interfaces.js';
type PDFViewer = {
currentPageNumber?: number;
scrollPageIntoView: (args: ScrollPageIntoViewArgs) => void;
};
export default class LinkService implements IPDFLinkService {
externalLinkEnabled: boolean;
externalLinkRel?: ExternalLinkRel;
externalLinkTarget?: ExternalLinkTarget;
isInPresentationMode: boolean;
pdfDocument?: PDFDocumentProxy | null;
pdfViewer?: PDFViewer | null;
constructor();
setDocument(pdfDocument: PDFDocumentProxy): void;
setViewer(pdfViewer: PDFViewer): void;
setExternalLinkRel(externalLinkRel?: ExternalLinkRel): void;
setExternalLinkTarget(externalLinkTarget?: ExternalLinkTarget): void;
setHistory(): void;
get pagesCount(): number;
get page(): number;
set page(value: number);
get rotation(): number;
set rotation(_value: number);
goToDestination(dest: Dest): Promise<void>;
navigateTo(dest: Dest): void;
goToPage(pageNumber: number): void;
addLinkAttributes(link: HTMLAnchorElement, url: string, newWindow: boolean): void;
getDestinationHash(): string;
getAnchorUrl(): string;
setHash(): void;
executeNamedAction(): void;
cachePageRef(): void;
isPageVisible(): boolean;
isPageCached(): boolean;
executeSetOCGState(): void;
}
export {};

151
node_modules/react-pdf/dist/cjs/LinkService.js generated vendored Normal file
View File

@@ -0,0 +1,151 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
/* Copyright 2015 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
const DEFAULT_LINK_REL = 'noopener noreferrer nofollow';
class LinkService {
constructor() {
this.externalLinkEnabled = true;
this.externalLinkRel = undefined;
this.externalLinkTarget = undefined;
this.isInPresentationMode = false;
this.pdfDocument = undefined;
this.pdfViewer = undefined;
}
setDocument(pdfDocument) {
this.pdfDocument = pdfDocument;
}
setViewer(pdfViewer) {
this.pdfViewer = pdfViewer;
}
setExternalLinkRel(externalLinkRel) {
this.externalLinkRel = externalLinkRel;
}
setExternalLinkTarget(externalLinkTarget) {
this.externalLinkTarget = externalLinkTarget;
}
setHistory() {
// Intentionally empty
}
get pagesCount() {
return this.pdfDocument ? this.pdfDocument.numPages : 0;
}
get page() {
(0, tiny_invariant_1.default)(this.pdfViewer, 'PDF viewer is not initialized.');
return this.pdfViewer.currentPageNumber || 0;
}
set page(value) {
(0, tiny_invariant_1.default)(this.pdfViewer, 'PDF viewer is not initialized.');
this.pdfViewer.currentPageNumber = value;
}
get rotation() {
return 0;
}
set rotation(_value) {
// Intentionally empty
}
goToDestination(dest) {
return new Promise((resolve) => {
(0, tiny_invariant_1.default)(this.pdfDocument, 'PDF document not loaded.');
(0, tiny_invariant_1.default)(dest, 'Destination is not specified.');
if (typeof dest === 'string') {
this.pdfDocument.getDestination(dest).then(resolve);
}
else if (Array.isArray(dest)) {
resolve(dest);
}
else {
dest.then(resolve);
}
}).then((explicitDest) => {
(0, tiny_invariant_1.default)(Array.isArray(explicitDest), `"${explicitDest}" is not a valid destination array.`);
const destRef = explicitDest[0];
new Promise((resolve) => {
(0, tiny_invariant_1.default)(this.pdfDocument, 'PDF document not loaded.');
if (destRef instanceof Object) {
this.pdfDocument
.getPageIndex(destRef)
.then((pageIndex) => {
resolve(pageIndex);
})
.catch(() => {
(0, tiny_invariant_1.default)(false, `"${destRef}" is not a valid page reference.`);
});
}
else if (typeof destRef === 'number') {
resolve(destRef);
}
else {
(0, tiny_invariant_1.default)(false, `"${destRef}" is not a valid destination reference.`);
}
}).then((pageIndex) => {
const pageNumber = pageIndex + 1;
(0, tiny_invariant_1.default)(this.pdfViewer, 'PDF viewer is not initialized.');
(0, tiny_invariant_1.default)(pageNumber >= 1 && pageNumber <= this.pagesCount, `"${pageNumber}" is not a valid page number.`);
this.pdfViewer.scrollPageIntoView({
dest: explicitDest,
pageIndex,
pageNumber,
});
});
});
}
navigateTo(dest) {
this.goToDestination(dest);
}
goToPage(pageNumber) {
const pageIndex = pageNumber - 1;
(0, tiny_invariant_1.default)(this.pdfViewer, 'PDF viewer is not initialized.');
(0, tiny_invariant_1.default)(pageNumber >= 1 && pageNumber <= this.pagesCount, `"${pageNumber}" is not a valid page number.`);
this.pdfViewer.scrollPageIntoView({
pageIndex,
pageNumber,
});
}
addLinkAttributes(link, url, newWindow) {
link.href = url;
link.rel = this.externalLinkRel || DEFAULT_LINK_REL;
link.target = newWindow ? '_blank' : this.externalLinkTarget || '';
}
getDestinationHash() {
return '#';
}
getAnchorUrl() {
return '#';
}
setHash() {
// Intentionally empty
}
executeNamedAction() {
// Intentionally empty
}
cachePageRef() {
// Intentionally empty
}
isPageVisible() {
return true;
}
isPageCached() {
return true;
}
executeSetOCGState() {
// Intentionally empty
}
}
exports.default = LinkService;

6
node_modules/react-pdf/dist/cjs/Message.d.ts generated vendored Normal file
View File

@@ -0,0 +1,6 @@
type MessageProps = {
children?: React.ReactNode;
type: 'error' | 'loading' | 'no-data';
};
export default function Message({ children, type }: MessageProps): React.ReactElement;
export {};

7
node_modules/react-pdf/dist/cjs/Message.js generated vendored Normal file
View File

@@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Message;
const jsx_runtime_1 = require("react/jsx-runtime");
function Message({ children, type }) {
return (0, jsx_runtime_1.jsx)("div", { className: `react-pdf__message react-pdf__message--${type}`, children: children });
}

47
node_modules/react-pdf/dist/cjs/Outline.d.ts generated vendored Normal file
View File

@@ -0,0 +1,47 @@
import type { PDFDocumentProxy } from 'pdfjs-dist';
import type { EventProps } from 'make-event-props';
import type { ClassName, OnItemClickArgs } from './shared/types.js';
type PDFOutline = Awaited<ReturnType<PDFDocumentProxy['getOutline']>>;
export type OutlineProps = {
/**
* Class name(s) that will be added to rendered element along with the default `react-pdf__Outline`.
*
* @example 'custom-class-name-1 custom-class-name-2'
* @example ['custom-class-name-1', 'custom-class-name-2']
*/
className?: ClassName;
/**
* A prop that behaves like [ref](https://reactjs.org/docs/refs-and-the-dom.html), but it's passed to main `<div>` rendered by `<Outline>` component.
*
* @example (ref) => { this.myOutline = ref; }
* @example this.ref
* @example ref
*/
inputRef?: React.Ref<HTMLDivElement>;
/**
* Function called when an outline item has been clicked. Usually, you would like to use this callback to move the user wherever they requested to.
*
* @example ({ dest, pageIndex, pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!')
*/
onItemClick?: (props: OnItemClickArgs) => void;
/**
* Function called in case of an error while retrieving the outline.
*
* @example (error) => alert('Error while retrieving the outline! ' + error.message)
*/
onLoadError?: (error: Error) => void;
/**
* Function called when the outline is successfully retrieved.
*
* @example (outline) => alert('The outline has been successfully retrieved.')
*/
onLoadSuccess?: (outline: PDFOutline | null) => void;
pdf?: PDFDocumentProxy | false;
} & EventProps<PDFOutline | null | false | undefined>;
/**
* Displays an outline (table of contents).
*
* Should be placed inside `<Document />`. Alternatively, it can have `pdf` prop passed, which can be obtained from `<Document />`'s `onLoadSuccess` callback function.
*/
export default function Outline(props: OutlineProps): React.ReactElement | null;
export {};

114
node_modules/react-pdf/dist/cjs/Outline.js generated vendored Normal file
View File

@@ -0,0 +1,114 @@
"use strict";
'use client';
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Outline;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const make_cancellable_promise_1 = __importDefault(require("make-cancellable-promise"));
const make_event_props_1 = __importDefault(require("make-event-props"));
const clsx_1 = __importDefault(require("clsx"));
const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
const warning_1 = __importDefault(require("warning"));
const OutlineContext_js_1 = __importDefault(require("./OutlineContext.js"));
const OutlineItem_js_1 = __importDefault(require("./OutlineItem.js"));
const utils_js_1 = require("./shared/utils.js");
const useDocumentContext_js_1 = __importDefault(require("./shared/hooks/useDocumentContext.js"));
const useResolver_js_1 = __importDefault(require("./shared/hooks/useResolver.js"));
/**
* Displays an outline (table of contents).
*
* Should be placed inside `<Document />`. Alternatively, it can have `pdf` prop passed, which can be obtained from `<Document />`'s `onLoadSuccess` callback function.
*/
function Outline(props) {
const documentContext = (0, useDocumentContext_js_1.default)();
const mergedProps = Object.assign(Object.assign({}, documentContext), props);
const { className, inputRef, onItemClick, onLoadError: onLoadErrorProps, onLoadSuccess: onLoadSuccessProps, pdf } = mergedProps, otherProps = __rest(mergedProps, ["className", "inputRef", "onItemClick", "onLoadError", "onLoadSuccess", "pdf"]);
(0, tiny_invariant_1.default)(pdf, 'Attempted to load an outline, but no document was specified. Wrap <Outline /> in a <Document /> or pass explicit `pdf` prop.');
const [outlineState, outlineDispatch] = (0, useResolver_js_1.default)();
const { value: outline, error: outlineError } = outlineState;
/**
* Called when an outline is read successfully
*/
function onLoadSuccess() {
if (typeof outline === 'undefined' || outline === false) {
return;
}
if (onLoadSuccessProps) {
onLoadSuccessProps(outline);
}
}
/**
* Called when an outline failed to read successfully
*/
function onLoadError() {
if (!outlineError) {
// Impossible, but TypeScript doesn't know that
return;
}
(0, warning_1.default)(false, outlineError.toString());
if (onLoadErrorProps) {
onLoadErrorProps(outlineError);
}
}
// biome-ignore lint/correctness/useExhaustiveDependencies: useEffect intentionally triggered on pdf change
(0, react_1.useEffect)(function resetOutline() {
outlineDispatch({ type: 'RESET' });
}, [outlineDispatch, pdf]);
(0, react_1.useEffect)(function loadOutline() {
if (!pdf) {
// Impossible, but TypeScript doesn't know that
return;
}
const cancellable = (0, make_cancellable_promise_1.default)(pdf.getOutline());
const runningTask = cancellable;
cancellable.promise
.then((nextOutline) => {
outlineDispatch({ type: 'RESOLVE', value: nextOutline });
})
.catch((error) => {
outlineDispatch({ type: 'REJECT', error });
});
return () => (0, utils_js_1.cancelRunningTask)(runningTask);
}, [outlineDispatch, pdf]);
// biome-ignore lint/correctness/useExhaustiveDependencies: Ommitted callbacks so they are not called every time they change
(0, react_1.useEffect)(() => {
if (outline === undefined) {
return;
}
if (outline === false) {
onLoadError();
return;
}
onLoadSuccess();
}, [outline]);
const childContext = (0, react_1.useMemo)(() => ({
onItemClick,
}), [onItemClick]);
const eventProps = (0, react_1.useMemo)(() => (0, make_event_props_1.default)(otherProps, () => outline),
// biome-ignore lint/correctness/useExhaustiveDependencies: FIXME
[otherProps, outline]);
if (!outline) {
return null;
}
function renderOutline() {
if (!outline) {
return null;
}
return ((0, jsx_runtime_1.jsx)("ul", { children: outline.map((item, itemIndex) => ((0, jsx_runtime_1.jsx)(OutlineItem_js_1.default, { item: item, pdf: pdf }, typeof item.dest === 'string' ? item.dest : itemIndex))) }));
}
return ((0, jsx_runtime_1.jsx)("div", Object.assign({ className: (0, clsx_1.default)('react-pdf__Outline', className), ref: inputRef }, eventProps, { children: (0, jsx_runtime_1.jsx)(OutlineContext_js_1.default.Provider, { value: childContext, children: renderOutline() }) })));
}

3
node_modules/react-pdf/dist/cjs/OutlineContext.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
import type { OutlineContextType } from './shared/types.js';
declare const outlineContext: React.Context<OutlineContextType>;
export default outlineContext;

6
node_modules/react-pdf/dist/cjs/OutlineContext.js generated vendored Normal file
View File

@@ -0,0 +1,6 @@
"use strict";
'use client';
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = require("react");
const outlineContext = (0, react_1.createContext)(null);
exports.default = outlineContext;

9
node_modules/react-pdf/dist/cjs/OutlineItem.d.ts generated vendored Normal file
View File

@@ -0,0 +1,9 @@
import type { PDFDocumentProxy } from 'pdfjs-dist';
type PDFOutline = Awaited<ReturnType<PDFDocumentProxy['getOutline']>>;
type PDFOutlineItem = PDFOutline[number];
type OutlineItemProps = {
item: PDFOutlineItem;
pdf?: PDFDocumentProxy | false;
};
export default function OutlineItem(props: OutlineItemProps): React.ReactElement;
export {};

82
node_modules/react-pdf/dist/cjs/OutlineItem.js generated vendored Normal file
View File

@@ -0,0 +1,82 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = OutlineItem;
const jsx_runtime_1 = require("react/jsx-runtime");
const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
const Ref_js_1 = __importDefault(require("./Ref.js"));
const useCachedValue_js_1 = __importDefault(require("./shared/hooks/useCachedValue.js"));
const useDocumentContext_js_1 = __importDefault(require("./shared/hooks/useDocumentContext.js"));
const useOutlineContext_js_1 = __importDefault(require("./shared/hooks/useOutlineContext.js"));
function OutlineItem(props) {
const documentContext = (0, useDocumentContext_js_1.default)();
const outlineContext = (0, useOutlineContext_js_1.default)();
(0, tiny_invariant_1.default)(outlineContext, 'Unable to find Outline context.');
const mergedProps = Object.assign(Object.assign(Object.assign({}, documentContext), outlineContext), props);
const { item, linkService, onItemClick, pdf } = mergedProps, otherProps = __rest(mergedProps, ["item", "linkService", "onItemClick", "pdf"]);
(0, tiny_invariant_1.default)(pdf, 'Attempted to load an outline, but no document was specified. Wrap <Outline /> in a <Document /> or pass explicit `pdf` prop.');
const getDestination = (0, useCachedValue_js_1.default)(() => {
if (typeof item.dest === 'string') {
return pdf.getDestination(item.dest);
}
return item.dest;
});
const getPageIndex = (0, useCachedValue_js_1.default)(() => __awaiter(this, void 0, void 0, function* () {
const destination = yield getDestination();
if (!destination) {
throw new Error('Destination not found.');
}
const [ref] = destination;
return pdf.getPageIndex(new Ref_js_1.default(ref));
}));
const getPageNumber = (0, useCachedValue_js_1.default)(() => __awaiter(this, void 0, void 0, function* () {
const pageIndex = yield getPageIndex();
return pageIndex + 1;
}));
function onClick(event) {
event.preventDefault();
(0, tiny_invariant_1.default)(onItemClick || linkService, 'Either onItemClick callback or linkService must be defined in order to navigate to an outline item.');
if (onItemClick) {
Promise.all([getDestination(), getPageIndex(), getPageNumber()]).then(([dest, pageIndex, pageNumber]) => {
onItemClick({
dest,
pageIndex,
pageNumber,
});
});
}
else if (linkService) {
linkService.goToDestination(item.dest);
}
}
function renderSubitems() {
if (!item.items || !item.items.length) {
return null;
}
const { items: subitems } = item;
return ((0, jsx_runtime_1.jsx)("ul", { children: subitems.map((subitem, subitemIndex) => ((0, jsx_runtime_1.jsx)(OutlineItem, Object.assign({ item: subitem, pdf: pdf }, otherProps), typeof subitem.dest === 'string' ? subitem.dest : subitemIndex))) }));
}
return ((0, jsx_runtime_1.jsxs)("li", { children: [(0, jsx_runtime_1.jsx)("a", { href: "#", onClick: onClick, children: item.title }), renderSubitems()] }));
}

256
node_modules/react-pdf/dist/cjs/Page.d.ts generated vendored Normal file
View File

@@ -0,0 +1,256 @@
import type { PDFDocumentProxy } from 'pdfjs-dist';
import type { EventProps } from 'make-event-props';
import type { ClassName, CustomRenderer, CustomTextRenderer, NodeOrRenderer, OnGetAnnotationsError, OnGetAnnotationsSuccess, OnGetStructTreeError, OnGetStructTreeSuccess, OnGetTextError, OnGetTextSuccess, OnPageLoadError, OnPageLoadSuccess, OnRenderAnnotationLayerError, OnRenderAnnotationLayerSuccess, OnRenderError, OnRenderSuccess, OnRenderTextLayerError, OnRenderTextLayerSuccess, PageCallback, RenderMode } from './shared/types.js';
export type PageProps = {
_className?: string;
_enableRegisterUnregisterPage?: boolean;
/**
* Canvas background color. Any valid `canvas.fillStyle` can be used.
*
* @example 'transparent'
*/
canvasBackground?: string;
/**
* A prop that behaves like [ref](https://reactjs.org/docs/refs-and-the-dom.html), but it's passed to `<canvas>` rendered by `<PageCanvas>` component.
*
* @example (ref) => { this.myCanvas = ref; }
* @example this.ref
* @example ref
*/
canvasRef?: React.Ref<HTMLCanvasElement>;
children?: React.ReactNode;
/**
* Class name(s) that will be added to rendered element along with the default `react-pdf__Page`.
*
* @example 'custom-class-name-1 custom-class-name-2'
* @example ['custom-class-name-1', 'custom-class-name-2']
*/
className?: ClassName;
/**
* Function that customizes how a page is rendered. You must set `renderMode` to `"custom"` to use this prop.
*
* @example MyCustomRenderer
*/
customRenderer?: CustomRenderer;
/**
* Function that customizes how a text layer is rendered.
*
* @example ({ str, itemIndex }) => str.replace(/ipsum/g, value => `<mark>${value}</mark>`)
*/
customTextRenderer?: CustomTextRenderer;
/**
* The ratio between physical pixels and device-independent pixels (DIPs) on the current device.
*
* @default window.devicePixelRatio
* @example 1
*/
devicePixelRatio?: number;
/**
* What the component should display in case of an error.
*
* @default 'Failed to load the page.'
* @example 'An error occurred!'
* @example <p>An error occurred!</p>
* @example this.renderError
*/
error?: NodeOrRenderer;
/**
* Page height. If neither `height` nor `width` are defined, page will be rendered at the size defined in PDF. If you define `width` and `height` at the same time, `height` will be ignored. If you define `height` and `scale` at the same time, the height will be multiplied by a given factor.
*
* @example 300
*/
height?: number;
/**
* The path used to prefix the src attributes of annotation SVGs.
*
* @default ''
* @example '/public/images/'
*/
imageResourcesPath?: string;
/**
* A prop that behaves like [ref](https://reactjs.org/docs/refs-and-the-dom.html), but it's passed to main `<div>` rendered by `<Page>` component.
*
* @example (ref) => { this.myPage = ref; }
* @example this.ref
* @example ref
*/
inputRef?: React.Ref<HTMLDivElement | null>;
/**
* What the component should display while loading.
*
* @default 'Loading page…'
* @example 'Please wait!'
* @example <p>Please wait!</p>
* @example this.renderLoader
*/
loading?: NodeOrRenderer;
/**
* What the component should display in case of no data.
*
* @default 'No page specified.'
* @example 'Please select a page.'
* @example <p>Please select a page.</p>
* @example this.renderNoData
*/
noData?: NodeOrRenderer;
/**
* Function called in case of an error while loading annotations.
*
* @example (error) => alert('Error while loading annotations! ' + error.message)
*/
onGetAnnotationsError?: OnGetAnnotationsError;
/**
* Function called when annotations are successfully loaded.
*
* @example (annotations) => alert('Now displaying ' + annotations.length + ' annotations!')
*/
onGetAnnotationsSuccess?: OnGetAnnotationsSuccess;
/**
* Function called in case of an error while loading structure tree.
*
* @example (error) => alert('Error while loading structure tree! ' + error.message)
*/
onGetStructTreeError?: OnGetStructTreeError;
/**
* Function called when structure tree is successfully loaded.
*
* @example (structTree) => alert(JSON.stringify(structTree))
*/
onGetStructTreeSuccess?: OnGetStructTreeSuccess;
/**
* Function called in case of an error while loading text layer items.
*
* @example (error) => alert('Error while loading text layer items! ' + error.message)
*/
onGetTextError?: OnGetTextError;
/**
* Function called when text layer items are successfully loaded.
*
* @example ({ items, styles }) => alert('Now displaying ' + items.length + ' text layer items!')
*/
onGetTextSuccess?: OnGetTextSuccess;
/**
* Function called in case of an error while loading the page.
*
* @example (error) => alert('Error while loading page! ' + error.message)
*/
onLoadError?: OnPageLoadError;
/**
* Function called when the page is successfully loaded.
*
* @example (page) => alert('Now displaying a page number ' + page.pageNumber + '!')
*/
onLoadSuccess?: OnPageLoadSuccess;
/**
* Function called in case of an error while rendering the annotation layer.
*
* @example (error) => alert('Error while rendering annotation layer! ' + error.message)
*/
onRenderAnnotationLayerError?: OnRenderAnnotationLayerError;
/**
* Function called when annotations are successfully rendered on the screen.
*
* @example () => alert('Rendered the annotation layer!')
*/
onRenderAnnotationLayerSuccess?: OnRenderAnnotationLayerSuccess;
/**
* Function called in case of an error while rendering the page.
*
* @example (error) => alert('Error while loading page! ' + error.message)
*/
onRenderError?: OnRenderError;
/**
* Function called when the page is successfully rendered on the screen.
*
* @example () => alert('Rendered the page!')
*/
onRenderSuccess?: OnRenderSuccess;
/**
* Function called in case of an error while rendering the text layer.
*
* @example (error) => alert('Error while rendering text layer! ' + error.message)
*/
onRenderTextLayerError?: OnRenderTextLayerError;
/**
* Function called when the text layer is successfully rendered on the screen.
*
* @example () => alert('Rendered the text layer!')
*/
onRenderTextLayerSuccess?: OnRenderTextLayerSuccess;
/**
* Which page from PDF file should be displayed, by page index. Ignored if `pageNumber` prop is provided.
*
* @default 0
* @example 1
*/
pageIndex?: number;
/**
* Which page from PDF file should be displayed, by page number. If provided, `pageIndex` prop will be ignored.
*
* @default 1
* @example 2
*/
pageNumber?: number;
/**
* pdf object obtained from `<Document />`'s `onLoadSuccess` callback function.
*
* @example pdf
*/
pdf?: PDFDocumentProxy | false;
registerPage?: undefined;
/**
* Whether annotations (e.g. links) should be rendered.
*
* @default true
* @example false
*/
renderAnnotationLayer?: boolean;
/**
* Whether forms should be rendered. `renderAnnotationLayer` prop must be set to `true`.
*
* @default false
* @example true
*/
renderForms?: boolean;
/**
* Rendering mode of the document. Can be `"canvas"`, `"custom"` or `"none"`. If set to `"custom"`, `customRenderer` must also be provided.
*
* @default 'canvas'
* @example 'custom'
*/
renderMode?: RenderMode;
/**
* Whether a text layer should be rendered.
*
* @default true
* @example false
*/
renderTextLayer?: boolean;
/**
* Rotation of the page in degrees. `90` = rotated to the right, `180` = upside down, `270` = rotated to the left.
*
* @default 0
* @example 90
*/
rotate?: number | null;
/**
* Page scale.
*
* @default 1
* @example 0.5
*/
scale?: number;
unregisterPage?: undefined;
/**
* Page width. If neither `height` nor `width` are defined, page will be rendered at the size defined in PDF. If you define `width` and `height` at the same time, `height` will be ignored. If you define `width` and `scale` at the same time, the width will be multiplied by a given factor.
*
* @example 300
*/
width?: number;
} & EventProps<PageCallback | false | undefined>;
/**
* Displays a page.
*
* Should be placed inside `<Document />`. Alternatively, it can have `pdf` prop passed, which can be obtained from `<Document />`'s `onLoadSuccess` callback function, however some advanced functions like linking between pages inside a document may not be working correctly.
*/
export default function Page(props: PageProps): React.ReactElement;

252
node_modules/react-pdf/dist/cjs/Page.js generated vendored Normal file
View File

@@ -0,0 +1,252 @@
"use strict";
'use client';
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Page;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const make_cancellable_promise_1 = __importDefault(require("make-cancellable-promise"));
const make_event_props_1 = __importDefault(require("make-event-props"));
const clsx_1 = __importDefault(require("clsx"));
const merge_refs_1 = __importDefault(require("merge-refs"));
const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
const warning_1 = __importDefault(require("warning"));
const PageContext_js_1 = __importDefault(require("./PageContext.js"));
const Message_js_1 = __importDefault(require("./Message.js"));
const Canvas_js_1 = __importDefault(require("./Page/Canvas.js"));
const TextLayer_js_1 = __importDefault(require("./Page/TextLayer.js"));
const AnnotationLayer_js_1 = __importDefault(require("./Page/AnnotationLayer.js"));
const utils_js_1 = require("./shared/utils.js");
const useDocumentContext_js_1 = __importDefault(require("./shared/hooks/useDocumentContext.js"));
const useResolver_js_1 = __importDefault(require("./shared/hooks/useResolver.js"));
const defaultScale = 1;
/**
* Displays a page.
*
* Should be placed inside `<Document />`. Alternatively, it can have `pdf` prop passed, which can be obtained from `<Document />`'s `onLoadSuccess` callback function, however some advanced functions like linking between pages inside a document may not be working correctly.
*/
function Page(props) {
const documentContext = (0, useDocumentContext_js_1.default)();
const mergedProps = Object.assign(Object.assign({}, documentContext), props);
const { _className = 'react-pdf__Page', _enableRegisterUnregisterPage = true, canvasBackground, canvasRef, children, className, customRenderer: CustomRenderer, customTextRenderer, devicePixelRatio, error = 'Failed to load the page.', height, inputRef, loading = 'Loading page…', noData = 'No page specified.', onGetAnnotationsError: onGetAnnotationsErrorProps, onGetAnnotationsSuccess: onGetAnnotationsSuccessProps, onGetStructTreeError: onGetStructTreeErrorProps, onGetStructTreeSuccess: onGetStructTreeSuccessProps, onGetTextError: onGetTextErrorProps, onGetTextSuccess: onGetTextSuccessProps, onLoadError: onLoadErrorProps, onLoadSuccess: onLoadSuccessProps, onRenderAnnotationLayerError: onRenderAnnotationLayerErrorProps, onRenderAnnotationLayerSuccess: onRenderAnnotationLayerSuccessProps, onRenderError: onRenderErrorProps, onRenderSuccess: onRenderSuccessProps, onRenderTextLayerError: onRenderTextLayerErrorProps, onRenderTextLayerSuccess: onRenderTextLayerSuccessProps, pageIndex: pageIndexProps, pageNumber: pageNumberProps, pdf, registerPage, renderAnnotationLayer: renderAnnotationLayerProps = true, renderForms = false, renderMode = 'canvas', renderTextLayer: renderTextLayerProps = true, rotate: rotateProps, scale: scaleProps = defaultScale, unregisterPage, width } = mergedProps, otherProps = __rest(mergedProps, ["_className", "_enableRegisterUnregisterPage", "canvasBackground", "canvasRef", "children", "className", "customRenderer", "customTextRenderer", "devicePixelRatio", "error", "height", "inputRef", "loading", "noData", "onGetAnnotationsError", "onGetAnnotationsSuccess", "onGetStructTreeError", "onGetStructTreeSuccess", "onGetTextError", "onGetTextSuccess", "onLoadError", "onLoadSuccess", "onRenderAnnotationLayerError", "onRenderAnnotationLayerSuccess", "onRenderError", "onRenderSuccess", "onRenderTextLayerError", "onRenderTextLayerSuccess", "pageIndex", "pageNumber", "pdf", "registerPage", "renderAnnotationLayer", "renderForms", "renderMode", "renderTextLayer", "rotate", "scale", "unregisterPage", "width"]);
const [pageState, pageDispatch] = (0, useResolver_js_1.default)();
const { value: page, error: pageError } = pageState;
const pageElement = (0, react_1.useRef)(null);
(0, tiny_invariant_1.default)(pdf, 'Attempted to load a page, but no document was specified. Wrap <Page /> in a <Document /> or pass explicit `pdf` prop.');
const pageIndex = (0, utils_js_1.isProvided)(pageNumberProps) ? pageNumberProps - 1 : (pageIndexProps !== null && pageIndexProps !== void 0 ? pageIndexProps : null);
const pageNumber = pageNumberProps !== null && pageNumberProps !== void 0 ? pageNumberProps : ((0, utils_js_1.isProvided)(pageIndexProps) ? pageIndexProps + 1 : null);
const rotate = rotateProps !== null && rotateProps !== void 0 ? rotateProps : (page ? page.rotate : null);
const scale = (0, react_1.useMemo)(() => {
if (!page) {
return null;
}
// Be default, we'll render page at 100% * scale width.
let pageScale = 1;
// Passing scale explicitly null would cause the page not to render
const scaleWithDefault = scaleProps !== null && scaleProps !== void 0 ? scaleProps : defaultScale;
// If width/height is defined, calculate the scale of the page so it could be of desired width.
if (width || height) {
const viewport = page.getViewport({ scale: 1, rotation: rotate });
if (width) {
pageScale = width / viewport.width;
}
else if (height) {
pageScale = height / viewport.height;
}
}
return scaleWithDefault * pageScale;
}, [height, page, rotate, scaleProps, width]);
// biome-ignore lint/correctness/useExhaustiveDependencies: useEffect intentionally triggered on pdf change
(0, react_1.useEffect)(function hook() {
return () => {
if (!(0, utils_js_1.isProvided)(pageIndex)) {
// Impossible, but TypeScript doesn't know that
return;
}
if (_enableRegisterUnregisterPage && unregisterPage) {
unregisterPage(pageIndex);
}
};
}, [_enableRegisterUnregisterPage, pdf, pageIndex, unregisterPage]);
/**
* Called when a page is loaded successfully
*/
function onLoadSuccess() {
if (onLoadSuccessProps) {
if (!page || !scale) {
// Impossible, but TypeScript doesn't know that
return;
}
onLoadSuccessProps((0, utils_js_1.makePageCallback)(page, scale));
}
if (_enableRegisterUnregisterPage && registerPage) {
if (!(0, utils_js_1.isProvided)(pageIndex) || !pageElement.current) {
// Impossible, but TypeScript doesn't know that
return;
}
registerPage(pageIndex, pageElement.current);
}
}
/**
* Called when a page failed to load
*/
function onLoadError() {
if (!pageError) {
// Impossible, but TypeScript doesn't know that
return;
}
(0, warning_1.default)(false, pageError.toString());
if (onLoadErrorProps) {
onLoadErrorProps(pageError);
}
}
// biome-ignore lint/correctness/useExhaustiveDependencies: useEffect intentionally triggered on pdf and pageIndex change
(0, react_1.useEffect)(function resetPage() {
pageDispatch({ type: 'RESET' });
}, [pageDispatch, pdf, pageIndex]);
(0, react_1.useEffect)(function loadPage() {
if (!pdf || !pageNumber) {
return;
}
const cancellable = (0, make_cancellable_promise_1.default)(pdf.getPage(pageNumber));
const runningTask = cancellable;
cancellable.promise
.then((nextPage) => {
pageDispatch({ type: 'RESOLVE', value: nextPage });
})
.catch((error) => {
pageDispatch({ type: 'REJECT', error });
});
return () => (0, utils_js_1.cancelRunningTask)(runningTask);
}, [pageDispatch, pdf, pageNumber]);
// biome-ignore lint/correctness/useExhaustiveDependencies: Ommitted callbacks so they are not called every time they change
(0, react_1.useEffect)(() => {
if (page === undefined) {
return;
}
if (page === false) {
onLoadError();
return;
}
onLoadSuccess();
}, [page, scale]);
const childContext = (0, react_1.useMemo)(() =>
// Technically there cannot be page without pageIndex, pageNumber, rotate and scale, but TypeScript doesn't know that
page && (0, utils_js_1.isProvided)(pageIndex) && pageNumber && (0, utils_js_1.isProvided)(rotate) && (0, utils_js_1.isProvided)(scale)
? {
_className,
canvasBackground,
customTextRenderer,
devicePixelRatio,
onGetAnnotationsError: onGetAnnotationsErrorProps,
onGetAnnotationsSuccess: onGetAnnotationsSuccessProps,
onGetStructTreeError: onGetStructTreeErrorProps,
onGetStructTreeSuccess: onGetStructTreeSuccessProps,
onGetTextError: onGetTextErrorProps,
onGetTextSuccess: onGetTextSuccessProps,
onRenderAnnotationLayerError: onRenderAnnotationLayerErrorProps,
onRenderAnnotationLayerSuccess: onRenderAnnotationLayerSuccessProps,
onRenderError: onRenderErrorProps,
onRenderSuccess: onRenderSuccessProps,
onRenderTextLayerError: onRenderTextLayerErrorProps,
onRenderTextLayerSuccess: onRenderTextLayerSuccessProps,
page,
pageIndex,
pageNumber,
renderForms,
renderTextLayer: renderTextLayerProps,
rotate,
scale,
}
: null, [
_className,
canvasBackground,
customTextRenderer,
devicePixelRatio,
onGetAnnotationsErrorProps,
onGetAnnotationsSuccessProps,
onGetStructTreeErrorProps,
onGetStructTreeSuccessProps,
onGetTextErrorProps,
onGetTextSuccessProps,
onRenderAnnotationLayerErrorProps,
onRenderAnnotationLayerSuccessProps,
onRenderErrorProps,
onRenderSuccessProps,
onRenderTextLayerErrorProps,
onRenderTextLayerSuccessProps,
page,
pageIndex,
pageNumber,
renderForms,
renderTextLayerProps,
rotate,
scale,
]);
const eventProps = (0, react_1.useMemo)(() => (0, make_event_props_1.default)(otherProps, () => page ? (scale ? (0, utils_js_1.makePageCallback)(page, scale) : undefined) : page),
// biome-ignore lint/correctness/useExhaustiveDependencies: FIXME
[otherProps, page, scale]);
const pageKey = `${pageIndex}@${scale}/${rotate}`;
function renderMainLayer() {
switch (renderMode) {
case 'custom': {
(0, tiny_invariant_1.default)(CustomRenderer, `renderMode was set to "custom", but no customRenderer was passed.`);
return (0, jsx_runtime_1.jsx)(CustomRenderer, {}, `${pageKey}_custom`);
}
case 'none':
return null;
case 'canvas':
default:
return (0, jsx_runtime_1.jsx)(Canvas_js_1.default, { canvasRef: canvasRef }, `${pageKey}_canvas`);
}
}
function renderTextLayer() {
if (!renderTextLayerProps) {
return null;
}
return (0, jsx_runtime_1.jsx)(TextLayer_js_1.default, {}, `${pageKey}_text`);
}
function renderAnnotationLayer() {
if (!renderAnnotationLayerProps) {
return null;
}
return (0, jsx_runtime_1.jsx)(AnnotationLayer_js_1.default, {}, `${pageKey}_annotations`);
}
function renderChildren() {
return ((0, jsx_runtime_1.jsxs)(PageContext_js_1.default.Provider, { value: childContext, children: [renderMainLayer(), renderTextLayer(), renderAnnotationLayer(), children] }));
}
function renderContent() {
if (!pageNumber) {
return (0, jsx_runtime_1.jsx)(Message_js_1.default, { type: "no-data", children: typeof noData === 'function' ? noData() : noData });
}
if (pdf === null || page === undefined || page === null) {
return ((0, jsx_runtime_1.jsx)(Message_js_1.default, { type: "loading", children: typeof loading === 'function' ? loading() : loading }));
}
if (pdf === false || page === false) {
return (0, jsx_runtime_1.jsx)(Message_js_1.default, { type: "error", children: typeof error === 'function' ? error() : error });
}
return renderChildren();
}
return ((0, jsx_runtime_1.jsx)("div", Object.assign({ className: (0, clsx_1.default)(_className, className), "data-page-number": pageNumber,
// Assertion is needed for React 18 compatibility
ref: (0, merge_refs_1.default)(inputRef, pageElement), style: {
['--scale-factor']: `${scale}`,
backgroundColor: canvasBackground || 'white',
position: 'relative',
minWidth: 'min-content',
minHeight: 'min-content',
} }, eventProps, { children: renderContent() })));
}

View File

@@ -0,0 +1,333 @@
/* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
:root {
--react-pdf-annotation-layer: 1;
--annotation-unfocused-field-background: url("data:image/svg+xml;charset=UTF-8,<svg width='1px' height='1px' xmlns='http://www.w3.org/2000/svg'><rect width='100%' height='100%' style='fill:rgba(0, 54, 255, 0.13);'/></svg>");
--input-focus-border-color: Highlight;
--input-focus-outline: 1px solid Canvas;
--input-unfocused-border-color: transparent;
--input-disabled-border-color: transparent;
--input-hover-border-color: black;
--link-outline: none;
}
@media screen and (forced-colors: active) {
:root {
--input-focus-border-color: CanvasText;
--input-unfocused-border-color: ActiveText;
--input-disabled-border-color: GrayText;
--input-hover-border-color: Highlight;
--link-outline: 1.5px solid LinkText;
}
.annotationLayer .textWidgetAnnotation :is(input, textarea):required,
.annotationLayer .choiceWidgetAnnotation select:required,
.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input:required {
outline: 1.5px solid selectedItem;
}
.annotationLayer .linkAnnotation:hover {
backdrop-filter: invert(100%);
}
}
.annotationLayer {
position: absolute;
top: 0;
left: 0;
pointer-events: none;
transform-origin: 0 0;
z-index: 3;
}
.annotationLayer[data-main-rotation='90'] .norotate {
transform: rotate(270deg) translateX(-100%);
}
.annotationLayer[data-main-rotation='180'] .norotate {
transform: rotate(180deg) translate(-100%, -100%);
}
.annotationLayer[data-main-rotation='270'] .norotate {
transform: rotate(90deg) translateY(-100%);
}
.annotationLayer canvas {
position: absolute;
width: 100%;
height: 100%;
}
.annotationLayer section {
position: absolute;
text-align: initial;
pointer-events: auto;
box-sizing: border-box;
margin: 0;
transform-origin: 0 0;
}
.annotationLayer .linkAnnotation {
outline: var(--link-outline);
}
.textLayer.selecting ~ .annotationLayer section {
pointer-events: none;
}
.annotationLayer :is(.linkAnnotation, .buttonWidgetAnnotation.pushButton) > a {
position: absolute;
font-size: 1em;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.annotationLayer :is(.linkAnnotation, .buttonWidgetAnnotation.pushButton) > a:hover {
opacity: 0.2;
background: rgba(255, 255, 0, 1);
box-shadow: 0 2px 10px rgba(255, 255, 0, 1);
}
.annotationLayer .textAnnotation img {
position: absolute;
cursor: pointer;
width: 100%;
height: 100%;
top: 0;
left: 0;
}
.annotationLayer .textWidgetAnnotation :is(input, textarea),
.annotationLayer .choiceWidgetAnnotation select,
.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input {
background-image: var(--annotation-unfocused-field-background);
border: 2px solid var(--input-unfocused-border-color);
box-sizing: border-box;
font: calc(9px * var(--scale-factor)) sans-serif;
height: 100%;
margin: 0;
vertical-align: top;
width: 100%;
}
.annotationLayer .textWidgetAnnotation :is(input, textarea):required,
.annotationLayer .choiceWidgetAnnotation select:required,
.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input:required {
outline: 1.5px solid red;
}
.annotationLayer .choiceWidgetAnnotation select option {
padding: 0;
}
.annotationLayer .buttonWidgetAnnotation.radioButton input {
border-radius: 50%;
}
.annotationLayer .textWidgetAnnotation textarea {
resize: none;
}
.annotationLayer .textWidgetAnnotation :is(input, textarea)[disabled],
.annotationLayer .choiceWidgetAnnotation select[disabled],
.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input[disabled] {
background: none;
border: 2px solid var(--input-disabled-border-color);
cursor: not-allowed;
}
.annotationLayer .textWidgetAnnotation :is(input, textarea):hover,
.annotationLayer .choiceWidgetAnnotation select:hover,
.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input:hover {
border: 2px solid var(--input-hover-border-color);
}
.annotationLayer .textWidgetAnnotation :is(input, textarea):hover,
.annotationLayer .choiceWidgetAnnotation select:hover,
.annotationLayer .buttonWidgetAnnotation.checkBox input:hover {
border-radius: 2px;
}
.annotationLayer .textWidgetAnnotation :is(input, textarea):focus,
.annotationLayer .choiceWidgetAnnotation select:focus {
background: none;
border: 2px solid var(--input-focus-border-color);
border-radius: 2px;
outline: var(--input-focus-outline);
}
.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) :focus {
background-image: none;
background-color: transparent;
}
.annotationLayer .buttonWidgetAnnotation.checkBox :focus {
border: 2px solid var(--input-focus-border-color);
border-radius: 2px;
outline: var(--input-focus-outline);
}
.annotationLayer .buttonWidgetAnnotation.radioButton :focus {
border: 2px solid var(--input-focus-border-color);
outline: var(--input-focus-outline);
}
.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before,
.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after,
.annotationLayer .buttonWidgetAnnotation.radioButton input:checked::before {
background-color: CanvasText;
content: '';
display: block;
position: absolute;
}
.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before,
.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after {
height: 80%;
left: 45%;
width: 1px;
}
.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before {
transform: rotate(45deg);
}
.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after {
transform: rotate(-45deg);
}
.annotationLayer .buttonWidgetAnnotation.radioButton input:checked::before {
border-radius: 50%;
height: 50%;
left: 30%;
top: 20%;
width: 50%;
}
.annotationLayer .textWidgetAnnotation input.comb {
font-family: monospace;
padding-left: 2px;
padding-right: 0;
}
.annotationLayer .textWidgetAnnotation input.comb:focus {
/*
* Letter spacing is placed on the right side of each character. Hence, the
* letter spacing of the last character may be placed outside the visible
* area, causing horizontal scrolling. We avoid this by extending the width
* when the element has focus and revert this when it loses focus.
*/
width: 103%;
}
.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input {
appearance: none;
}
.annotationLayer .popupTriggerArea {
height: 100%;
width: 100%;
}
.annotationLayer .fileAttachmentAnnotation .popupTriggerArea {
position: absolute;
}
.annotationLayer .popupWrapper {
position: absolute;
font-size: calc(9px * var(--scale-factor));
width: 100%;
min-width: calc(180px * var(--scale-factor));
pointer-events: none;
}
.annotationLayer .popup {
position: absolute;
max-width: calc(180px * var(--scale-factor));
background-color: rgba(255, 255, 153, 1);
box-shadow: 0 calc(2px * var(--scale-factor)) calc(5px * var(--scale-factor))
rgba(136, 136, 136, 1);
border-radius: calc(2px * var(--scale-factor));
padding: calc(6px * var(--scale-factor));
margin-left: calc(5px * var(--scale-factor));
cursor: pointer;
font: message-box;
white-space: normal;
word-wrap: break-word;
pointer-events: auto;
}
.annotationLayer .popup > * {
font-size: calc(9px * var(--scale-factor));
}
.annotationLayer .popup h1 {
display: inline-block;
}
.annotationLayer .popupDate {
display: inline-block;
margin-left: calc(5px * var(--scale-factor));
}
.annotationLayer .popupContent {
border-top: 1px solid rgba(51, 51, 51, 1);
margin-top: calc(2px * var(--scale-factor));
padding-top: calc(2px * var(--scale-factor));
}
.annotationLayer .richText > * {
white-space: pre-wrap;
font-size: calc(9px * var(--scale-factor));
}
.annotationLayer .highlightAnnotation,
.annotationLayer .underlineAnnotation,
.annotationLayer .squigglyAnnotation,
.annotationLayer .strikeoutAnnotation,
.annotationLayer .freeTextAnnotation,
.annotationLayer .lineAnnotation svg line,
.annotationLayer .squareAnnotation svg rect,
.annotationLayer .circleAnnotation svg ellipse,
.annotationLayer .polylineAnnotation svg polyline,
.annotationLayer .polygonAnnotation svg polygon,
.annotationLayer .caretAnnotation,
.annotationLayer .inkAnnotation svg polyline,
.annotationLayer .stampAnnotation,
.annotationLayer .fileAttachmentAnnotation {
cursor: pointer;
}
.annotationLayer section svg {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
}
.annotationLayer .annotationTextContent {
position: absolute;
width: 100%;
height: 100%;
opacity: 0;
color: transparent;
user-select: none;
pointer-events: none;
}
.annotationLayer .annotationTextContent span {
width: 100%;
display: inline-block;
}

View File

@@ -0,0 +1 @@
export default function AnnotationLayer(): React.ReactElement;

162
node_modules/react-pdf/dist/cjs/Page/AnnotationLayer.js generated vendored Normal file
View File

@@ -0,0 +1,162 @@
"use strict";
'use client';
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = AnnotationLayer;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const make_cancellable_promise_1 = __importDefault(require("make-cancellable-promise"));
const clsx_1 = __importDefault(require("clsx"));
const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
const warning_1 = __importDefault(require("warning"));
const pdfjs = __importStar(require("pdfjs-dist"));
const useDocumentContext_js_1 = __importDefault(require("../shared/hooks/useDocumentContext.js"));
const usePageContext_js_1 = __importDefault(require("../shared/hooks/usePageContext.js"));
const useResolver_js_1 = __importDefault(require("../shared/hooks/useResolver.js"));
const utils_js_1 = require("../shared/utils.js");
function AnnotationLayer() {
const documentContext = (0, useDocumentContext_js_1.default)();
const pageContext = (0, usePageContext_js_1.default)();
(0, tiny_invariant_1.default)(pageContext, 'Unable to find Page context.');
const mergedProps = Object.assign(Object.assign({}, documentContext), pageContext);
const { imageResourcesPath, linkService, onGetAnnotationsError: onGetAnnotationsErrorProps, onGetAnnotationsSuccess: onGetAnnotationsSuccessProps, onRenderAnnotationLayerError: onRenderAnnotationLayerErrorProps, onRenderAnnotationLayerSuccess: onRenderAnnotationLayerSuccessProps, page, pdf, renderForms, rotate, scale = 1, } = mergedProps;
(0, tiny_invariant_1.default)(pdf, 'Attempted to load page annotations, but no document was specified. Wrap <Page /> in a <Document /> or pass explicit `pdf` prop.');
(0, tiny_invariant_1.default)(page, 'Attempted to load page annotations, but no page was specified.');
(0, tiny_invariant_1.default)(linkService, 'Attempted to load page annotations, but no linkService was specified.');
const [annotationsState, annotationsDispatch] = (0, useResolver_js_1.default)();
const { value: annotations, error: annotationsError } = annotationsState;
const layerElement = (0, react_1.useRef)(null);
(0, warning_1.default)(Number.parseInt(window.getComputedStyle(document.body).getPropertyValue('--react-pdf-annotation-layer'), 10) === 1, 'AnnotationLayer styles not found. Read more: https://github.com/wojtekmaj/react-pdf#support-for-annotations');
function onLoadSuccess() {
if (!annotations) {
// Impossible, but TypeScript doesn't know that
return;
}
if (onGetAnnotationsSuccessProps) {
onGetAnnotationsSuccessProps(annotations);
}
}
function onLoadError() {
if (!annotationsError) {
// Impossible, but TypeScript doesn't know that
return;
}
(0, warning_1.default)(false, annotationsError.toString());
if (onGetAnnotationsErrorProps) {
onGetAnnotationsErrorProps(annotationsError);
}
}
// biome-ignore lint/correctness/useExhaustiveDependencies: useEffect intentionally triggered on page change
(0, react_1.useEffect)(function resetAnnotations() {
annotationsDispatch({ type: 'RESET' });
}, [annotationsDispatch, page]);
(0, react_1.useEffect)(function loadAnnotations() {
if (!page) {
return;
}
const cancellable = (0, make_cancellable_promise_1.default)(page.getAnnotations());
const runningTask = cancellable;
cancellable.promise
.then((nextAnnotations) => {
annotationsDispatch({ type: 'RESOLVE', value: nextAnnotations });
})
.catch((error) => {
annotationsDispatch({ type: 'REJECT', error });
});
return () => {
(0, utils_js_1.cancelRunningTask)(runningTask);
};
}, [annotationsDispatch, page]);
// biome-ignore lint/correctness/useExhaustiveDependencies: Ommitted callbacks so they are not called every time they change
(0, react_1.useEffect)(() => {
if (annotations === undefined) {
return;
}
if (annotations === false) {
onLoadError();
return;
}
onLoadSuccess();
}, [annotations]);
function onRenderSuccess() {
if (onRenderAnnotationLayerSuccessProps) {
onRenderAnnotationLayerSuccessProps();
}
}
function onRenderError(error) {
(0, warning_1.default)(false, `${error}`);
if (onRenderAnnotationLayerErrorProps) {
onRenderAnnotationLayerErrorProps(error);
}
}
const viewport = (0, react_1.useMemo)(() => page.getViewport({ scale, rotation: rotate }), [page, rotate, scale]);
// biome-ignore lint/correctness/useExhaustiveDependencies: Ommitted callbacks so they are not called every time they change
(0, react_1.useEffect)(function renderAnnotationLayer() {
if (!pdf || !page || !linkService || !annotations) {
return;
}
const { current: layer } = layerElement;
if (!layer) {
return;
}
const clonedViewport = viewport.clone({ dontFlip: true });
const annotationLayerParameters = {
accessibilityManager: null, // TODO: Implement this
annotationCanvasMap: null, // TODO: Implement this
annotationEditorUIManager: null, // TODO: Implement this
div: layer,
l10n: null, // TODO: Implement this
page,
structTreeLayer: null, // TODO: Implement this
viewport: clonedViewport,
};
const renderParameters = {
annotations,
annotationStorage: pdf.annotationStorage,
div: layer,
imageResourcesPath,
linkService,
page,
renderForms,
viewport: clonedViewport,
};
layer.innerHTML = '';
try {
new pdfjs.AnnotationLayer(annotationLayerParameters).render(renderParameters);
// Intentional immediate callback
onRenderSuccess();
}
catch (error) {
onRenderError(error);
}
return () => {
// TODO: Cancel running task?
};
}, [annotations, imageResourcesPath, linkService, page, pdf, renderForms, viewport]);
return ((0, jsx_runtime_1.jsx)("div", { className: (0, clsx_1.default)('react-pdf__Page__annotations', 'annotationLayer'), ref: layerElement }));
}

5
node_modules/react-pdf/dist/cjs/Page/Canvas.d.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
type CanvasProps = {
canvasRef?: React.Ref<HTMLCanvasElement>;
};
export default function Canvas(props: CanvasProps): React.ReactElement;
export {};

125
node_modules/react-pdf/dist/cjs/Page/Canvas.js generated vendored Normal file
View File

@@ -0,0 +1,125 @@
"use strict";
'use client';
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Canvas;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const merge_refs_1 = __importDefault(require("merge-refs"));
const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
const warning_1 = __importDefault(require("warning"));
const pdfjs = __importStar(require("pdfjs-dist"));
const StructTree_js_1 = __importDefault(require("../StructTree.js"));
const usePageContext_js_1 = __importDefault(require("../shared/hooks/usePageContext.js"));
const utils_js_1 = require("../shared/utils.js");
const ANNOTATION_MODE = pdfjs.AnnotationMode;
function Canvas(props) {
const pageContext = (0, usePageContext_js_1.default)();
(0, tiny_invariant_1.default)(pageContext, 'Unable to find Page context.');
const mergedProps = Object.assign(Object.assign({}, pageContext), props);
const { _className, canvasBackground, devicePixelRatio = (0, utils_js_1.getDevicePixelRatio)(), onRenderError: onRenderErrorProps, onRenderSuccess: onRenderSuccessProps, page, renderForms, renderTextLayer, rotate, scale, } = mergedProps;
const { canvasRef } = props;
(0, tiny_invariant_1.default)(page, 'Attempted to render page canvas, but no page was specified.');
const canvasElement = (0, react_1.useRef)(null);
/**
* Called when a page is rendered successfully.
*/
function onRenderSuccess() {
if (!page) {
// Impossible, but TypeScript doesn't know that
return;
}
if (onRenderSuccessProps) {
onRenderSuccessProps((0, utils_js_1.makePageCallback)(page, scale));
}
}
/**
* Called when a page fails to render.
*/
function onRenderError(error) {
if ((0, utils_js_1.isCancelException)(error)) {
return;
}
(0, warning_1.default)(false, error.toString());
if (onRenderErrorProps) {
onRenderErrorProps(error);
}
}
const renderViewport = (0, react_1.useMemo)(() => page.getViewport({ scale: scale * devicePixelRatio, rotation: rotate }), [devicePixelRatio, page, rotate, scale]);
const viewport = (0, react_1.useMemo)(() => page.getViewport({ scale, rotation: rotate }), [page, rotate, scale]);
// biome-ignore lint/correctness/useExhaustiveDependencies: Ommitted callbacks so they are not called every time they change
(0, react_1.useEffect)(function drawPageOnCanvas() {
if (!page) {
return;
}
// Ensures the canvas will be re-rendered from scratch. Otherwise all form data will stay.
page.cleanup();
const { current: canvas } = canvasElement;
if (!canvas) {
return;
}
canvas.width = renderViewport.width;
canvas.height = renderViewport.height;
canvas.style.width = `${Math.floor(viewport.width)}px`;
canvas.style.height = `${Math.floor(viewport.height)}px`;
canvas.style.visibility = 'hidden';
const renderContext = {
annotationMode: renderForms ? ANNOTATION_MODE.ENABLE_FORMS : ANNOTATION_MODE.ENABLE,
canvasContext: canvas.getContext('2d', { alpha: false }),
viewport: renderViewport,
};
if (canvasBackground) {
renderContext.background = canvasBackground;
}
const cancellable = page.render(renderContext);
const runningTask = cancellable;
cancellable.promise
.then(() => {
canvas.style.visibility = '';
onRenderSuccess();
})
.catch(onRenderError);
return () => (0, utils_js_1.cancelRunningTask)(runningTask);
}, [canvasBackground, page, renderForms, renderViewport, viewport]);
const cleanup = (0, react_1.useCallback)(() => {
const { current: canvas } = canvasElement;
/**
* Zeroing the width and height cause most browsers to release graphics
* resources immediately, which can greatly reduce memory consumption.
*/
if (canvas) {
canvas.width = 0;
canvas.height = 0;
}
}, []);
(0, react_1.useEffect)(() => cleanup, [cleanup]);
return ((0, jsx_runtime_1.jsx)("canvas", { className: `${_className}__canvas`, dir: "ltr", ref: (0, merge_refs_1.default)(canvasRef, canvasElement), style: {
display: 'block',
userSelect: 'none',
}, children: renderTextLayer ? (0, jsx_runtime_1.jsx)(StructTree_js_1.default, {}) : null }));
}

119
node_modules/react-pdf/dist/cjs/Page/TextLayer.css generated vendored Normal file
View File

@@ -0,0 +1,119 @@
/* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
:root {
--react-pdf-text-layer: 1;
--highlight-bg-color: rgba(180, 0, 170, 1);
--highlight-selected-bg-color: rgba(0, 100, 0, 1);
}
@media screen and (forced-colors: active) {
:root {
--highlight-bg-color: Highlight;
--highlight-selected-bg-color: ButtonText;
}
}
[data-main-rotation='90'] {
transform: rotate(90deg) translateY(-100%);
}
[data-main-rotation='180'] {
transform: rotate(180deg) translate(-100%, -100%);
}
[data-main-rotation='270'] {
transform: rotate(270deg) translateX(-100%);
}
.textLayer {
position: absolute;
text-align: initial;
inset: 0;
overflow: hidden;
line-height: 1;
text-size-adjust: none;
forced-color-adjust: none;
transform-origin: 0 0;
z-index: 2;
}
.textLayer :is(span, br) {
color: transparent;
position: absolute;
white-space: pre;
cursor: text;
margin: 0;
transform-origin: 0 0;
}
/* Only necessary in Google Chrome, see issue 14205, and most unfortunately
* the problem doesn't show up in "text" reference tests. */
.textLayer span.markedContent {
top: 0;
height: 0;
}
.textLayer .highlight {
margin: -1px;
padding: 1px;
background-color: var(--highlight-bg-color);
border-radius: 4px;
}
.textLayer .highlight.appended {
position: initial;
}
.textLayer .highlight.begin {
border-radius: 4px 0 0 4px;
}
.textLayer .highlight.end {
border-radius: 0 4px 4px 0;
}
.textLayer .highlight.middle {
border-radius: 0;
}
.textLayer .highlight.selected {
background-color: var(--highlight-selected-bg-color);
}
/* Avoids https://github.com/mozilla/pdf.js/issues/13840 in Chrome */
.textLayer br::selection {
background: transparent;
}
.textLayer .endOfContent {
display: block;
position: absolute;
inset: 100% 0 0;
z-index: -1;
cursor: default;
user-select: none;
}
.textLayer.selecting .endOfContent {
top: 0;
}
.hiddenCanvasElement {
position: absolute;
top: 0;
left: 0;
width: 0;
height: 0;
display: none;
}

1
node_modules/react-pdf/dist/cjs/Page/TextLayer.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export default function TextLayer(): React.ReactElement;

197
node_modules/react-pdf/dist/cjs/Page/TextLayer.js generated vendored Normal file
View File

@@ -0,0 +1,197 @@
"use strict";
'use client';
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = TextLayer;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const make_cancellable_promise_1 = __importDefault(require("make-cancellable-promise"));
const clsx_1 = __importDefault(require("clsx"));
const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
const warning_1 = __importDefault(require("warning"));
const pdfjs = __importStar(require("pdfjs-dist"));
const usePageContext_js_1 = __importDefault(require("../shared/hooks/usePageContext.js"));
const useResolver_js_1 = __importDefault(require("../shared/hooks/useResolver.js"));
const utils_js_1 = require("../shared/utils.js");
function isTextItem(item) {
return 'str' in item;
}
function TextLayer() {
const pageContext = (0, usePageContext_js_1.default)();
(0, tiny_invariant_1.default)(pageContext, 'Unable to find Page context.');
const { customTextRenderer, onGetTextError, onGetTextSuccess, onRenderTextLayerError, onRenderTextLayerSuccess, page, pageIndex, pageNumber, rotate, scale, } = pageContext;
(0, tiny_invariant_1.default)(page, 'Attempted to load page text content, but no page was specified.');
const [textContentState, textContentDispatch] = (0, useResolver_js_1.default)();
const { value: textContent, error: textContentError } = textContentState;
const layerElement = (0, react_1.useRef)(null);
(0, warning_1.default)(Number.parseInt(window.getComputedStyle(document.body).getPropertyValue('--react-pdf-text-layer'), 10) === 1, 'TextLayer styles not found. Read more: https://github.com/wojtekmaj/react-pdf#support-for-text-layer');
/**
* Called when a page text content is read successfully
*/
function onLoadSuccess() {
if (!textContent) {
// Impossible, but TypeScript doesn't know that
return;
}
if (onGetTextSuccess) {
onGetTextSuccess(textContent);
}
}
/**
* Called when a page text content failed to read successfully
*/
function onLoadError() {
if (!textContentError) {
// Impossible, but TypeScript doesn't know that
return;
}
(0, warning_1.default)(false, textContentError.toString());
if (onGetTextError) {
onGetTextError(textContentError);
}
}
// biome-ignore lint/correctness/useExhaustiveDependencies: useEffect intentionally triggered on page change
(0, react_1.useEffect)(function resetTextContent() {
textContentDispatch({ type: 'RESET' });
}, [page, textContentDispatch]);
(0, react_1.useEffect)(function loadTextContent() {
if (!page) {
return;
}
const cancellable = (0, make_cancellable_promise_1.default)(page.getTextContent());
const runningTask = cancellable;
cancellable.promise
.then((nextTextContent) => {
textContentDispatch({ type: 'RESOLVE', value: nextTextContent });
})
.catch((error) => {
textContentDispatch({ type: 'REJECT', error });
});
return () => (0, utils_js_1.cancelRunningTask)(runningTask);
}, [page, textContentDispatch]);
// biome-ignore lint/correctness/useExhaustiveDependencies: Ommitted callbacks so they are not called every time they change
(0, react_1.useEffect)(() => {
if (textContent === undefined) {
return;
}
if (textContent === false) {
onLoadError();
return;
}
onLoadSuccess();
}, [textContent]);
/**
* Called when a text layer is rendered successfully
*/
const onRenderSuccess = (0, react_1.useCallback)(() => {
if (onRenderTextLayerSuccess) {
onRenderTextLayerSuccess();
}
}, [onRenderTextLayerSuccess]);
/**
* Called when a text layer failed to render successfully
*/
const onRenderError = (0, react_1.useCallback)((error) => {
(0, warning_1.default)(false, error.toString());
if (onRenderTextLayerError) {
onRenderTextLayerError(error);
}
}, [onRenderTextLayerError]);
function onMouseDown() {
const layer = layerElement.current;
if (!layer) {
return;
}
layer.classList.add('selecting');
}
function onMouseUp() {
const layer = layerElement.current;
if (!layer) {
return;
}
layer.classList.remove('selecting');
}
const viewport = (0, react_1.useMemo)(() => page.getViewport({ scale, rotation: rotate }), [page, rotate, scale]);
(0, react_1.useLayoutEffect)(function renderTextLayer() {
if (!page || !textContent) {
return;
}
const { current: layer } = layerElement;
if (!layer) {
return;
}
layer.innerHTML = '';
const textContentSource = page.streamTextContent({ includeMarkedContent: true });
const parameters = {
container: layer,
textContentSource,
viewport,
};
const cancellable = new pdfjs.TextLayer(parameters);
const runningTask = cancellable;
cancellable
.render()
.then(() => {
const end = document.createElement('div');
end.className = 'endOfContent';
layer.append(end);
const layerChildren = layer.querySelectorAll('[role="presentation"]');
if (customTextRenderer) {
let index = 0;
textContent.items.forEach((item, itemIndex) => {
if (!isTextItem(item)) {
return;
}
const child = layerChildren[index];
if (!child) {
return;
}
const content = customTextRenderer(Object.assign({ pageIndex,
pageNumber,
itemIndex }, item));
child.innerHTML = content;
index += item.str && item.hasEOL ? 2 : 1;
});
}
// Intentional immediate callback
onRenderSuccess();
})
.catch(onRenderError);
return () => (0, utils_js_1.cancelRunningTask)(runningTask);
}, [
customTextRenderer,
onRenderError,
onRenderSuccess,
page,
pageIndex,
pageNumber,
textContent,
viewport,
]);
return ((0, jsx_runtime_1.jsx)("div", { className: (0, clsx_1.default)('react-pdf__Page__textContent', 'textLayer'), onMouseUp: onMouseUp, onMouseDown: onMouseDown, ref: layerElement }));
}

3
node_modules/react-pdf/dist/cjs/PageContext.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
import type { PageContextType } from './shared/types.js';
declare const pageContext: React.Context<PageContextType>;
export default pageContext;

6
node_modules/react-pdf/dist/cjs/PageContext.js generated vendored Normal file
View File

@@ -0,0 +1,6 @@
"use strict";
'use client';
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = require("react");
const pageContext = (0, react_1.createContext)(null);
exports.default = pageContext;

View File

@@ -0,0 +1,5 @@
declare const PasswordResponses: {
readonly NEED_PASSWORD: 1;
readonly INCORRECT_PASSWORD: 2;
};
export default PasswordResponses;

8
node_modules/react-pdf/dist/cjs/PasswordResponses.js generated vendored Normal file
View File

@@ -0,0 +1,8 @@
"use strict";
// As defined in https://github.com/mozilla/pdf.js/blob/d9fac3459609a807be6506fb3441b5da4b154d14/src/shared/util.js#L371-L374
Object.defineProperty(exports, "__esModule", { value: true });
const PasswordResponses = {
NEED_PASSWORD: 1,
INCORRECT_PASSWORD: 2,
};
exports.default = PasswordResponses;

9
node_modules/react-pdf/dist/cjs/Ref.d.ts generated vendored Normal file
View File

@@ -0,0 +1,9 @@
export default class Ref {
num: number;
gen: number;
constructor({ num, gen }: {
num: number;
gen: number;
});
toString(): string;
}

16
node_modules/react-pdf/dist/cjs/Ref.js generated vendored Normal file
View File

@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Ref {
constructor({ num, gen }) {
this.num = num;
this.gen = gen;
}
toString() {
let str = `${this.num}R`;
if (this.gen !== 0) {
str += this.gen;
}
return str;
}
}
exports.default = Ref;

1
node_modules/react-pdf/dist/cjs/StructTree.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export default function StructTree(): React.ReactElement | null;

80
node_modules/react-pdf/dist/cjs/StructTree.js generated vendored Normal file
View File

@@ -0,0 +1,80 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = StructTree;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const make_cancellable_promise_1 = __importDefault(require("make-cancellable-promise"));
const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
const warning_1 = __importDefault(require("warning"));
const StructTreeItem_js_1 = __importDefault(require("./StructTreeItem.js"));
const usePageContext_js_1 = __importDefault(require("./shared/hooks/usePageContext.js"));
const useResolver_js_1 = __importDefault(require("./shared/hooks/useResolver.js"));
const utils_js_1 = require("./shared/utils.js");
function StructTree() {
const pageContext = (0, usePageContext_js_1.default)();
(0, tiny_invariant_1.default)(pageContext, 'Unable to find Page context.');
const { onGetStructTreeError: onGetStructTreeErrorProps, onGetStructTreeSuccess: onGetStructTreeSuccessProps, } = pageContext;
const [structTreeState, structTreeDispatch] = (0, useResolver_js_1.default)();
const { value: structTree, error: structTreeError } = structTreeState;
const { customTextRenderer, page } = pageContext;
function onLoadSuccess() {
if (!structTree) {
// Impossible, but TypeScript doesn't know that
return;
}
if (onGetStructTreeSuccessProps) {
onGetStructTreeSuccessProps(structTree);
}
}
function onLoadError() {
if (!structTreeError) {
// Impossible, but TypeScript doesn't know that
return;
}
(0, warning_1.default)(false, structTreeError.toString());
if (onGetStructTreeErrorProps) {
onGetStructTreeErrorProps(structTreeError);
}
}
// biome-ignore lint/correctness/useExhaustiveDependencies: useEffect intentionally triggered on page change
(0, react_1.useEffect)(function resetStructTree() {
structTreeDispatch({ type: 'RESET' });
}, [structTreeDispatch, page]);
(0, react_1.useEffect)(function loadStructTree() {
if (customTextRenderer) {
// TODO: Document why this is necessary
return;
}
if (!page) {
return;
}
const cancellable = (0, make_cancellable_promise_1.default)(page.getStructTree());
const runningTask = cancellable;
cancellable.promise
.then((nextStructTree) => {
structTreeDispatch({ type: 'RESOLVE', value: nextStructTree });
})
.catch((error) => {
structTreeDispatch({ type: 'REJECT', error });
});
return () => (0, utils_js_1.cancelRunningTask)(runningTask);
}, [customTextRenderer, page, structTreeDispatch]);
// biome-ignore lint/correctness/useExhaustiveDependencies: Ommitted callbacks so they are not called every time they change
(0, react_1.useEffect)(() => {
if (structTree === undefined) {
return;
}
if (structTree === false) {
onLoadError();
return;
}
onLoadSuccess();
}, [structTree]);
if (!structTree) {
return null;
}
return (0, jsx_runtime_1.jsx)(StructTreeItem_js_1.default, { className: "react-pdf__Page__structTree structTree", node: structTree });
}

8
node_modules/react-pdf/dist/cjs/StructTreeItem.d.ts generated vendored Normal file
View File

@@ -0,0 +1,8 @@
import type { StructTreeContent } from 'pdfjs-dist/types/src/display/api.js';
import type { StructTreeNodeWithExtraAttributes } from './shared/types.js';
type StructTreeItemProps = {
className?: string;
node: StructTreeNodeWithExtraAttributes | StructTreeContent;
};
export default function StructTreeItem({ className, node, }: StructTreeItemProps): React.ReactElement;
export {};

23
node_modules/react-pdf/dist/cjs/StructTreeItem.js generated vendored Normal file
View File

@@ -0,0 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = StructTreeItem;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const structTreeUtils_js_1 = require("./shared/structTreeUtils.js");
function StructTreeItem({ className, node, }) {
const attributes = (0, react_1.useMemo)(() => (0, structTreeUtils_js_1.getAttributes)(node), [node]);
const children = (0, react_1.useMemo)(() => {
if (!(0, structTreeUtils_js_1.isStructTreeNode)(node)) {
return null;
}
if ((0, structTreeUtils_js_1.isStructTreeNodeWithOnlyContentChild)(node)) {
return null;
}
return node.children.map((child, index) => {
return (
// biome-ignore lint/suspicious/noArrayIndexKey: index is stable here
(0, jsx_runtime_1.jsx)(StructTreeItem, { node: child }, index));
});
}, [node]);
return ((0, jsx_runtime_1.jsx)("span", Object.assign({ className: className }, attributes, { children: children })));
}

23
node_modules/react-pdf/dist/cjs/Thumbnail.d.ts generated vendored Normal file
View File

@@ -0,0 +1,23 @@
import type { PageProps } from './Page.js';
import type { ClassName, OnItemClickArgs } from './shared/types.js';
export type ThumbnailProps = Omit<PageProps, 'className' | 'customTextRenderer' | 'onGetAnnotationsError' | 'onGetAnnotationsSuccess' | 'onGetTextError' | 'onGetTextSuccess' | 'onRenderAnnotationLayerError' | 'onRenderAnnotationLayerSuccess' | 'onRenderTextLayerError' | 'onRenderTextLayerSuccess' | 'renderAnnotationLayer' | 'renderForms' | 'renderTextLayer'> & {
/**
* Class name(s) that will be added to rendered element along with the default `react-pdf__Thumbnail`.
*
* @example 'custom-class-name-1 custom-class-name-2'
* @example ['custom-class-name-1', 'custom-class-name-2']
*/
className?: ClassName;
/**
* Function called when a thumbnail has been clicked. Usually, you would like to use this callback to move the user wherever they requested to.
*
* @example ({ dest, pageIndex, pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!')
*/
onItemClick?: (args: OnItemClickArgs) => void;
};
/**
* Displays a thumbnail of a page. Does not render the annotation layer or the text layer. Does not register itself as a link target, so the user will not be scrolled to a Thumbnail component when clicked on an internal link (e.g. in Table of Contents). When clicked, attempts to navigate to the page clicked (similarly to a link in Outline).
*
* Should be placed inside `<Document />`. Alternatively, it can have `pdf` prop passed, which can be obtained from `<Document />`'s `onLoadSuccess` callback function.
*/
export default function Thumbnail(props: ThumbnailProps): React.ReactElement;

55
node_modules/react-pdf/dist/cjs/Thumbnail.js generated vendored Normal file
View File

@@ -0,0 +1,55 @@
"use strict";
'use client';
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Thumbnail;
const jsx_runtime_1 = require("react/jsx-runtime");
const clsx_1 = __importDefault(require("clsx"));
const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
const Page_js_1 = __importDefault(require("./Page.js"));
const utils_js_1 = require("./shared/utils.js");
const useDocumentContext_js_1 = __importDefault(require("./shared/hooks/useDocumentContext.js"));
/**
* Displays a thumbnail of a page. Does not render the annotation layer or the text layer. Does not register itself as a link target, so the user will not be scrolled to a Thumbnail component when clicked on an internal link (e.g. in Table of Contents). When clicked, attempts to navigate to the page clicked (similarly to a link in Outline).
*
* Should be placed inside `<Document />`. Alternatively, it can have `pdf` prop passed, which can be obtained from `<Document />`'s `onLoadSuccess` callback function.
*/
function Thumbnail(props) {
const documentContext = (0, useDocumentContext_js_1.default)();
const mergedProps = Object.assign(Object.assign({}, documentContext), props);
const { className, linkService, onItemClick, pageIndex: pageIndexProps, pageNumber: pageNumberProps, pdf, } = mergedProps;
(0, tiny_invariant_1.default)(pdf, 'Attempted to load a thumbnail, but no document was specified. Wrap <Thumbnail /> in a <Document /> or pass explicit `pdf` prop.');
const pageIndex = (0, utils_js_1.isProvided)(pageNumberProps) ? pageNumberProps - 1 : (pageIndexProps !== null && pageIndexProps !== void 0 ? pageIndexProps : null);
const pageNumber = pageNumberProps !== null && pageNumberProps !== void 0 ? pageNumberProps : ((0, utils_js_1.isProvided)(pageIndexProps) ? pageIndexProps + 1 : null);
function onClick(event) {
event.preventDefault();
if (!(0, utils_js_1.isProvided)(pageIndex) || !pageNumber) {
return;
}
(0, tiny_invariant_1.default)(onItemClick || linkService, 'Either onItemClick callback or linkService must be defined in order to navigate to an outline item.');
if (onItemClick) {
onItemClick({
pageIndex,
pageNumber,
});
}
else if (linkService) {
linkService.goToPage(pageNumber);
}
}
const { className: classNameProps, onItemClick: onItemClickProps } = props, pageProps = __rest(props, ["className", "onItemClick"]);
return ((0, jsx_runtime_1.jsx)("a", { className: (0, clsx_1.default)('react-pdf__Thumbnail', className), href: pageNumber ? '#' : undefined, onClick: onClick, children: (0, jsx_runtime_1.jsx)(Page_js_1.default, Object.assign({}, pageProps, { _className: "react-pdf__Thumbnail__page", _enableRegisterUnregisterPage: false, renderAnnotationLayer: false, renderTextLayer: false })) }));
}

14
node_modules/react-pdf/dist/cjs/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,14 @@
import * as pdfjs from 'pdfjs-dist';
import Document from './Document.js';
import Outline from './Outline.js';
import Page from './Page.js';
import Thumbnail from './Thumbnail.js';
import useDocumentContext from './shared/hooks/useDocumentContext.js';
import useOutlineContext from './shared/hooks/useOutlineContext.js';
import usePageContext from './shared/hooks/usePageContext.js';
import PasswordResponses from './PasswordResponses.js';
export type { DocumentProps } from './Document.js';
export type { OutlineProps } from './Outline.js';
export type { PageProps } from './Page.js';
export type { ThumbnailProps } from './Thumbnail.js';
export { pdfjs, Document, Outline, Page, Thumbnail, useDocumentContext, useOutlineContext, usePageContext, PasswordResponses, };

50
node_modules/react-pdf/dist/cjs/index.js generated vendored Normal file
View File

@@ -0,0 +1,50 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PasswordResponses = exports.usePageContext = exports.useOutlineContext = exports.useDocumentContext = exports.Thumbnail = exports.Page = exports.Outline = exports.Document = exports.pdfjs = void 0;
const pdfjs = __importStar(require("pdfjs-dist"));
exports.pdfjs = pdfjs;
const Document_js_1 = __importDefault(require("./Document.js"));
exports.Document = Document_js_1.default;
const Outline_js_1 = __importDefault(require("./Outline.js"));
exports.Outline = Outline_js_1.default;
const Page_js_1 = __importDefault(require("./Page.js"));
exports.Page = Page_js_1.default;
const Thumbnail_js_1 = __importDefault(require("./Thumbnail.js"));
exports.Thumbnail = Thumbnail_js_1.default;
const useDocumentContext_js_1 = __importDefault(require("./shared/hooks/useDocumentContext.js"));
exports.useDocumentContext = useDocumentContext_js_1.default;
const useOutlineContext_js_1 = __importDefault(require("./shared/hooks/useOutlineContext.js"));
exports.useOutlineContext = useOutlineContext_js_1.default;
const usePageContext_js_1 = __importDefault(require("./shared/hooks/usePageContext.js"));
exports.usePageContext = usePageContext_js_1.default;
const PasswordResponses_js_1 = __importDefault(require("./PasswordResponses.js"));
exports.PasswordResponses = PasswordResponses_js_1.default;
const utils_js_1 = require("./shared/utils.js");
(0, utils_js_1.displayWorkerWarning)();
pdfjs.GlobalWorkerOptions.workerSrc = 'pdf.worker.mjs';

14
node_modules/react-pdf/dist/cjs/index.test.d.ts generated vendored Normal file
View File

@@ -0,0 +1,14 @@
import * as pdfjs from 'pdfjs-dist';
import Document from './Document.js';
import Outline from './Outline.js';
import Page from './Page.js';
import Thumbnail from './Thumbnail.js';
import useDocumentContext from './shared/hooks/useDocumentContext.js';
import useOutlineContext from './shared/hooks/useOutlineContext.js';
import usePageContext from './shared/hooks/usePageContext.js';
export type { DocumentProps } from './Document.js';
export type { OutlineProps } from './Outline.js';
export type { PageProps } from './Page.js';
export type { ThumbnailProps } from './Thumbnail.js';
import './pdf.worker.entry.js';
export { pdfjs, Document, Outline, Page, Thumbnail, useDocumentContext, useOutlineContext, usePageContext, };

46
node_modules/react-pdf/dist/cjs/index.test.js generated vendored Normal file
View File

@@ -0,0 +1,46 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.usePageContext = exports.useOutlineContext = exports.useDocumentContext = exports.Thumbnail = exports.Page = exports.Outline = exports.Document = exports.pdfjs = void 0;
const pdfjs = __importStar(require("pdfjs-dist"));
exports.pdfjs = pdfjs;
const Document_js_1 = __importDefault(require("./Document.js"));
exports.Document = Document_js_1.default;
const Outline_js_1 = __importDefault(require("./Outline.js"));
exports.Outline = Outline_js_1.default;
const Page_js_1 = __importDefault(require("./Page.js"));
exports.Page = Page_js_1.default;
const Thumbnail_js_1 = __importDefault(require("./Thumbnail.js"));
exports.Thumbnail = Thumbnail_js_1.default;
const useDocumentContext_js_1 = __importDefault(require("./shared/hooks/useDocumentContext.js"));
exports.useDocumentContext = useDocumentContext_js_1.default;
const useOutlineContext_js_1 = __importDefault(require("./shared/hooks/useOutlineContext.js"));
exports.useOutlineContext = useOutlineContext_js_1.default;
const usePageContext_js_1 = __importDefault(require("./shared/hooks/usePageContext.js"));
exports.usePageContext = usePageContext_js_1.default;
require("./pdf.worker.entry.js");

3
node_modules/react-pdf/dist/cjs/package.json generated vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"type": "commonjs"
}

View File

@@ -0,0 +1,7 @@
/**
* PDF.js worker entry file.
*
* This file is identical to Mozilla's pdf.worker.entry.js, with one exception being placed inside
* this bundle, not theirs.
*/
export {};

34
node_modules/react-pdf/dist/cjs/pdf.worker.entry.js generated vendored Normal file
View File

@@ -0,0 +1,34 @@
"use strict";
/**
* PDF.js worker entry file.
*
* This file is identical to Mozilla's pdf.worker.entry.js, with one exception being placed inside
* this bundle, not theirs.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
(typeof window !== 'undefined' ? window : {}).pdfjsWorker =
// @ts-expect-error - pdfjs-dist does not ship with types
await Promise.resolve().then(() => __importStar(require('pdfjs-dist/build/pdf.worker.mjs')));

43
node_modules/react-pdf/dist/cjs/shared/constants.d.ts generated vendored Normal file
View File

@@ -0,0 +1,43 @@
export declare const PDF_ROLE_TO_HTML_ROLE: {
Document: null;
DocumentFragment: null;
Part: string;
Sect: string;
Div: string;
Aside: string;
NonStruct: string;
P: null;
H: string;
Title: null;
FENote: string;
Sub: string;
Lbl: null;
Span: null;
Em: null;
Strong: null;
Link: string;
Annot: string;
Form: string;
Ruby: null;
RB: null;
RT: null;
RP: null;
Warichu: null;
WT: null;
WP: null;
L: string;
LI: string;
LBody: null;
Table: string;
TR: string;
TH: string;
TD: string;
THead: string;
TBody: null;
TFoot: null;
Caption: null;
Figure: string;
Formula: null;
Artifact: null;
};
export declare const HEADING_PATTERN: RegExp;

60
node_modules/react-pdf/dist/cjs/shared/constants.js generated vendored Normal file
View File

@@ -0,0 +1,60 @@
"use strict";
// From pdfjs-dist/lib/web/struct_tree_layer_builder.js
Object.defineProperty(exports, "__esModule", { value: true });
exports.HEADING_PATTERN = exports.PDF_ROLE_TO_HTML_ROLE = void 0;
exports.PDF_ROLE_TO_HTML_ROLE = {
// Document level structure types
Document: null, // There's a "document" role, but it doesn't make sense here.
DocumentFragment: null,
// Grouping level structure types
Part: 'group',
Sect: 'group', // XXX: There's a "section" role, but it's abstract.
Div: 'group',
Aside: 'note',
NonStruct: 'none',
// Block level structure types
P: null,
// H<n>,
H: 'heading',
Title: null,
FENote: 'note',
// Sub-block level structure type
Sub: 'group',
// General inline level structure types
Lbl: null,
Span: null,
Em: null,
Strong: null,
Link: 'link',
Annot: 'note',
Form: 'form',
// Ruby and Warichu structure types
Ruby: null,
RB: null,
RT: null,
RP: null,
Warichu: null,
WT: null,
WP: null,
// List standard structure types
L: 'list',
LI: 'listitem',
LBody: null,
// Table standard structure types
Table: 'table',
TR: 'row',
TH: 'columnheader',
TD: 'cell',
THead: 'columnheader',
TBody: null,
TFoot: null,
// Standard structure type Caption
Caption: null,
// Standard structure type Figure
Figure: 'figure',
// Standard structure type Formula
Formula: null,
// standard structure type Artifact
Artifact: null,
};
exports.HEADING_PATTERN = /^H(\d+)$/;

View File

@@ -0,0 +1 @@
export default function useCachedValue<T>(getter: () => T): () => T;

View File

@@ -0,0 +1,18 @@
"use strict";
'use client';
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = useCachedValue;
const react_1 = require("react");
const utils_js_1 = require("../utils.js");
function useCachedValue(getter) {
const ref = (0, react_1.useRef)(undefined);
const currentValue = ref.current;
if ((0, utils_js_1.isDefined)(currentValue)) {
return () => currentValue;
}
return () => {
const value = getter();
ref.current = value;
return value;
};
}

View File

@@ -0,0 +1,2 @@
import type { DocumentContextType } from '../types.js';
export default function useDocumentContext(): DocumentContextType;

View File

@@ -0,0 +1,11 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = useDocumentContext;
const react_1 = require("react");
const DocumentContext_js_1 = __importDefault(require("../../DocumentContext.js"));
function useDocumentContext() {
return (0, react_1.useContext)(DocumentContext_js_1.default);
}

View File

@@ -0,0 +1,2 @@
import type { OutlineContextType } from '../types.js';
export default function useOutlineContext(): OutlineContextType;

View File

@@ -0,0 +1,11 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = useOutlineContext;
const react_1 = require("react");
const OutlineContext_js_1 = __importDefault(require("../../OutlineContext.js"));
function useOutlineContext() {
return (0, react_1.useContext)(OutlineContext_js_1.default);
}

View File

@@ -0,0 +1,2 @@
import type { PageContextType } from '../types.js';
export default function usePageContext(): PageContextType;

View File

@@ -0,0 +1,11 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = usePageContext;
const react_1 = require("react");
const PageContext_js_1 = __importDefault(require("../../PageContext.js"));
function usePageContext() {
return (0, react_1.useContext)(PageContext_js_1.default);
}

View File

@@ -0,0 +1,21 @@
type State<T> = {
value: T;
error: undefined;
} | {
value: false;
error: Error;
} | {
value: undefined;
error: undefined;
};
type Action<T> = {
type: 'RESOLVE';
value: T;
} | {
type: 'REJECT';
error: Error;
} | {
type: 'RESET';
};
export default function useResolver<T>(): [State<T>, React.Dispatch<Action<T>>];
export {};

View File

@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = useResolver;
const react_1 = require("react");
function reducer(state, action) {
switch (action.type) {
case 'RESOLVE':
return { value: action.value, error: undefined };
case 'REJECT':
return { value: false, error: action.error };
case 'RESET':
return { value: undefined, error: undefined };
default:
return state;
}
}
function useResolver() {
return (0, react_1.useReducer)((reducer), { value: undefined, error: undefined });
}

View File

@@ -0,0 +1,12 @@
import { PDF_ROLE_TO_HTML_ROLE } from './constants.js';
import type { StructTreeContent, StructTreeNode } from 'pdfjs-dist/types/src/display/api.js';
import type { StructTreeNodeWithExtraAttributes } from './types.js';
type PdfRole = keyof typeof PDF_ROLE_TO_HTML_ROLE;
type Attributes = React.HTMLAttributes<HTMLElement>;
export declare function isPdfRole(role: string): role is PdfRole;
export declare function isStructTreeNode(node: StructTreeNode | StructTreeContent): node is StructTreeNode;
export declare function isStructTreeNodeWithOnlyContentChild(node: StructTreeNode | StructTreeContent): boolean;
export declare function getRoleAttributes(node: StructTreeNode | StructTreeContent): Attributes;
export declare function getBaseAttributes(node: StructTreeNodeWithExtraAttributes | StructTreeContent): Attributes;
export declare function getAttributes(node: StructTreeNodeWithExtraAttributes | StructTreeContent): Attributes | null;
export {};

View File

@@ -0,0 +1,69 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isPdfRole = isPdfRole;
exports.isStructTreeNode = isStructTreeNode;
exports.isStructTreeNodeWithOnlyContentChild = isStructTreeNodeWithOnlyContentChild;
exports.getRoleAttributes = getRoleAttributes;
exports.getBaseAttributes = getBaseAttributes;
exports.getAttributes = getAttributes;
const constants_js_1 = require("./constants.js");
function isPdfRole(role) {
return role in constants_js_1.PDF_ROLE_TO_HTML_ROLE;
}
function isStructTreeNode(node) {
return 'children' in node;
}
function isStructTreeNodeWithOnlyContentChild(node) {
if (!isStructTreeNode(node)) {
return false;
}
return node.children.length === 1 && 0 in node.children && 'id' in node.children[0];
}
function getRoleAttributes(node) {
const attributes = {};
if (isStructTreeNode(node)) {
const { role } = node;
const matches = role.match(constants_js_1.HEADING_PATTERN);
if (matches) {
attributes.role = 'heading';
attributes['aria-level'] = Number(matches[1]);
}
else if (isPdfRole(role)) {
const htmlRole = constants_js_1.PDF_ROLE_TO_HTML_ROLE[role];
if (htmlRole) {
attributes.role = htmlRole;
}
}
}
return attributes;
}
function getBaseAttributes(node) {
const attributes = {};
if (isStructTreeNode(node)) {
if (node.alt !== undefined) {
attributes['aria-label'] = node.alt;
}
if (node.lang !== undefined) {
attributes.lang = node.lang;
}
if (isStructTreeNodeWithOnlyContentChild(node)) {
const [child] = node.children;
if (child) {
const childAttributes = getBaseAttributes(child);
return Object.assign(Object.assign({}, attributes), childAttributes);
}
}
}
else {
if ('id' in node) {
attributes['aria-owns'] = node.id;
}
}
return attributes;
}
function getAttributes(node) {
if (!node) {
return null;
}
return Object.assign(Object.assign({}, getRoleAttributes(node)), getBaseAttributes(node));
}

119
node_modules/react-pdf/dist/cjs/shared/types.d.ts generated vendored Normal file
View File

@@ -0,0 +1,119 @@
import type { PDFDataRangeTransport, PDFDocumentProxy, PDFPageProxy, PasswordResponses } from 'pdfjs-dist';
import type { TypedArray, DocumentInitParameters, RefProxy, StructTreeNode, TextContent, TextItem } from 'pdfjs-dist/types/src/display/api.js';
import type { AnnotationLayerParameters } from 'pdfjs-dist/types/src/display/annotation_layer.js';
import type LinkService from '../LinkService.js';
type NullableObject<T extends object> = {
[P in keyof T]: T[P] | null;
};
type KeyOfUnion<T> = T extends unknown ? keyof T : never;
export type Annotations = AnnotationLayerParameters['annotations'];
export type ClassName = string | null | undefined | (string | null | undefined)[];
export type ResolvedDest = (RefProxy | number)[];
export type Dest = Promise<ResolvedDest> | ResolvedDest | string | null;
export type ExternalLinkRel = string;
export type ExternalLinkTarget = '_self' | '_blank' | '_parent' | '_top';
export type ImageResourcesPath = string;
export type OnError = (error: Error) => void;
export type OnItemClickArgs = {
dest?: Dest;
pageIndex: number;
pageNumber: number;
};
export type OnLoadProgressArgs = {
loaded: number;
total: number;
};
export type RegisterPage = (pageIndex: number, ref: HTMLDivElement) => void;
export type RenderMode = 'canvas' | 'custom' | 'none';
export type ScrollPageIntoViewArgs = {
dest?: ResolvedDest;
pageIndex?: number;
pageNumber: number;
};
type BinaryData = TypedArray | ArrayBuffer | number[] | string;
export type Source = {
data: BinaryData | undefined;
} | {
range: PDFDataRangeTransport;
} | {
url: string;
};
export type UnregisterPage = (pageIndex: number) => void;
export type CustomRenderer = React.FunctionComponent | React.ComponentClass;
export type CustomTextRenderer = (props: {
pageIndex: number;
pageNumber: number;
itemIndex: number;
} & TextItem) => string;
export type DocumentCallback = PDFDocumentProxy;
export type File = string | ArrayBuffer | Blob | Source | null;
export type PageCallback = PDFPageProxy & {
width: number;
height: number;
originalWidth: number;
originalHeight: number;
};
export type NodeOrRenderer = React.ReactNode | (() => React.ReactNode);
export type OnDocumentLoadError = OnError;
export type OnDocumentLoadProgress = (args: OnLoadProgressArgs) => void;
export type OnDocumentLoadSuccess = (document: DocumentCallback) => void;
export type OnGetAnnotationsError = OnError;
export type OnGetAnnotationsSuccess = (annotations: Annotations) => void;
export type OnGetStructTreeError = OnError;
export type OnGetStructTreeSuccess = (tree: StructTreeNode) => void;
export type OnGetTextError = OnError;
export type OnGetTextSuccess = (textContent: TextContent) => void;
export type OnPageLoadError = OnError;
export type OnPageLoadSuccess = (page: PageCallback) => void;
export type OnPasswordCallback = (password: string | null) => void;
export type OnRenderAnnotationLayerError = (error: unknown) => void;
export type OnRenderAnnotationLayerSuccess = () => void;
export type OnRenderError = OnError;
export type OnRenderSuccess = (page: PageCallback) => void;
export type OnRenderTextLayerError = OnError;
export type OnRenderTextLayerSuccess = () => void;
export type PasswordResponse = (typeof PasswordResponses)[keyof typeof PasswordResponses];
export type Options = NullableObject<Omit<DocumentInitParameters, KeyOfUnion<Source>>>;
export type DocumentContextType = {
imageResourcesPath?: ImageResourcesPath;
linkService: LinkService;
onItemClick?: (args: OnItemClickArgs) => void;
pdf?: PDFDocumentProxy | false;
registerPage: RegisterPage;
renderMode?: RenderMode;
rotate?: number | null;
unregisterPage: UnregisterPage;
} | null;
export type PageContextType = {
_className?: string;
canvasBackground?: string;
customTextRenderer?: CustomTextRenderer;
devicePixelRatio?: number;
onGetAnnotationsError?: OnGetAnnotationsError;
onGetAnnotationsSuccess?: OnGetAnnotationsSuccess;
onGetStructTreeError?: OnGetStructTreeError;
onGetStructTreeSuccess?: OnGetStructTreeSuccess;
onGetTextError?: OnGetTextError;
onGetTextSuccess?: OnGetTextSuccess;
onRenderAnnotationLayerError?: OnRenderAnnotationLayerError;
onRenderAnnotationLayerSuccess?: OnRenderAnnotationLayerSuccess;
onRenderError?: OnRenderError;
onRenderSuccess?: OnRenderSuccess;
onRenderTextLayerError?: OnRenderTextLayerError;
onRenderTextLayerSuccess?: OnRenderTextLayerSuccess;
page: PDFPageProxy | false | undefined;
pageIndex: number;
pageNumber: number;
renderForms: boolean;
renderTextLayer: boolean;
rotate: number;
scale: number;
} | null;
export type OutlineContextType = {
onItemClick?: (args: OnItemClickArgs) => void;
} | null;
export type StructTreeNodeWithExtraAttributes = StructTreeNode & {
alt?: string;
lang?: string;
};
export {};

2
node_modules/react-pdf/dist/cjs/shared/types.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

56
node_modules/react-pdf/dist/cjs/shared/utils.d.ts generated vendored Normal file
View File

@@ -0,0 +1,56 @@
import type { PDFPageProxy } from 'pdfjs-dist';
import type { PageCallback } from './types.js';
/**
* Checks if we're running in a browser environment.
*/
export declare const isBrowser: boolean;
/**
* Checks whether we're running from a local file system.
*/
export declare const isLocalFileSystem: boolean;
/**
* Checks whether a variable is defined.
*
* @param {*} variable Variable to check
*/
export declare function isDefined<T>(variable: T | undefined): variable is T;
/**
* Checks whether a variable is defined and not null.
*
* @param {*} variable Variable to check
*/
export declare function isProvided<T>(variable: T | null | undefined): variable is T;
/**
* Checks whether a variable provided is a string.
*
* @param {*} variable Variable to check
*/
export declare function isString(variable: unknown): variable is string;
/**
* Checks whether a variable provided is an ArrayBuffer.
*
* @param {*} variable Variable to check
*/
export declare function isArrayBuffer(variable: unknown): variable is ArrayBuffer;
/**
* Checks whether a variable provided is a Blob.
*
* @param {*} variable Variable to check
*/
export declare function isBlob(variable: unknown): variable is Blob;
/**
* Checks whether a variable provided is a data URI.
*
* @param {*} variable String to check
*/
export declare function isDataURI(variable: unknown): variable is `data:${string}`;
export declare function dataURItoByteString(dataURI: unknown): string;
export declare function getDevicePixelRatio(): number;
export declare function displayCORSWarning(): void;
export declare function displayWorkerWarning(): void;
export declare function cancelRunningTask(runningTask?: {
cancel?: () => void;
} | null): void;
export declare function makePageCallback(page: PDFPageProxy, scale: number): PageCallback;
export declare function isCancelException(error: Error): boolean;
export declare function loadFromFile(file: Blob): Promise<ArrayBuffer>;

163
node_modules/react-pdf/dist/cjs/shared/utils.js generated vendored Normal file
View File

@@ -0,0 +1,163 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isLocalFileSystem = exports.isBrowser = void 0;
exports.isDefined = isDefined;
exports.isProvided = isProvided;
exports.isString = isString;
exports.isArrayBuffer = isArrayBuffer;
exports.isBlob = isBlob;
exports.isDataURI = isDataURI;
exports.dataURItoByteString = dataURItoByteString;
exports.getDevicePixelRatio = getDevicePixelRatio;
exports.displayCORSWarning = displayCORSWarning;
exports.displayWorkerWarning = displayWorkerWarning;
exports.cancelRunningTask = cancelRunningTask;
exports.makePageCallback = makePageCallback;
exports.isCancelException = isCancelException;
exports.loadFromFile = loadFromFile;
const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
const warning_1 = __importDefault(require("warning"));
/**
* Checks if we're running in a browser environment.
*/
exports.isBrowser = typeof window !== 'undefined';
/**
* Checks whether we're running from a local file system.
*/
exports.isLocalFileSystem = exports.isBrowser && window.location.protocol === 'file:';
/**
* Checks whether a variable is defined.
*
* @param {*} variable Variable to check
*/
function isDefined(variable) {
return typeof variable !== 'undefined';
}
/**
* Checks whether a variable is defined and not null.
*
* @param {*} variable Variable to check
*/
function isProvided(variable) {
return isDefined(variable) && variable !== null;
}
/**
* Checks whether a variable provided is a string.
*
* @param {*} variable Variable to check
*/
function isString(variable) {
return typeof variable === 'string';
}
/**
* Checks whether a variable provided is an ArrayBuffer.
*
* @param {*} variable Variable to check
*/
function isArrayBuffer(variable) {
return variable instanceof ArrayBuffer;
}
/**
* Checks whether a variable provided is a Blob.
*
* @param {*} variable Variable to check
*/
function isBlob(variable) {
(0, tiny_invariant_1.default)(exports.isBrowser, 'isBlob can only be used in a browser environment');
return variable instanceof Blob;
}
/**
* Checks whether a variable provided is a data URI.
*
* @param {*} variable String to check
*/
function isDataURI(variable) {
return isString(variable) && /^data:/.test(variable);
}
function dataURItoByteString(dataURI) {
(0, tiny_invariant_1.default)(isDataURI(dataURI), 'Invalid data URI.');
const [headersString = '', dataString = ''] = dataURI.split(',');
const headers = headersString.split(';');
if (headers.indexOf('base64') !== -1) {
return atob(dataString);
}
return unescape(dataString);
}
function getDevicePixelRatio() {
return (exports.isBrowser && window.devicePixelRatio) || 1;
}
const allowFileAccessFromFilesTip = 'On Chromium based browsers, you can use --allow-file-access-from-files flag for debugging purposes.';
function displayCORSWarning() {
(0, warning_1.default)(!exports.isLocalFileSystem, `Loading PDF as base64 strings/URLs may not work on protocols other than HTTP/HTTPS. ${allowFileAccessFromFilesTip}`);
}
function displayWorkerWarning() {
(0, warning_1.default)(!exports.isLocalFileSystem, `Loading PDF.js worker may not work on protocols other than HTTP/HTTPS. ${allowFileAccessFromFilesTip}`);
}
function cancelRunningTask(runningTask) {
if (runningTask === null || runningTask === void 0 ? void 0 : runningTask.cancel)
runningTask.cancel();
}
function makePageCallback(page, scale) {
Object.defineProperty(page, 'width', {
get() {
return this.view[2] * scale;
},
configurable: true,
});
Object.defineProperty(page, 'height', {
get() {
return this.view[3] * scale;
},
configurable: true,
});
Object.defineProperty(page, 'originalWidth', {
get() {
return this.view[2];
},
configurable: true,
});
Object.defineProperty(page, 'originalHeight', {
get() {
return this.view[3];
},
configurable: true,
});
return page;
}
function isCancelException(error) {
return error.name === 'RenderingCancelledException';
}
function loadFromFile(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
if (!reader.result) {
return reject(new Error('Error while reading a file.'));
}
resolve(reader.result);
};
reader.onerror = (event) => {
if (!event.target) {
return reject(new Error('Error while reading a file.'));
}
const { error } = event.target;
if (!error) {
return reject(new Error('Error while reading a file.'));
}
switch (error.code) {
case error.NOT_FOUND_ERR:
return reject(new Error('Error while reading a file: File not found.'));
case error.SECURITY_ERR:
return reject(new Error('Error while reading a file: Security error.'));
case error.ABORT_ERR:
return reject(new Error('Error while reading a file: Aborted.'));
default:
return reject(new Error('Error while reading a file.'));
}
};
reader.readAsArrayBuffer(file);
});
}

160
node_modules/react-pdf/dist/esm/Document.d.ts generated vendored Normal file
View File

@@ -0,0 +1,160 @@
import LinkService from './LinkService.js';
import type { EventProps } from 'make-event-props';
import type { ClassName, DocumentCallback, ExternalLinkRel, ExternalLinkTarget, File, ImageResourcesPath, NodeOrRenderer, OnDocumentLoadError, OnDocumentLoadProgress, OnDocumentLoadSuccess, OnError, OnItemClickArgs, OnPasswordCallback, Options, PasswordResponse, RenderMode, ScrollPageIntoViewArgs } from './shared/types.js';
type OnItemClick = (args: OnItemClickArgs) => void;
type OnPassword = (callback: OnPasswordCallback, reason: PasswordResponse) => void;
type OnSourceError = OnError;
type OnSourceSuccess = () => void;
export type DocumentProps = {
children?: React.ReactNode;
/**
* Class name(s) that will be added to rendered element along with the default `react-pdf__Document`.
*
* @example 'custom-class-name-1 custom-class-name-2'
* @example ['custom-class-name-1', 'custom-class-name-2']
*/
className?: ClassName;
/**
* What the component should display in case of an error.
*
* @default 'Failed to load PDF file.'
* @example 'An error occurred!'
* @example <p>An error occurred!</p>
* @example {this.renderError}
*/
error?: NodeOrRenderer;
/**
* Link rel for links rendered in annotations.
*
* @default 'noopener noreferrer nofollow'
*/
externalLinkRel?: ExternalLinkRel;
/**
* Link target for external links rendered in annotations.
*/
externalLinkTarget?: ExternalLinkTarget;
/**
* What PDF should be displayed.
*
* Its value can be an URL, a file (imported using `import … from …` or from file input form element), or an object with parameters (`url` - URL; `data` - data, preferably Uint8Array; `range` - PDFDataRangeTransport.
*
* **Warning**: Since equality check (`===`) is used to determine if `file` object has changed, it must be memoized by setting it in component's state, `useMemo` or other similar technique.
*
* @example 'https://example.com/sample.pdf'
* @example importedPdf
* @example { url: 'https://example.com/sample.pdf' }
*/
file?: File;
/**
* The path used to prefix the src attributes of annotation SVGs.
*
* @default ''
* @example '/public/images/'
*/
imageResourcesPath?: ImageResourcesPath;
/**
* A prop that behaves like [ref](https://reactjs.org/docs/refs-and-the-dom.html), but it's passed to main `<div>` rendered by `<Document>` component.
*
* @example (ref) => { this.myDocument = ref; }
* @example this.ref
* @example ref
*/
inputRef?: React.Ref<HTMLDivElement | null>;
/**
* What the component should display while loading.
*
* @default 'Loading PDF…'
* @example 'Please wait!'
* @example <p>Please wait!</p>
* @example {this.renderLoader}
*/
loading?: NodeOrRenderer;
/**
* What the component should display in case of no data.
*
* @default 'No PDF file specified.'
* @example 'Please select a file.'
* @example <p>Please select a file.</p>
* @example {this.renderNoData}
*/
noData?: NodeOrRenderer;
/**
* Function called when an outline item or a thumbnail has been clicked. Usually, you would like to use this callback to move the user wherever they requested to.
*
* @example ({ dest, pageIndex, pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!')
*/
onItemClick?: OnItemClick;
/**
* Function called in case of an error while loading a document.
*
* @example (error) => alert('Error while loading document! ' + error.message)
*/
onLoadError?: OnDocumentLoadError;
/**
* Function called, potentially multiple times, as the loading progresses.
*
* @example ({ loaded, total }) => alert('Loading a document: ' + (loaded / total) * 100 + '%')
*/
onLoadProgress?: OnDocumentLoadProgress;
/**
* Function called when the document is successfully loaded.
*
* @example (pdf) => alert('Loaded a file with ' + pdf.numPages + ' pages!')
*/
onLoadSuccess?: OnDocumentLoadSuccess;
/**
* Function called when a password-protected PDF is loaded.
*
* @example (callback) => callback('s3cr3t_p4ssw0rd')
*/
onPassword?: OnPassword;
/**
* Function called in case of an error while retrieving document source from `file` prop.
*
* @example (error) => alert('Error while retrieving document source! ' + error.message)
*/
onSourceError?: OnSourceError;
/**
* Function called when document source is successfully retrieved from `file` prop.
*
* @example () => alert('Document source retrieved!')
*/
onSourceSuccess?: OnSourceSuccess;
/**
* An object in which additional parameters to be passed to PDF.js can be defined. Most notably:
* - `cMapUrl`;
* - `httpHeaders` - custom request headers, e.g. for authorization);
* - `withCredentials` - a boolean to indicate whether or not to include cookies in the request (defaults to `false`)
*
* For a full list of possible parameters, check [PDF.js documentation on DocumentInitParameters](https://mozilla.github.io/pdf.js/api/draft/module-pdfjsLib.html#~DocumentInitParameters).
*
* **Note**: Make sure to define options object outside of your React component, and use `useMemo` if you can't.
*
* @example { cMapUrl: '/cmaps/' }
*/
options?: Options;
/**
* Rendering mode of the document. Can be `"canvas"`, `"custom"` or `"none"``. If set to `"custom"`, `customRenderer` must also be provided.
*
* @default 'canvas'
* @example 'custom'
*/
renderMode?: RenderMode;
/**
* Rotation of the document in degrees. If provided, will change rotation globally, even for the pages which were given `rotate` prop of their own. `90` = rotated to the right, `180` = upside down, `270` = rotated to the left.
*
* @example 90
*/
rotate?: number | null;
} & EventProps<DocumentCallback | false | undefined>;
/**
* Loads a document passed using `file` prop.
*/
declare const Document: React.ForwardRefExoticComponent<DocumentProps & React.RefAttributes<{
linkService: React.RefObject<LinkService>;
pages: React.RefObject<HTMLDivElement[]>;
viewer: React.RefObject<{
scrollPageIntoView: (args: ScrollPageIntoViewArgs) => void;
}>;
}>>;
export default Document;

316
node_modules/react-pdf/dist/esm/Document.js generated vendored Normal file
View File

@@ -0,0 +1,316 @@
'use client';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
import { jsx as _jsx } from "react/jsx-runtime";
import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef } from 'react';
import makeEventProps from 'make-event-props';
import makeCancellable from 'make-cancellable-promise';
import clsx from 'clsx';
import invariant from 'tiny-invariant';
import warning from 'warning';
import { dequal } from 'dequal';
import * as pdfjs from 'pdfjs-dist';
import DocumentContext from './DocumentContext.js';
import Message from './Message.js';
import LinkService from './LinkService.js';
import PasswordResponses from './PasswordResponses.js';
import { cancelRunningTask, dataURItoByteString, displayCORSWarning, isArrayBuffer, isBlob, isBrowser, isDataURI, loadFromFile, } from './shared/utils.js';
import useResolver from './shared/hooks/useResolver.js';
const { PDFDataRangeTransport } = pdfjs;
const defaultOnPassword = (callback, reason) => {
switch (reason) {
case PasswordResponses.NEED_PASSWORD: {
const password = prompt('Enter the password to open this PDF file.');
callback(password);
break;
}
case PasswordResponses.INCORRECT_PASSWORD: {
const password = prompt('Invalid password. Please try again.');
callback(password);
break;
}
default:
}
};
function isParameterObject(file) {
return (typeof file === 'object' &&
file !== null &&
('data' in file || 'range' in file || 'url' in file));
}
/**
* Loads a document passed using `file` prop.
*/
const Document = forwardRef(function Document(_a, ref) {
var { children, className, error = 'Failed to load PDF file.', externalLinkRel, externalLinkTarget, file, inputRef, imageResourcesPath, loading = 'Loading PDF…', noData = 'No PDF file specified.', onItemClick, onLoadError: onLoadErrorProps, onLoadProgress, onLoadSuccess: onLoadSuccessProps, onPassword = defaultOnPassword, onSourceError: onSourceErrorProps, onSourceSuccess: onSourceSuccessProps, options, renderMode, rotate } = _a, otherProps = __rest(_a, ["children", "className", "error", "externalLinkRel", "externalLinkTarget", "file", "inputRef", "imageResourcesPath", "loading", "noData", "onItemClick", "onLoadError", "onLoadProgress", "onLoadSuccess", "onPassword", "onSourceError", "onSourceSuccess", "options", "renderMode", "rotate"]);
const [sourceState, sourceDispatch] = useResolver();
const { value: source, error: sourceError } = sourceState;
const [pdfState, pdfDispatch] = useResolver();
const { value: pdf, error: pdfError } = pdfState;
const linkService = useRef(new LinkService());
const pages = useRef([]);
const prevFile = useRef(undefined);
const prevOptions = useRef(undefined);
if (file && file !== prevFile.current && isParameterObject(file)) {
warning(!dequal(file, prevFile.current), `File prop passed to <Document /> changed, but it's equal to previous one. This might result in unnecessary reloads. Consider memoizing the value passed to "file" prop.`);
prevFile.current = file;
}
// Detect non-memoized changes in options prop
if (options && options !== prevOptions.current) {
warning(!dequal(options, prevOptions.current), `Options prop passed to <Document /> changed, but it's equal to previous one. This might result in unnecessary reloads. Consider memoizing the value passed to "options" prop.`);
prevOptions.current = options;
}
const viewer = useRef({
// Handling jumping to internal links target
scrollPageIntoView: (args) => {
const { dest, pageNumber, pageIndex = pageNumber - 1 } = args;
// First, check if custom handling of onItemClick was provided
if (onItemClick) {
onItemClick({ dest, pageIndex, pageNumber });
return;
}
// If not, try to look for target page within the <Document>.
const page = pages.current[pageIndex];
if (page) {
// Scroll to the page automatically
page.scrollIntoView();
return;
}
warning(false, `An internal link leading to page ${pageNumber} was clicked, but neither <Document> was provided with onItemClick nor it was able to find the page within itself. Either provide onItemClick to <Document> and handle navigating by yourself or ensure that all pages are rendered within <Document>.`);
},
});
useImperativeHandle(ref, () => ({
linkService,
pages,
viewer,
}), []);
/**
* Called when a document source is resolved correctly
*/
function onSourceSuccess() {
if (onSourceSuccessProps) {
onSourceSuccessProps();
}
}
/**
* Called when a document source failed to be resolved correctly
*/
function onSourceError() {
if (!sourceError) {
// Impossible, but TypeScript doesn't know that
return;
}
warning(false, sourceError.toString());
if (onSourceErrorProps) {
onSourceErrorProps(sourceError);
}
}
function resetSource() {
sourceDispatch({ type: 'RESET' });
}
// biome-ignore lint/correctness/useExhaustiveDependencies: See https://github.com/biomejs/biome/issues/3080
useEffect(resetSource, [file, sourceDispatch]);
const findDocumentSource = useCallback(() => __awaiter(this, void 0, void 0, function* () {
if (!file) {
return null;
}
// File is a string
if (typeof file === 'string') {
if (isDataURI(file)) {
const fileByteString = dataURItoByteString(file);
return { data: fileByteString };
}
displayCORSWarning();
return { url: file };
}
// File is PDFDataRangeTransport
if (file instanceof PDFDataRangeTransport) {
return { range: file };
}
// File is an ArrayBuffer
if (isArrayBuffer(file)) {
return { data: file };
}
/**
* The cases below are browser-only.
* If you're running on a non-browser environment, these cases will be of no use.
*/
if (isBrowser) {
// File is a Blob
if (isBlob(file)) {
const data = yield loadFromFile(file);
return { data };
}
}
// At this point, file must be an object
invariant(typeof file === 'object', 'Invalid parameter in file, need either Uint8Array, string or a parameter object');
invariant(isParameterObject(file), 'Invalid parameter object: need either .data, .range or .url');
// File .url is a string
if ('url' in file && typeof file.url === 'string') {
if (isDataURI(file.url)) {
const { url } = file, otherParams = __rest(file, ["url"]);
const fileByteString = dataURItoByteString(url);
return Object.assign({ data: fileByteString }, otherParams);
}
displayCORSWarning();
}
return file;
}), [file]);
useEffect(() => {
const cancellable = makeCancellable(findDocumentSource());
cancellable.promise
.then((nextSource) => {
sourceDispatch({ type: 'RESOLVE', value: nextSource });
})
.catch((error) => {
sourceDispatch({ type: 'REJECT', error });
});
return () => {
cancelRunningTask(cancellable);
};
}, [findDocumentSource, sourceDispatch]);
// biome-ignore lint/correctness/useExhaustiveDependencies: Ommitted callbacks so they are not called every time they change
useEffect(() => {
if (typeof source === 'undefined') {
return;
}
if (source === false) {
onSourceError();
return;
}
onSourceSuccess();
}, [source]);
/**
* Called when a document is read successfully
*/
function onLoadSuccess() {
if (!pdf) {
// Impossible, but TypeScript doesn't know that
return;
}
if (onLoadSuccessProps) {
onLoadSuccessProps(pdf);
}
pages.current = new Array(pdf.numPages);
linkService.current.setDocument(pdf);
}
/**
* Called when a document failed to read successfully
*/
function onLoadError() {
if (!pdfError) {
// Impossible, but TypeScript doesn't know that
return;
}
warning(false, pdfError.toString());
if (onLoadErrorProps) {
onLoadErrorProps(pdfError);
}
}
// biome-ignore lint/correctness/useExhaustiveDependencies: useEffect intentionally triggered on source change
useEffect(function resetDocument() {
pdfDispatch({ type: 'RESET' });
}, [pdfDispatch, source]);
// biome-ignore lint/correctness/useExhaustiveDependencies: Ommitted callbacks so they are not called every time they change
useEffect(function loadDocument() {
if (!source) {
return;
}
const documentInitParams = options
? Object.assign(Object.assign({}, source), options) : source;
const destroyable = pdfjs.getDocument(documentInitParams);
if (onLoadProgress) {
destroyable.onProgress = onLoadProgress;
}
if (onPassword) {
destroyable.onPassword = onPassword;
}
const loadingTask = destroyable;
const loadingPromise = loadingTask.promise
.then((nextPdf) => {
pdfDispatch({ type: 'RESOLVE', value: nextPdf });
})
.catch((error) => {
if (loadingTask.destroyed) {
return;
}
pdfDispatch({ type: 'REJECT', error });
});
return () => {
loadingPromise.finally(() => loadingTask.destroy());
};
}, [options, pdfDispatch, source]);
// biome-ignore lint/correctness/useExhaustiveDependencies: Ommitted callbacks so they are not called every time they change
useEffect(() => {
if (typeof pdf === 'undefined') {
return;
}
if (pdf === false) {
onLoadError();
return;
}
onLoadSuccess();
}, [pdf]);
useEffect(function setupLinkService() {
linkService.current.setViewer(viewer.current);
linkService.current.setExternalLinkRel(externalLinkRel);
linkService.current.setExternalLinkTarget(externalLinkTarget);
}, [externalLinkRel, externalLinkTarget]);
const registerPage = useCallback((pageIndex, ref) => {
pages.current[pageIndex] = ref;
}, []);
const unregisterPage = useCallback((pageIndex) => {
delete pages.current[pageIndex];
}, []);
const childContext = useMemo(() => ({
imageResourcesPath,
linkService: linkService.current,
onItemClick,
pdf,
registerPage,
renderMode,
rotate,
unregisterPage,
}), [imageResourcesPath, onItemClick, pdf, registerPage, renderMode, rotate, unregisterPage]);
const eventProps = useMemo(() => makeEventProps(otherProps, () => pdf),
// biome-ignore lint/correctness/useExhaustiveDependencies: FIXME
[otherProps, pdf]);
function renderChildren() {
return _jsx(DocumentContext.Provider, { value: childContext, children: children });
}
function renderContent() {
if (!file) {
return _jsx(Message, { type: "no-data", children: typeof noData === 'function' ? noData() : noData });
}
if (pdf === undefined || pdf === null) {
return (_jsx(Message, { type: "loading", children: typeof loading === 'function' ? loading() : loading }));
}
if (pdf === false) {
return _jsx(Message, { type: "error", children: typeof error === 'function' ? error() : error });
}
return renderChildren();
}
return (_jsx("div", Object.assign({ className: clsx('react-pdf__Document', className),
// Assertion is needed for React 18 compatibility
ref: inputRef, style: {
['--scale-factor']: '1',
} }, eventProps, { children: renderContent() })));
});
export default Document;

3
node_modules/react-pdf/dist/esm/DocumentContext.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
import type { DocumentContextType } from './shared/types.js';
declare const documentContext: React.Context<DocumentContextType>;
export default documentContext;

4
node_modules/react-pdf/dist/esm/DocumentContext.js generated vendored Normal file
View File

@@ -0,0 +1,4 @@
'use client';
import { createContext } from 'react';
const documentContext = createContext(null);
export default documentContext;

39
node_modules/react-pdf/dist/esm/LinkService.d.ts generated vendored Normal file
View File

@@ -0,0 +1,39 @@
import type { PDFDocumentProxy } from 'pdfjs-dist';
import type { Dest, ExternalLinkRel, ExternalLinkTarget, ScrollPageIntoViewArgs } from './shared/types.js';
import type { IPDFLinkService } from 'pdfjs-dist/types/web/interfaces.js';
type PDFViewer = {
currentPageNumber?: number;
scrollPageIntoView: (args: ScrollPageIntoViewArgs) => void;
};
export default class LinkService implements IPDFLinkService {
externalLinkEnabled: boolean;
externalLinkRel?: ExternalLinkRel;
externalLinkTarget?: ExternalLinkTarget;
isInPresentationMode: boolean;
pdfDocument?: PDFDocumentProxy | null;
pdfViewer?: PDFViewer | null;
constructor();
setDocument(pdfDocument: PDFDocumentProxy): void;
setViewer(pdfViewer: PDFViewer): void;
setExternalLinkRel(externalLinkRel?: ExternalLinkRel): void;
setExternalLinkTarget(externalLinkTarget?: ExternalLinkTarget): void;
setHistory(): void;
get pagesCount(): number;
get page(): number;
set page(value: number);
get rotation(): number;
set rotation(_value: number);
goToDestination(dest: Dest): Promise<void>;
navigateTo(dest: Dest): void;
goToPage(pageNumber: number): void;
addLinkAttributes(link: HTMLAnchorElement, url: string, newWindow: boolean): void;
getDestinationHash(): string;
getAnchorUrl(): string;
setHash(): void;
executeNamedAction(): void;
cachePageRef(): void;
isPageVisible(): boolean;
isPageCached(): boolean;
executeSetOCGState(): void;
}
export {};

145
node_modules/react-pdf/dist/esm/LinkService.js generated vendored Normal file
View File

@@ -0,0 +1,145 @@
/* Copyright 2015 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import invariant from 'tiny-invariant';
const DEFAULT_LINK_REL = 'noopener noreferrer nofollow';
export default class LinkService {
constructor() {
this.externalLinkEnabled = true;
this.externalLinkRel = undefined;
this.externalLinkTarget = undefined;
this.isInPresentationMode = false;
this.pdfDocument = undefined;
this.pdfViewer = undefined;
}
setDocument(pdfDocument) {
this.pdfDocument = pdfDocument;
}
setViewer(pdfViewer) {
this.pdfViewer = pdfViewer;
}
setExternalLinkRel(externalLinkRel) {
this.externalLinkRel = externalLinkRel;
}
setExternalLinkTarget(externalLinkTarget) {
this.externalLinkTarget = externalLinkTarget;
}
setHistory() {
// Intentionally empty
}
get pagesCount() {
return this.pdfDocument ? this.pdfDocument.numPages : 0;
}
get page() {
invariant(this.pdfViewer, 'PDF viewer is not initialized.');
return this.pdfViewer.currentPageNumber || 0;
}
set page(value) {
invariant(this.pdfViewer, 'PDF viewer is not initialized.');
this.pdfViewer.currentPageNumber = value;
}
get rotation() {
return 0;
}
set rotation(_value) {
// Intentionally empty
}
goToDestination(dest) {
return new Promise((resolve) => {
invariant(this.pdfDocument, 'PDF document not loaded.');
invariant(dest, 'Destination is not specified.');
if (typeof dest === 'string') {
this.pdfDocument.getDestination(dest).then(resolve);
}
else if (Array.isArray(dest)) {
resolve(dest);
}
else {
dest.then(resolve);
}
}).then((explicitDest) => {
invariant(Array.isArray(explicitDest), `"${explicitDest}" is not a valid destination array.`);
const destRef = explicitDest[0];
new Promise((resolve) => {
invariant(this.pdfDocument, 'PDF document not loaded.');
if (destRef instanceof Object) {
this.pdfDocument
.getPageIndex(destRef)
.then((pageIndex) => {
resolve(pageIndex);
})
.catch(() => {
invariant(false, `"${destRef}" is not a valid page reference.`);
});
}
else if (typeof destRef === 'number') {
resolve(destRef);
}
else {
invariant(false, `"${destRef}" is not a valid destination reference.`);
}
}).then((pageIndex) => {
const pageNumber = pageIndex + 1;
invariant(this.pdfViewer, 'PDF viewer is not initialized.');
invariant(pageNumber >= 1 && pageNumber <= this.pagesCount, `"${pageNumber}" is not a valid page number.`);
this.pdfViewer.scrollPageIntoView({
dest: explicitDest,
pageIndex,
pageNumber,
});
});
});
}
navigateTo(dest) {
this.goToDestination(dest);
}
goToPage(pageNumber) {
const pageIndex = pageNumber - 1;
invariant(this.pdfViewer, 'PDF viewer is not initialized.');
invariant(pageNumber >= 1 && pageNumber <= this.pagesCount, `"${pageNumber}" is not a valid page number.`);
this.pdfViewer.scrollPageIntoView({
pageIndex,
pageNumber,
});
}
addLinkAttributes(link, url, newWindow) {
link.href = url;
link.rel = this.externalLinkRel || DEFAULT_LINK_REL;
link.target = newWindow ? '_blank' : this.externalLinkTarget || '';
}
getDestinationHash() {
return '#';
}
getAnchorUrl() {
return '#';
}
setHash() {
// Intentionally empty
}
executeNamedAction() {
// Intentionally empty
}
cachePageRef() {
// Intentionally empty
}
isPageVisible() {
return true;
}
isPageCached() {
return true;
}
executeSetOCGState() {
// Intentionally empty
}
}

6
node_modules/react-pdf/dist/esm/Message.d.ts generated vendored Normal file
View File

@@ -0,0 +1,6 @@
type MessageProps = {
children?: React.ReactNode;
type: 'error' | 'loading' | 'no-data';
};
export default function Message({ children, type }: MessageProps): React.ReactElement;
export {};

4
node_modules/react-pdf/dist/esm/Message.js generated vendored Normal file
View File

@@ -0,0 +1,4 @@
import { jsx as _jsx } from "react/jsx-runtime";
export default function Message({ children, type }) {
return _jsx("div", { className: `react-pdf__message react-pdf__message--${type}`, children: children });
}

47
node_modules/react-pdf/dist/esm/Outline.d.ts generated vendored Normal file
View File

@@ -0,0 +1,47 @@
import type { PDFDocumentProxy } from 'pdfjs-dist';
import type { EventProps } from 'make-event-props';
import type { ClassName, OnItemClickArgs } from './shared/types.js';
type PDFOutline = Awaited<ReturnType<PDFDocumentProxy['getOutline']>>;
export type OutlineProps = {
/**
* Class name(s) that will be added to rendered element along with the default `react-pdf__Outline`.
*
* @example 'custom-class-name-1 custom-class-name-2'
* @example ['custom-class-name-1', 'custom-class-name-2']
*/
className?: ClassName;
/**
* A prop that behaves like [ref](https://reactjs.org/docs/refs-and-the-dom.html), but it's passed to main `<div>` rendered by `<Outline>` component.
*
* @example (ref) => { this.myOutline = ref; }
* @example this.ref
* @example ref
*/
inputRef?: React.Ref<HTMLDivElement>;
/**
* Function called when an outline item has been clicked. Usually, you would like to use this callback to move the user wherever they requested to.
*
* @example ({ dest, pageIndex, pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!')
*/
onItemClick?: (props: OnItemClickArgs) => void;
/**
* Function called in case of an error while retrieving the outline.
*
* @example (error) => alert('Error while retrieving the outline! ' + error.message)
*/
onLoadError?: (error: Error) => void;
/**
* Function called when the outline is successfully retrieved.
*
* @example (outline) => alert('The outline has been successfully retrieved.')
*/
onLoadSuccess?: (outline: PDFOutline | null) => void;
pdf?: PDFDocumentProxy | false;
} & EventProps<PDFOutline | null | false | undefined>;
/**
* Displays an outline (table of contents).
*
* Should be placed inside `<Document />`. Alternatively, it can have `pdf` prop passed, which can be obtained from `<Document />`'s `onLoadSuccess` callback function.
*/
export default function Outline(props: OutlineProps): React.ReactElement | null;
export {};

108
node_modules/react-pdf/dist/esm/Outline.js generated vendored Normal file
View File

@@ -0,0 +1,108 @@
'use client';
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
import { jsx as _jsx } from "react/jsx-runtime";
import { useEffect, useMemo } from 'react';
import makeCancellable from 'make-cancellable-promise';
import makeEventProps from 'make-event-props';
import clsx from 'clsx';
import invariant from 'tiny-invariant';
import warning from 'warning';
import OutlineContext from './OutlineContext.js';
import OutlineItem from './OutlineItem.js';
import { cancelRunningTask } from './shared/utils.js';
import useDocumentContext from './shared/hooks/useDocumentContext.js';
import useResolver from './shared/hooks/useResolver.js';
/**
* Displays an outline (table of contents).
*
* Should be placed inside `<Document />`. Alternatively, it can have `pdf` prop passed, which can be obtained from `<Document />`'s `onLoadSuccess` callback function.
*/
export default function Outline(props) {
const documentContext = useDocumentContext();
const mergedProps = Object.assign(Object.assign({}, documentContext), props);
const { className, inputRef, onItemClick, onLoadError: onLoadErrorProps, onLoadSuccess: onLoadSuccessProps, pdf } = mergedProps, otherProps = __rest(mergedProps, ["className", "inputRef", "onItemClick", "onLoadError", "onLoadSuccess", "pdf"]);
invariant(pdf, 'Attempted to load an outline, but no document was specified. Wrap <Outline /> in a <Document /> or pass explicit `pdf` prop.');
const [outlineState, outlineDispatch] = useResolver();
const { value: outline, error: outlineError } = outlineState;
/**
* Called when an outline is read successfully
*/
function onLoadSuccess() {
if (typeof outline === 'undefined' || outline === false) {
return;
}
if (onLoadSuccessProps) {
onLoadSuccessProps(outline);
}
}
/**
* Called when an outline failed to read successfully
*/
function onLoadError() {
if (!outlineError) {
// Impossible, but TypeScript doesn't know that
return;
}
warning(false, outlineError.toString());
if (onLoadErrorProps) {
onLoadErrorProps(outlineError);
}
}
// biome-ignore lint/correctness/useExhaustiveDependencies: useEffect intentionally triggered on pdf change
useEffect(function resetOutline() {
outlineDispatch({ type: 'RESET' });
}, [outlineDispatch, pdf]);
useEffect(function loadOutline() {
if (!pdf) {
// Impossible, but TypeScript doesn't know that
return;
}
const cancellable = makeCancellable(pdf.getOutline());
const runningTask = cancellable;
cancellable.promise
.then((nextOutline) => {
outlineDispatch({ type: 'RESOLVE', value: nextOutline });
})
.catch((error) => {
outlineDispatch({ type: 'REJECT', error });
});
return () => cancelRunningTask(runningTask);
}, [outlineDispatch, pdf]);
// biome-ignore lint/correctness/useExhaustiveDependencies: Ommitted callbacks so they are not called every time they change
useEffect(() => {
if (outline === undefined) {
return;
}
if (outline === false) {
onLoadError();
return;
}
onLoadSuccess();
}, [outline]);
const childContext = useMemo(() => ({
onItemClick,
}), [onItemClick]);
const eventProps = useMemo(() => makeEventProps(otherProps, () => outline),
// biome-ignore lint/correctness/useExhaustiveDependencies: FIXME
[otherProps, outline]);
if (!outline) {
return null;
}
function renderOutline() {
if (!outline) {
return null;
}
return (_jsx("ul", { children: outline.map((item, itemIndex) => (_jsx(OutlineItem, { item: item, pdf: pdf }, typeof item.dest === 'string' ? item.dest : itemIndex))) }));
}
return (_jsx("div", Object.assign({ className: clsx('react-pdf__Outline', className), ref: inputRef }, eventProps, { children: _jsx(OutlineContext.Provider, { value: childContext, children: renderOutline() }) })));
}

3
node_modules/react-pdf/dist/esm/OutlineContext.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
import type { OutlineContextType } from './shared/types.js';
declare const outlineContext: React.Context<OutlineContextType>;
export default outlineContext;

4
node_modules/react-pdf/dist/esm/OutlineContext.js generated vendored Normal file
View File

@@ -0,0 +1,4 @@
'use client';
import { createContext } from 'react';
const outlineContext = createContext(null);
export default outlineContext;

9
node_modules/react-pdf/dist/esm/OutlineItem.d.ts generated vendored Normal file
View File

@@ -0,0 +1,9 @@
import type { PDFDocumentProxy } from 'pdfjs-dist';
type PDFOutline = Awaited<ReturnType<PDFDocumentProxy['getOutline']>>;
type PDFOutlineItem = PDFOutline[number];
type OutlineItemProps = {
item: PDFOutlineItem;
pdf?: PDFDocumentProxy | false;
};
export default function OutlineItem(props: OutlineItemProps): React.ReactElement;
export {};

76
node_modules/react-pdf/dist/esm/OutlineItem.js generated vendored Normal file
View File

@@ -0,0 +1,76 @@
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import invariant from 'tiny-invariant';
import Ref from './Ref.js';
import useCachedValue from './shared/hooks/useCachedValue.js';
import useDocumentContext from './shared/hooks/useDocumentContext.js';
import useOutlineContext from './shared/hooks/useOutlineContext.js';
export default function OutlineItem(props) {
const documentContext = useDocumentContext();
const outlineContext = useOutlineContext();
invariant(outlineContext, 'Unable to find Outline context.');
const mergedProps = Object.assign(Object.assign(Object.assign({}, documentContext), outlineContext), props);
const { item, linkService, onItemClick, pdf } = mergedProps, otherProps = __rest(mergedProps, ["item", "linkService", "onItemClick", "pdf"]);
invariant(pdf, 'Attempted to load an outline, but no document was specified. Wrap <Outline /> in a <Document /> or pass explicit `pdf` prop.');
const getDestination = useCachedValue(() => {
if (typeof item.dest === 'string') {
return pdf.getDestination(item.dest);
}
return item.dest;
});
const getPageIndex = useCachedValue(() => __awaiter(this, void 0, void 0, function* () {
const destination = yield getDestination();
if (!destination) {
throw new Error('Destination not found.');
}
const [ref] = destination;
return pdf.getPageIndex(new Ref(ref));
}));
const getPageNumber = useCachedValue(() => __awaiter(this, void 0, void 0, function* () {
const pageIndex = yield getPageIndex();
return pageIndex + 1;
}));
function onClick(event) {
event.preventDefault();
invariant(onItemClick || linkService, 'Either onItemClick callback or linkService must be defined in order to navigate to an outline item.');
if (onItemClick) {
Promise.all([getDestination(), getPageIndex(), getPageNumber()]).then(([dest, pageIndex, pageNumber]) => {
onItemClick({
dest,
pageIndex,
pageNumber,
});
});
}
else if (linkService) {
linkService.goToDestination(item.dest);
}
}
function renderSubitems() {
if (!item.items || !item.items.length) {
return null;
}
const { items: subitems } = item;
return (_jsx("ul", { children: subitems.map((subitem, subitemIndex) => (_jsx(OutlineItem, Object.assign({ item: subitem, pdf: pdf }, otherProps), typeof subitem.dest === 'string' ? subitem.dest : subitemIndex))) }));
}
return (_jsxs("li", { children: [_jsx("a", { href: "#", onClick: onClick, children: item.title }), renderSubitems()] }));
}

256
node_modules/react-pdf/dist/esm/Page.d.ts generated vendored Normal file
View File

@@ -0,0 +1,256 @@
import type { PDFDocumentProxy } from 'pdfjs-dist';
import type { EventProps } from 'make-event-props';
import type { ClassName, CustomRenderer, CustomTextRenderer, NodeOrRenderer, OnGetAnnotationsError, OnGetAnnotationsSuccess, OnGetStructTreeError, OnGetStructTreeSuccess, OnGetTextError, OnGetTextSuccess, OnPageLoadError, OnPageLoadSuccess, OnRenderAnnotationLayerError, OnRenderAnnotationLayerSuccess, OnRenderError, OnRenderSuccess, OnRenderTextLayerError, OnRenderTextLayerSuccess, PageCallback, RenderMode } from './shared/types.js';
export type PageProps = {
_className?: string;
_enableRegisterUnregisterPage?: boolean;
/**
* Canvas background color. Any valid `canvas.fillStyle` can be used.
*
* @example 'transparent'
*/
canvasBackground?: string;
/**
* A prop that behaves like [ref](https://reactjs.org/docs/refs-and-the-dom.html), but it's passed to `<canvas>` rendered by `<PageCanvas>` component.
*
* @example (ref) => { this.myCanvas = ref; }
* @example this.ref
* @example ref
*/
canvasRef?: React.Ref<HTMLCanvasElement>;
children?: React.ReactNode;
/**
* Class name(s) that will be added to rendered element along with the default `react-pdf__Page`.
*
* @example 'custom-class-name-1 custom-class-name-2'
* @example ['custom-class-name-1', 'custom-class-name-2']
*/
className?: ClassName;
/**
* Function that customizes how a page is rendered. You must set `renderMode` to `"custom"` to use this prop.
*
* @example MyCustomRenderer
*/
customRenderer?: CustomRenderer;
/**
* Function that customizes how a text layer is rendered.
*
* @example ({ str, itemIndex }) => str.replace(/ipsum/g, value => `<mark>${value}</mark>`)
*/
customTextRenderer?: CustomTextRenderer;
/**
* The ratio between physical pixels and device-independent pixels (DIPs) on the current device.
*
* @default window.devicePixelRatio
* @example 1
*/
devicePixelRatio?: number;
/**
* What the component should display in case of an error.
*
* @default 'Failed to load the page.'
* @example 'An error occurred!'
* @example <p>An error occurred!</p>
* @example this.renderError
*/
error?: NodeOrRenderer;
/**
* Page height. If neither `height` nor `width` are defined, page will be rendered at the size defined in PDF. If you define `width` and `height` at the same time, `height` will be ignored. If you define `height` and `scale` at the same time, the height will be multiplied by a given factor.
*
* @example 300
*/
height?: number;
/**
* The path used to prefix the src attributes of annotation SVGs.
*
* @default ''
* @example '/public/images/'
*/
imageResourcesPath?: string;
/**
* A prop that behaves like [ref](https://reactjs.org/docs/refs-and-the-dom.html), but it's passed to main `<div>` rendered by `<Page>` component.
*
* @example (ref) => { this.myPage = ref; }
* @example this.ref
* @example ref
*/
inputRef?: React.Ref<HTMLDivElement | null>;
/**
* What the component should display while loading.
*
* @default 'Loading page…'
* @example 'Please wait!'
* @example <p>Please wait!</p>
* @example this.renderLoader
*/
loading?: NodeOrRenderer;
/**
* What the component should display in case of no data.
*
* @default 'No page specified.'
* @example 'Please select a page.'
* @example <p>Please select a page.</p>
* @example this.renderNoData
*/
noData?: NodeOrRenderer;
/**
* Function called in case of an error while loading annotations.
*
* @example (error) => alert('Error while loading annotations! ' + error.message)
*/
onGetAnnotationsError?: OnGetAnnotationsError;
/**
* Function called when annotations are successfully loaded.
*
* @example (annotations) => alert('Now displaying ' + annotations.length + ' annotations!')
*/
onGetAnnotationsSuccess?: OnGetAnnotationsSuccess;
/**
* Function called in case of an error while loading structure tree.
*
* @example (error) => alert('Error while loading structure tree! ' + error.message)
*/
onGetStructTreeError?: OnGetStructTreeError;
/**
* Function called when structure tree is successfully loaded.
*
* @example (structTree) => alert(JSON.stringify(structTree))
*/
onGetStructTreeSuccess?: OnGetStructTreeSuccess;
/**
* Function called in case of an error while loading text layer items.
*
* @example (error) => alert('Error while loading text layer items! ' + error.message)
*/
onGetTextError?: OnGetTextError;
/**
* Function called when text layer items are successfully loaded.
*
* @example ({ items, styles }) => alert('Now displaying ' + items.length + ' text layer items!')
*/
onGetTextSuccess?: OnGetTextSuccess;
/**
* Function called in case of an error while loading the page.
*
* @example (error) => alert('Error while loading page! ' + error.message)
*/
onLoadError?: OnPageLoadError;
/**
* Function called when the page is successfully loaded.
*
* @example (page) => alert('Now displaying a page number ' + page.pageNumber + '!')
*/
onLoadSuccess?: OnPageLoadSuccess;
/**
* Function called in case of an error while rendering the annotation layer.
*
* @example (error) => alert('Error while rendering annotation layer! ' + error.message)
*/
onRenderAnnotationLayerError?: OnRenderAnnotationLayerError;
/**
* Function called when annotations are successfully rendered on the screen.
*
* @example () => alert('Rendered the annotation layer!')
*/
onRenderAnnotationLayerSuccess?: OnRenderAnnotationLayerSuccess;
/**
* Function called in case of an error while rendering the page.
*
* @example (error) => alert('Error while loading page! ' + error.message)
*/
onRenderError?: OnRenderError;
/**
* Function called when the page is successfully rendered on the screen.
*
* @example () => alert('Rendered the page!')
*/
onRenderSuccess?: OnRenderSuccess;
/**
* Function called in case of an error while rendering the text layer.
*
* @example (error) => alert('Error while rendering text layer! ' + error.message)
*/
onRenderTextLayerError?: OnRenderTextLayerError;
/**
* Function called when the text layer is successfully rendered on the screen.
*
* @example () => alert('Rendered the text layer!')
*/
onRenderTextLayerSuccess?: OnRenderTextLayerSuccess;
/**
* Which page from PDF file should be displayed, by page index. Ignored if `pageNumber` prop is provided.
*
* @default 0
* @example 1
*/
pageIndex?: number;
/**
* Which page from PDF file should be displayed, by page number. If provided, `pageIndex` prop will be ignored.
*
* @default 1
* @example 2
*/
pageNumber?: number;
/**
* pdf object obtained from `<Document />`'s `onLoadSuccess` callback function.
*
* @example pdf
*/
pdf?: PDFDocumentProxy | false;
registerPage?: undefined;
/**
* Whether annotations (e.g. links) should be rendered.
*
* @default true
* @example false
*/
renderAnnotationLayer?: boolean;
/**
* Whether forms should be rendered. `renderAnnotationLayer` prop must be set to `true`.
*
* @default false
* @example true
*/
renderForms?: boolean;
/**
* Rendering mode of the document. Can be `"canvas"`, `"custom"` or `"none"`. If set to `"custom"`, `customRenderer` must also be provided.
*
* @default 'canvas'
* @example 'custom'
*/
renderMode?: RenderMode;
/**
* Whether a text layer should be rendered.
*
* @default true
* @example false
*/
renderTextLayer?: boolean;
/**
* Rotation of the page in degrees. `90` = rotated to the right, `180` = upside down, `270` = rotated to the left.
*
* @default 0
* @example 90
*/
rotate?: number | null;
/**
* Page scale.
*
* @default 1
* @example 0.5
*/
scale?: number;
unregisterPage?: undefined;
/**
* Page width. If neither `height` nor `width` are defined, page will be rendered at the size defined in PDF. If you define `width` and `height` at the same time, `height` will be ignored. If you define `width` and `scale` at the same time, the width will be multiplied by a given factor.
*
* @example 300
*/
width?: number;
} & EventProps<PageCallback | false | undefined>;
/**
* Displays a page.
*
* Should be placed inside `<Document />`. Alternatively, it can have `pdf` prop passed, which can be obtained from `<Document />`'s `onLoadSuccess` callback function, however some advanced functions like linking between pages inside a document may not be working correctly.
*/
export default function Page(props: PageProps): React.ReactElement;

246
node_modules/react-pdf/dist/esm/Page.js generated vendored Normal file
View File

@@ -0,0 +1,246 @@
'use client';
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useMemo, useRef } from 'react';
import makeCancellable from 'make-cancellable-promise';
import makeEventProps from 'make-event-props';
import clsx from 'clsx';
import mergeRefs from 'merge-refs';
import invariant from 'tiny-invariant';
import warning from 'warning';
import PageContext from './PageContext.js';
import Message from './Message.js';
import Canvas from './Page/Canvas.js';
import TextLayer from './Page/TextLayer.js';
import AnnotationLayer from './Page/AnnotationLayer.js';
import { cancelRunningTask, isProvided, makePageCallback } from './shared/utils.js';
import useDocumentContext from './shared/hooks/useDocumentContext.js';
import useResolver from './shared/hooks/useResolver.js';
const defaultScale = 1;
/**
* Displays a page.
*
* Should be placed inside `<Document />`. Alternatively, it can have `pdf` prop passed, which can be obtained from `<Document />`'s `onLoadSuccess` callback function, however some advanced functions like linking between pages inside a document may not be working correctly.
*/
export default function Page(props) {
const documentContext = useDocumentContext();
const mergedProps = Object.assign(Object.assign({}, documentContext), props);
const { _className = 'react-pdf__Page', _enableRegisterUnregisterPage = true, canvasBackground, canvasRef, children, className, customRenderer: CustomRenderer, customTextRenderer, devicePixelRatio, error = 'Failed to load the page.', height, inputRef, loading = 'Loading page…', noData = 'No page specified.', onGetAnnotationsError: onGetAnnotationsErrorProps, onGetAnnotationsSuccess: onGetAnnotationsSuccessProps, onGetStructTreeError: onGetStructTreeErrorProps, onGetStructTreeSuccess: onGetStructTreeSuccessProps, onGetTextError: onGetTextErrorProps, onGetTextSuccess: onGetTextSuccessProps, onLoadError: onLoadErrorProps, onLoadSuccess: onLoadSuccessProps, onRenderAnnotationLayerError: onRenderAnnotationLayerErrorProps, onRenderAnnotationLayerSuccess: onRenderAnnotationLayerSuccessProps, onRenderError: onRenderErrorProps, onRenderSuccess: onRenderSuccessProps, onRenderTextLayerError: onRenderTextLayerErrorProps, onRenderTextLayerSuccess: onRenderTextLayerSuccessProps, pageIndex: pageIndexProps, pageNumber: pageNumberProps, pdf, registerPage, renderAnnotationLayer: renderAnnotationLayerProps = true, renderForms = false, renderMode = 'canvas', renderTextLayer: renderTextLayerProps = true, rotate: rotateProps, scale: scaleProps = defaultScale, unregisterPage, width } = mergedProps, otherProps = __rest(mergedProps, ["_className", "_enableRegisterUnregisterPage", "canvasBackground", "canvasRef", "children", "className", "customRenderer", "customTextRenderer", "devicePixelRatio", "error", "height", "inputRef", "loading", "noData", "onGetAnnotationsError", "onGetAnnotationsSuccess", "onGetStructTreeError", "onGetStructTreeSuccess", "onGetTextError", "onGetTextSuccess", "onLoadError", "onLoadSuccess", "onRenderAnnotationLayerError", "onRenderAnnotationLayerSuccess", "onRenderError", "onRenderSuccess", "onRenderTextLayerError", "onRenderTextLayerSuccess", "pageIndex", "pageNumber", "pdf", "registerPage", "renderAnnotationLayer", "renderForms", "renderMode", "renderTextLayer", "rotate", "scale", "unregisterPage", "width"]);
const [pageState, pageDispatch] = useResolver();
const { value: page, error: pageError } = pageState;
const pageElement = useRef(null);
invariant(pdf, 'Attempted to load a page, but no document was specified. Wrap <Page /> in a <Document /> or pass explicit `pdf` prop.');
const pageIndex = isProvided(pageNumberProps) ? pageNumberProps - 1 : (pageIndexProps !== null && pageIndexProps !== void 0 ? pageIndexProps : null);
const pageNumber = pageNumberProps !== null && pageNumberProps !== void 0 ? pageNumberProps : (isProvided(pageIndexProps) ? pageIndexProps + 1 : null);
const rotate = rotateProps !== null && rotateProps !== void 0 ? rotateProps : (page ? page.rotate : null);
const scale = useMemo(() => {
if (!page) {
return null;
}
// Be default, we'll render page at 100% * scale width.
let pageScale = 1;
// Passing scale explicitly null would cause the page not to render
const scaleWithDefault = scaleProps !== null && scaleProps !== void 0 ? scaleProps : defaultScale;
// If width/height is defined, calculate the scale of the page so it could be of desired width.
if (width || height) {
const viewport = page.getViewport({ scale: 1, rotation: rotate });
if (width) {
pageScale = width / viewport.width;
}
else if (height) {
pageScale = height / viewport.height;
}
}
return scaleWithDefault * pageScale;
}, [height, page, rotate, scaleProps, width]);
// biome-ignore lint/correctness/useExhaustiveDependencies: useEffect intentionally triggered on pdf change
useEffect(function hook() {
return () => {
if (!isProvided(pageIndex)) {
// Impossible, but TypeScript doesn't know that
return;
}
if (_enableRegisterUnregisterPage && unregisterPage) {
unregisterPage(pageIndex);
}
};
}, [_enableRegisterUnregisterPage, pdf, pageIndex, unregisterPage]);
/**
* Called when a page is loaded successfully
*/
function onLoadSuccess() {
if (onLoadSuccessProps) {
if (!page || !scale) {
// Impossible, but TypeScript doesn't know that
return;
}
onLoadSuccessProps(makePageCallback(page, scale));
}
if (_enableRegisterUnregisterPage && registerPage) {
if (!isProvided(pageIndex) || !pageElement.current) {
// Impossible, but TypeScript doesn't know that
return;
}
registerPage(pageIndex, pageElement.current);
}
}
/**
* Called when a page failed to load
*/
function onLoadError() {
if (!pageError) {
// Impossible, but TypeScript doesn't know that
return;
}
warning(false, pageError.toString());
if (onLoadErrorProps) {
onLoadErrorProps(pageError);
}
}
// biome-ignore lint/correctness/useExhaustiveDependencies: useEffect intentionally triggered on pdf and pageIndex change
useEffect(function resetPage() {
pageDispatch({ type: 'RESET' });
}, [pageDispatch, pdf, pageIndex]);
useEffect(function loadPage() {
if (!pdf || !pageNumber) {
return;
}
const cancellable = makeCancellable(pdf.getPage(pageNumber));
const runningTask = cancellable;
cancellable.promise
.then((nextPage) => {
pageDispatch({ type: 'RESOLVE', value: nextPage });
})
.catch((error) => {
pageDispatch({ type: 'REJECT', error });
});
return () => cancelRunningTask(runningTask);
}, [pageDispatch, pdf, pageNumber]);
// biome-ignore lint/correctness/useExhaustiveDependencies: Ommitted callbacks so they are not called every time they change
useEffect(() => {
if (page === undefined) {
return;
}
if (page === false) {
onLoadError();
return;
}
onLoadSuccess();
}, [page, scale]);
const childContext = useMemo(() =>
// Technically there cannot be page without pageIndex, pageNumber, rotate and scale, but TypeScript doesn't know that
page && isProvided(pageIndex) && pageNumber && isProvided(rotate) && isProvided(scale)
? {
_className,
canvasBackground,
customTextRenderer,
devicePixelRatio,
onGetAnnotationsError: onGetAnnotationsErrorProps,
onGetAnnotationsSuccess: onGetAnnotationsSuccessProps,
onGetStructTreeError: onGetStructTreeErrorProps,
onGetStructTreeSuccess: onGetStructTreeSuccessProps,
onGetTextError: onGetTextErrorProps,
onGetTextSuccess: onGetTextSuccessProps,
onRenderAnnotationLayerError: onRenderAnnotationLayerErrorProps,
onRenderAnnotationLayerSuccess: onRenderAnnotationLayerSuccessProps,
onRenderError: onRenderErrorProps,
onRenderSuccess: onRenderSuccessProps,
onRenderTextLayerError: onRenderTextLayerErrorProps,
onRenderTextLayerSuccess: onRenderTextLayerSuccessProps,
page,
pageIndex,
pageNumber,
renderForms,
renderTextLayer: renderTextLayerProps,
rotate,
scale,
}
: null, [
_className,
canvasBackground,
customTextRenderer,
devicePixelRatio,
onGetAnnotationsErrorProps,
onGetAnnotationsSuccessProps,
onGetStructTreeErrorProps,
onGetStructTreeSuccessProps,
onGetTextErrorProps,
onGetTextSuccessProps,
onRenderAnnotationLayerErrorProps,
onRenderAnnotationLayerSuccessProps,
onRenderErrorProps,
onRenderSuccessProps,
onRenderTextLayerErrorProps,
onRenderTextLayerSuccessProps,
page,
pageIndex,
pageNumber,
renderForms,
renderTextLayerProps,
rotate,
scale,
]);
const eventProps = useMemo(() => makeEventProps(otherProps, () => page ? (scale ? makePageCallback(page, scale) : undefined) : page),
// biome-ignore lint/correctness/useExhaustiveDependencies: FIXME
[otherProps, page, scale]);
const pageKey = `${pageIndex}@${scale}/${rotate}`;
function renderMainLayer() {
switch (renderMode) {
case 'custom': {
invariant(CustomRenderer, `renderMode was set to "custom", but no customRenderer was passed.`);
return _jsx(CustomRenderer, {}, `${pageKey}_custom`);
}
case 'none':
return null;
case 'canvas':
default:
return _jsx(Canvas, { canvasRef: canvasRef }, `${pageKey}_canvas`);
}
}
function renderTextLayer() {
if (!renderTextLayerProps) {
return null;
}
return _jsx(TextLayer, {}, `${pageKey}_text`);
}
function renderAnnotationLayer() {
if (!renderAnnotationLayerProps) {
return null;
}
return _jsx(AnnotationLayer, {}, `${pageKey}_annotations`);
}
function renderChildren() {
return (_jsxs(PageContext.Provider, { value: childContext, children: [renderMainLayer(), renderTextLayer(), renderAnnotationLayer(), children] }));
}
function renderContent() {
if (!pageNumber) {
return _jsx(Message, { type: "no-data", children: typeof noData === 'function' ? noData() : noData });
}
if (pdf === null || page === undefined || page === null) {
return (_jsx(Message, { type: "loading", children: typeof loading === 'function' ? loading() : loading }));
}
if (pdf === false || page === false) {
return _jsx(Message, { type: "error", children: typeof error === 'function' ? error() : error });
}
return renderChildren();
}
return (_jsx("div", Object.assign({ className: clsx(_className, className), "data-page-number": pageNumber,
// Assertion is needed for React 18 compatibility
ref: mergeRefs(inputRef, pageElement), style: {
['--scale-factor']: `${scale}`,
backgroundColor: canvasBackground || 'white',
position: 'relative',
minWidth: 'min-content',
minHeight: 'min-content',
} }, eventProps, { children: renderContent() })));
}

View File

@@ -0,0 +1,333 @@
/* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
:root {
--react-pdf-annotation-layer: 1;
--annotation-unfocused-field-background: url("data:image/svg+xml;charset=UTF-8,<svg width='1px' height='1px' xmlns='http://www.w3.org/2000/svg'><rect width='100%' height='100%' style='fill:rgba(0, 54, 255, 0.13);'/></svg>");
--input-focus-border-color: Highlight;
--input-focus-outline: 1px solid Canvas;
--input-unfocused-border-color: transparent;
--input-disabled-border-color: transparent;
--input-hover-border-color: black;
--link-outline: none;
}
@media screen and (forced-colors: active) {
:root {
--input-focus-border-color: CanvasText;
--input-unfocused-border-color: ActiveText;
--input-disabled-border-color: GrayText;
--input-hover-border-color: Highlight;
--link-outline: 1.5px solid LinkText;
}
.annotationLayer .textWidgetAnnotation :is(input, textarea):required,
.annotationLayer .choiceWidgetAnnotation select:required,
.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input:required {
outline: 1.5px solid selectedItem;
}
.annotationLayer .linkAnnotation:hover {
backdrop-filter: invert(100%);
}
}
.annotationLayer {
position: absolute;
top: 0;
left: 0;
pointer-events: none;
transform-origin: 0 0;
z-index: 3;
}
.annotationLayer[data-main-rotation='90'] .norotate {
transform: rotate(270deg) translateX(-100%);
}
.annotationLayer[data-main-rotation='180'] .norotate {
transform: rotate(180deg) translate(-100%, -100%);
}
.annotationLayer[data-main-rotation='270'] .norotate {
transform: rotate(90deg) translateY(-100%);
}
.annotationLayer canvas {
position: absolute;
width: 100%;
height: 100%;
}
.annotationLayer section {
position: absolute;
text-align: initial;
pointer-events: auto;
box-sizing: border-box;
margin: 0;
transform-origin: 0 0;
}
.annotationLayer .linkAnnotation {
outline: var(--link-outline);
}
.textLayer.selecting ~ .annotationLayer section {
pointer-events: none;
}
.annotationLayer :is(.linkAnnotation, .buttonWidgetAnnotation.pushButton) > a {
position: absolute;
font-size: 1em;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.annotationLayer :is(.linkAnnotation, .buttonWidgetAnnotation.pushButton) > a:hover {
opacity: 0.2;
background: rgba(255, 255, 0, 1);
box-shadow: 0 2px 10px rgba(255, 255, 0, 1);
}
.annotationLayer .textAnnotation img {
position: absolute;
cursor: pointer;
width: 100%;
height: 100%;
top: 0;
left: 0;
}
.annotationLayer .textWidgetAnnotation :is(input, textarea),
.annotationLayer .choiceWidgetAnnotation select,
.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input {
background-image: var(--annotation-unfocused-field-background);
border: 2px solid var(--input-unfocused-border-color);
box-sizing: border-box;
font: calc(9px * var(--scale-factor)) sans-serif;
height: 100%;
margin: 0;
vertical-align: top;
width: 100%;
}
.annotationLayer .textWidgetAnnotation :is(input, textarea):required,
.annotationLayer .choiceWidgetAnnotation select:required,
.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input:required {
outline: 1.5px solid red;
}
.annotationLayer .choiceWidgetAnnotation select option {
padding: 0;
}
.annotationLayer .buttonWidgetAnnotation.radioButton input {
border-radius: 50%;
}
.annotationLayer .textWidgetAnnotation textarea {
resize: none;
}
.annotationLayer .textWidgetAnnotation :is(input, textarea)[disabled],
.annotationLayer .choiceWidgetAnnotation select[disabled],
.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input[disabled] {
background: none;
border: 2px solid var(--input-disabled-border-color);
cursor: not-allowed;
}
.annotationLayer .textWidgetAnnotation :is(input, textarea):hover,
.annotationLayer .choiceWidgetAnnotation select:hover,
.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input:hover {
border: 2px solid var(--input-hover-border-color);
}
.annotationLayer .textWidgetAnnotation :is(input, textarea):hover,
.annotationLayer .choiceWidgetAnnotation select:hover,
.annotationLayer .buttonWidgetAnnotation.checkBox input:hover {
border-radius: 2px;
}
.annotationLayer .textWidgetAnnotation :is(input, textarea):focus,
.annotationLayer .choiceWidgetAnnotation select:focus {
background: none;
border: 2px solid var(--input-focus-border-color);
border-radius: 2px;
outline: var(--input-focus-outline);
}
.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) :focus {
background-image: none;
background-color: transparent;
}
.annotationLayer .buttonWidgetAnnotation.checkBox :focus {
border: 2px solid var(--input-focus-border-color);
border-radius: 2px;
outline: var(--input-focus-outline);
}
.annotationLayer .buttonWidgetAnnotation.radioButton :focus {
border: 2px solid var(--input-focus-border-color);
outline: var(--input-focus-outline);
}
.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before,
.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after,
.annotationLayer .buttonWidgetAnnotation.radioButton input:checked::before {
background-color: CanvasText;
content: '';
display: block;
position: absolute;
}
.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before,
.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after {
height: 80%;
left: 45%;
width: 1px;
}
.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before {
transform: rotate(45deg);
}
.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after {
transform: rotate(-45deg);
}
.annotationLayer .buttonWidgetAnnotation.radioButton input:checked::before {
border-radius: 50%;
height: 50%;
left: 30%;
top: 20%;
width: 50%;
}
.annotationLayer .textWidgetAnnotation input.comb {
font-family: monospace;
padding-left: 2px;
padding-right: 0;
}
.annotationLayer .textWidgetAnnotation input.comb:focus {
/*
* Letter spacing is placed on the right side of each character. Hence, the
* letter spacing of the last character may be placed outside the visible
* area, causing horizontal scrolling. We avoid this by extending the width
* when the element has focus and revert this when it loses focus.
*/
width: 103%;
}
.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input {
appearance: none;
}
.annotationLayer .popupTriggerArea {
height: 100%;
width: 100%;
}
.annotationLayer .fileAttachmentAnnotation .popupTriggerArea {
position: absolute;
}
.annotationLayer .popupWrapper {
position: absolute;
font-size: calc(9px * var(--scale-factor));
width: 100%;
min-width: calc(180px * var(--scale-factor));
pointer-events: none;
}
.annotationLayer .popup {
position: absolute;
max-width: calc(180px * var(--scale-factor));
background-color: rgba(255, 255, 153, 1);
box-shadow: 0 calc(2px * var(--scale-factor)) calc(5px * var(--scale-factor))
rgba(136, 136, 136, 1);
border-radius: calc(2px * var(--scale-factor));
padding: calc(6px * var(--scale-factor));
margin-left: calc(5px * var(--scale-factor));
cursor: pointer;
font: message-box;
white-space: normal;
word-wrap: break-word;
pointer-events: auto;
}
.annotationLayer .popup > * {
font-size: calc(9px * var(--scale-factor));
}
.annotationLayer .popup h1 {
display: inline-block;
}
.annotationLayer .popupDate {
display: inline-block;
margin-left: calc(5px * var(--scale-factor));
}
.annotationLayer .popupContent {
border-top: 1px solid rgba(51, 51, 51, 1);
margin-top: calc(2px * var(--scale-factor));
padding-top: calc(2px * var(--scale-factor));
}
.annotationLayer .richText > * {
white-space: pre-wrap;
font-size: calc(9px * var(--scale-factor));
}
.annotationLayer .highlightAnnotation,
.annotationLayer .underlineAnnotation,
.annotationLayer .squigglyAnnotation,
.annotationLayer .strikeoutAnnotation,
.annotationLayer .freeTextAnnotation,
.annotationLayer .lineAnnotation svg line,
.annotationLayer .squareAnnotation svg rect,
.annotationLayer .circleAnnotation svg ellipse,
.annotationLayer .polylineAnnotation svg polyline,
.annotationLayer .polygonAnnotation svg polygon,
.annotationLayer .caretAnnotation,
.annotationLayer .inkAnnotation svg polyline,
.annotationLayer .stampAnnotation,
.annotationLayer .fileAttachmentAnnotation {
cursor: pointer;
}
.annotationLayer section svg {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
}
.annotationLayer .annotationTextContent {
position: absolute;
width: 100%;
height: 100%;
opacity: 0;
color: transparent;
user-select: none;
pointer-events: none;
}
.annotationLayer .annotationTextContent span {
width: 100%;
display: inline-block;
}

View File

@@ -0,0 +1 @@
export default function AnnotationLayer(): React.ReactElement;

133
node_modules/react-pdf/dist/esm/Page/AnnotationLayer.js generated vendored Normal file
View File

@@ -0,0 +1,133 @@
'use client';
import { jsx as _jsx } from "react/jsx-runtime";
import { useEffect, useMemo, useRef } from 'react';
import makeCancellable from 'make-cancellable-promise';
import clsx from 'clsx';
import invariant from 'tiny-invariant';
import warning from 'warning';
import * as pdfjs from 'pdfjs-dist';
import useDocumentContext from '../shared/hooks/useDocumentContext.js';
import usePageContext from '../shared/hooks/usePageContext.js';
import useResolver from '../shared/hooks/useResolver.js';
import { cancelRunningTask } from '../shared/utils.js';
export default function AnnotationLayer() {
const documentContext = useDocumentContext();
const pageContext = usePageContext();
invariant(pageContext, 'Unable to find Page context.');
const mergedProps = Object.assign(Object.assign({}, documentContext), pageContext);
const { imageResourcesPath, linkService, onGetAnnotationsError: onGetAnnotationsErrorProps, onGetAnnotationsSuccess: onGetAnnotationsSuccessProps, onRenderAnnotationLayerError: onRenderAnnotationLayerErrorProps, onRenderAnnotationLayerSuccess: onRenderAnnotationLayerSuccessProps, page, pdf, renderForms, rotate, scale = 1, } = mergedProps;
invariant(pdf, 'Attempted to load page annotations, but no document was specified. Wrap <Page /> in a <Document /> or pass explicit `pdf` prop.');
invariant(page, 'Attempted to load page annotations, but no page was specified.');
invariant(linkService, 'Attempted to load page annotations, but no linkService was specified.');
const [annotationsState, annotationsDispatch] = useResolver();
const { value: annotations, error: annotationsError } = annotationsState;
const layerElement = useRef(null);
warning(Number.parseInt(window.getComputedStyle(document.body).getPropertyValue('--react-pdf-annotation-layer'), 10) === 1, 'AnnotationLayer styles not found. Read more: https://github.com/wojtekmaj/react-pdf#support-for-annotations');
function onLoadSuccess() {
if (!annotations) {
// Impossible, but TypeScript doesn't know that
return;
}
if (onGetAnnotationsSuccessProps) {
onGetAnnotationsSuccessProps(annotations);
}
}
function onLoadError() {
if (!annotationsError) {
// Impossible, but TypeScript doesn't know that
return;
}
warning(false, annotationsError.toString());
if (onGetAnnotationsErrorProps) {
onGetAnnotationsErrorProps(annotationsError);
}
}
// biome-ignore lint/correctness/useExhaustiveDependencies: useEffect intentionally triggered on page change
useEffect(function resetAnnotations() {
annotationsDispatch({ type: 'RESET' });
}, [annotationsDispatch, page]);
useEffect(function loadAnnotations() {
if (!page) {
return;
}
const cancellable = makeCancellable(page.getAnnotations());
const runningTask = cancellable;
cancellable.promise
.then((nextAnnotations) => {
annotationsDispatch({ type: 'RESOLVE', value: nextAnnotations });
})
.catch((error) => {
annotationsDispatch({ type: 'REJECT', error });
});
return () => {
cancelRunningTask(runningTask);
};
}, [annotationsDispatch, page]);
// biome-ignore lint/correctness/useExhaustiveDependencies: Ommitted callbacks so they are not called every time they change
useEffect(() => {
if (annotations === undefined) {
return;
}
if (annotations === false) {
onLoadError();
return;
}
onLoadSuccess();
}, [annotations]);
function onRenderSuccess() {
if (onRenderAnnotationLayerSuccessProps) {
onRenderAnnotationLayerSuccessProps();
}
}
function onRenderError(error) {
warning(false, `${error}`);
if (onRenderAnnotationLayerErrorProps) {
onRenderAnnotationLayerErrorProps(error);
}
}
const viewport = useMemo(() => page.getViewport({ scale, rotation: rotate }), [page, rotate, scale]);
// biome-ignore lint/correctness/useExhaustiveDependencies: Ommitted callbacks so they are not called every time they change
useEffect(function renderAnnotationLayer() {
if (!pdf || !page || !linkService || !annotations) {
return;
}
const { current: layer } = layerElement;
if (!layer) {
return;
}
const clonedViewport = viewport.clone({ dontFlip: true });
const annotationLayerParameters = {
accessibilityManager: null, // TODO: Implement this
annotationCanvasMap: null, // TODO: Implement this
annotationEditorUIManager: null, // TODO: Implement this
div: layer,
l10n: null, // TODO: Implement this
page,
structTreeLayer: null, // TODO: Implement this
viewport: clonedViewport,
};
const renderParameters = {
annotations,
annotationStorage: pdf.annotationStorage,
div: layer,
imageResourcesPath,
linkService,
page,
renderForms,
viewport: clonedViewport,
};
layer.innerHTML = '';
try {
new pdfjs.AnnotationLayer(annotationLayerParameters).render(renderParameters);
// Intentional immediate callback
onRenderSuccess();
}
catch (error) {
onRenderError(error);
}
return () => {
// TODO: Cancel running task?
};
}, [annotations, imageResourcesPath, linkService, page, pdf, renderForms, viewport]);
return (_jsx("div", { className: clsx('react-pdf__Page__annotations', 'annotationLayer'), ref: layerElement }));
}

5
node_modules/react-pdf/dist/esm/Page/Canvas.d.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
type CanvasProps = {
canvasRef?: React.Ref<HTMLCanvasElement>;
};
export default function Canvas(props: CanvasProps): React.ReactElement;
export {};

96
node_modules/react-pdf/dist/esm/Page/Canvas.js generated vendored Normal file
View File

@@ -0,0 +1,96 @@
'use client';
import { jsx as _jsx } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useRef } from 'react';
import mergeRefs from 'merge-refs';
import invariant from 'tiny-invariant';
import warning from 'warning';
import * as pdfjs from 'pdfjs-dist';
import StructTree from '../StructTree.js';
import usePageContext from '../shared/hooks/usePageContext.js';
import { cancelRunningTask, getDevicePixelRatio, isCancelException, makePageCallback, } from '../shared/utils.js';
const ANNOTATION_MODE = pdfjs.AnnotationMode;
export default function Canvas(props) {
const pageContext = usePageContext();
invariant(pageContext, 'Unable to find Page context.');
const mergedProps = Object.assign(Object.assign({}, pageContext), props);
const { _className, canvasBackground, devicePixelRatio = getDevicePixelRatio(), onRenderError: onRenderErrorProps, onRenderSuccess: onRenderSuccessProps, page, renderForms, renderTextLayer, rotate, scale, } = mergedProps;
const { canvasRef } = props;
invariant(page, 'Attempted to render page canvas, but no page was specified.');
const canvasElement = useRef(null);
/**
* Called when a page is rendered successfully.
*/
function onRenderSuccess() {
if (!page) {
// Impossible, but TypeScript doesn't know that
return;
}
if (onRenderSuccessProps) {
onRenderSuccessProps(makePageCallback(page, scale));
}
}
/**
* Called when a page fails to render.
*/
function onRenderError(error) {
if (isCancelException(error)) {
return;
}
warning(false, error.toString());
if (onRenderErrorProps) {
onRenderErrorProps(error);
}
}
const renderViewport = useMemo(() => page.getViewport({ scale: scale * devicePixelRatio, rotation: rotate }), [devicePixelRatio, page, rotate, scale]);
const viewport = useMemo(() => page.getViewport({ scale, rotation: rotate }), [page, rotate, scale]);
// biome-ignore lint/correctness/useExhaustiveDependencies: Ommitted callbacks so they are not called every time they change
useEffect(function drawPageOnCanvas() {
if (!page) {
return;
}
// Ensures the canvas will be re-rendered from scratch. Otherwise all form data will stay.
page.cleanup();
const { current: canvas } = canvasElement;
if (!canvas) {
return;
}
canvas.width = renderViewport.width;
canvas.height = renderViewport.height;
canvas.style.width = `${Math.floor(viewport.width)}px`;
canvas.style.height = `${Math.floor(viewport.height)}px`;
canvas.style.visibility = 'hidden';
const renderContext = {
annotationMode: renderForms ? ANNOTATION_MODE.ENABLE_FORMS : ANNOTATION_MODE.ENABLE,
canvasContext: canvas.getContext('2d', { alpha: false }),
viewport: renderViewport,
};
if (canvasBackground) {
renderContext.background = canvasBackground;
}
const cancellable = page.render(renderContext);
const runningTask = cancellable;
cancellable.promise
.then(() => {
canvas.style.visibility = '';
onRenderSuccess();
})
.catch(onRenderError);
return () => cancelRunningTask(runningTask);
}, [canvasBackground, page, renderForms, renderViewport, viewport]);
const cleanup = useCallback(() => {
const { current: canvas } = canvasElement;
/**
* Zeroing the width and height cause most browsers to release graphics
* resources immediately, which can greatly reduce memory consumption.
*/
if (canvas) {
canvas.width = 0;
canvas.height = 0;
}
}, []);
useEffect(() => cleanup, [cleanup]);
return (_jsx("canvas", { className: `${_className}__canvas`, dir: "ltr", ref: mergeRefs(canvasRef, canvasElement), style: {
display: 'block',
userSelect: 'none',
}, children: renderTextLayer ? _jsx(StructTree, {}) : null }));
}

119
node_modules/react-pdf/dist/esm/Page/TextLayer.css generated vendored Normal file
View File

@@ -0,0 +1,119 @@
/* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
:root {
--react-pdf-text-layer: 1;
--highlight-bg-color: rgba(180, 0, 170, 1);
--highlight-selected-bg-color: rgba(0, 100, 0, 1);
}
@media screen and (forced-colors: active) {
:root {
--highlight-bg-color: Highlight;
--highlight-selected-bg-color: ButtonText;
}
}
[data-main-rotation='90'] {
transform: rotate(90deg) translateY(-100%);
}
[data-main-rotation='180'] {
transform: rotate(180deg) translate(-100%, -100%);
}
[data-main-rotation='270'] {
transform: rotate(270deg) translateX(-100%);
}
.textLayer {
position: absolute;
text-align: initial;
inset: 0;
overflow: hidden;
line-height: 1;
text-size-adjust: none;
forced-color-adjust: none;
transform-origin: 0 0;
z-index: 2;
}
.textLayer :is(span, br) {
color: transparent;
position: absolute;
white-space: pre;
cursor: text;
margin: 0;
transform-origin: 0 0;
}
/* Only necessary in Google Chrome, see issue 14205, and most unfortunately
* the problem doesn't show up in "text" reference tests. */
.textLayer span.markedContent {
top: 0;
height: 0;
}
.textLayer .highlight {
margin: -1px;
padding: 1px;
background-color: var(--highlight-bg-color);
border-radius: 4px;
}
.textLayer .highlight.appended {
position: initial;
}
.textLayer .highlight.begin {
border-radius: 4px 0 0 4px;
}
.textLayer .highlight.end {
border-radius: 0 4px 4px 0;
}
.textLayer .highlight.middle {
border-radius: 0;
}
.textLayer .highlight.selected {
background-color: var(--highlight-selected-bg-color);
}
/* Avoids https://github.com/mozilla/pdf.js/issues/13840 in Chrome */
.textLayer br::selection {
background: transparent;
}
.textLayer .endOfContent {
display: block;
position: absolute;
inset: 100% 0 0;
z-index: -1;
cursor: default;
user-select: none;
}
.textLayer.selecting .endOfContent {
top: 0;
}
.hiddenCanvasElement {
position: absolute;
top: 0;
left: 0;
width: 0;
height: 0;
display: none;
}

1
node_modules/react-pdf/dist/esm/Page/TextLayer.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export default function TextLayer(): React.ReactElement;

168
node_modules/react-pdf/dist/esm/Page/TextLayer.js generated vendored Normal file
View File

@@ -0,0 +1,168 @@
'use client';
import { jsx as _jsx } from "react/jsx-runtime";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from 'react';
import makeCancellable from 'make-cancellable-promise';
import clsx from 'clsx';
import invariant from 'tiny-invariant';
import warning from 'warning';
import * as pdfjs from 'pdfjs-dist';
import usePageContext from '../shared/hooks/usePageContext.js';
import useResolver from '../shared/hooks/useResolver.js';
import { cancelRunningTask } from '../shared/utils.js';
function isTextItem(item) {
return 'str' in item;
}
export default function TextLayer() {
const pageContext = usePageContext();
invariant(pageContext, 'Unable to find Page context.');
const { customTextRenderer, onGetTextError, onGetTextSuccess, onRenderTextLayerError, onRenderTextLayerSuccess, page, pageIndex, pageNumber, rotate, scale, } = pageContext;
invariant(page, 'Attempted to load page text content, but no page was specified.');
const [textContentState, textContentDispatch] = useResolver();
const { value: textContent, error: textContentError } = textContentState;
const layerElement = useRef(null);
warning(Number.parseInt(window.getComputedStyle(document.body).getPropertyValue('--react-pdf-text-layer'), 10) === 1, 'TextLayer styles not found. Read more: https://github.com/wojtekmaj/react-pdf#support-for-text-layer');
/**
* Called when a page text content is read successfully
*/
function onLoadSuccess() {
if (!textContent) {
// Impossible, but TypeScript doesn't know that
return;
}
if (onGetTextSuccess) {
onGetTextSuccess(textContent);
}
}
/**
* Called when a page text content failed to read successfully
*/
function onLoadError() {
if (!textContentError) {
// Impossible, but TypeScript doesn't know that
return;
}
warning(false, textContentError.toString());
if (onGetTextError) {
onGetTextError(textContentError);
}
}
// biome-ignore lint/correctness/useExhaustiveDependencies: useEffect intentionally triggered on page change
useEffect(function resetTextContent() {
textContentDispatch({ type: 'RESET' });
}, [page, textContentDispatch]);
useEffect(function loadTextContent() {
if (!page) {
return;
}
const cancellable = makeCancellable(page.getTextContent());
const runningTask = cancellable;
cancellable.promise
.then((nextTextContent) => {
textContentDispatch({ type: 'RESOLVE', value: nextTextContent });
})
.catch((error) => {
textContentDispatch({ type: 'REJECT', error });
});
return () => cancelRunningTask(runningTask);
}, [page, textContentDispatch]);
// biome-ignore lint/correctness/useExhaustiveDependencies: Ommitted callbacks so they are not called every time they change
useEffect(() => {
if (textContent === undefined) {
return;
}
if (textContent === false) {
onLoadError();
return;
}
onLoadSuccess();
}, [textContent]);
/**
* Called when a text layer is rendered successfully
*/
const onRenderSuccess = useCallback(() => {
if (onRenderTextLayerSuccess) {
onRenderTextLayerSuccess();
}
}, [onRenderTextLayerSuccess]);
/**
* Called when a text layer failed to render successfully
*/
const onRenderError = useCallback((error) => {
warning(false, error.toString());
if (onRenderTextLayerError) {
onRenderTextLayerError(error);
}
}, [onRenderTextLayerError]);
function onMouseDown() {
const layer = layerElement.current;
if (!layer) {
return;
}
layer.classList.add('selecting');
}
function onMouseUp() {
const layer = layerElement.current;
if (!layer) {
return;
}
layer.classList.remove('selecting');
}
const viewport = useMemo(() => page.getViewport({ scale, rotation: rotate }), [page, rotate, scale]);
useLayoutEffect(function renderTextLayer() {
if (!page || !textContent) {
return;
}
const { current: layer } = layerElement;
if (!layer) {
return;
}
layer.innerHTML = '';
const textContentSource = page.streamTextContent({ includeMarkedContent: true });
const parameters = {
container: layer,
textContentSource,
viewport,
};
const cancellable = new pdfjs.TextLayer(parameters);
const runningTask = cancellable;
cancellable
.render()
.then(() => {
const end = document.createElement('div');
end.className = 'endOfContent';
layer.append(end);
const layerChildren = layer.querySelectorAll('[role="presentation"]');
if (customTextRenderer) {
let index = 0;
textContent.items.forEach((item, itemIndex) => {
if (!isTextItem(item)) {
return;
}
const child = layerChildren[index];
if (!child) {
return;
}
const content = customTextRenderer(Object.assign({ pageIndex,
pageNumber,
itemIndex }, item));
child.innerHTML = content;
index += item.str && item.hasEOL ? 2 : 1;
});
}
// Intentional immediate callback
onRenderSuccess();
})
.catch(onRenderError);
return () => cancelRunningTask(runningTask);
}, [
customTextRenderer,
onRenderError,
onRenderSuccess,
page,
pageIndex,
pageNumber,
textContent,
viewport,
]);
return (_jsx("div", { className: clsx('react-pdf__Page__textContent', 'textLayer'), onMouseUp: onMouseUp, onMouseDown: onMouseDown, ref: layerElement }));
}

3
node_modules/react-pdf/dist/esm/PageContext.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
import type { PageContextType } from './shared/types.js';
declare const pageContext: React.Context<PageContextType>;
export default pageContext;

4
node_modules/react-pdf/dist/esm/PageContext.js generated vendored Normal file
View File

@@ -0,0 +1,4 @@
'use client';
import { createContext } from 'react';
const pageContext = createContext(null);
export default pageContext;

View File

@@ -0,0 +1,5 @@
declare const PasswordResponses: {
readonly NEED_PASSWORD: 1;
readonly INCORRECT_PASSWORD: 2;
};
export default PasswordResponses;

6
node_modules/react-pdf/dist/esm/PasswordResponses.js generated vendored Normal file
View File

@@ -0,0 +1,6 @@
// As defined in https://github.com/mozilla/pdf.js/blob/d9fac3459609a807be6506fb3441b5da4b154d14/src/shared/util.js#L371-L374
const PasswordResponses = {
NEED_PASSWORD: 1,
INCORRECT_PASSWORD: 2,
};
export default PasswordResponses;

9
node_modules/react-pdf/dist/esm/Ref.d.ts generated vendored Normal file
View File

@@ -0,0 +1,9 @@
export default class Ref {
num: number;
gen: number;
constructor({ num, gen }: {
num: number;
gen: number;
});
toString(): string;
}

13
node_modules/react-pdf/dist/esm/Ref.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
export default class Ref {
constructor({ num, gen }) {
this.num = num;
this.gen = gen;
}
toString() {
let str = `${this.num}R`;
if (this.gen !== 0) {
str += this.gen;
}
return str;
}
}

1
node_modules/react-pdf/dist/esm/StructTree.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export default function StructTree(): React.ReactElement | null;

74
node_modules/react-pdf/dist/esm/StructTree.js generated vendored Normal file
View File

@@ -0,0 +1,74 @@
import { jsx as _jsx } from "react/jsx-runtime";
import { useEffect } from 'react';
import makeCancellable from 'make-cancellable-promise';
import invariant from 'tiny-invariant';
import warning from 'warning';
import StructTreeItem from './StructTreeItem.js';
import usePageContext from './shared/hooks/usePageContext.js';
import useResolver from './shared/hooks/useResolver.js';
import { cancelRunningTask } from './shared/utils.js';
export default function StructTree() {
const pageContext = usePageContext();
invariant(pageContext, 'Unable to find Page context.');
const { onGetStructTreeError: onGetStructTreeErrorProps, onGetStructTreeSuccess: onGetStructTreeSuccessProps, } = pageContext;
const [structTreeState, structTreeDispatch] = useResolver();
const { value: structTree, error: structTreeError } = structTreeState;
const { customTextRenderer, page } = pageContext;
function onLoadSuccess() {
if (!structTree) {
// Impossible, but TypeScript doesn't know that
return;
}
if (onGetStructTreeSuccessProps) {
onGetStructTreeSuccessProps(structTree);
}
}
function onLoadError() {
if (!structTreeError) {
// Impossible, but TypeScript doesn't know that
return;
}
warning(false, structTreeError.toString());
if (onGetStructTreeErrorProps) {
onGetStructTreeErrorProps(structTreeError);
}
}
// biome-ignore lint/correctness/useExhaustiveDependencies: useEffect intentionally triggered on page change
useEffect(function resetStructTree() {
structTreeDispatch({ type: 'RESET' });
}, [structTreeDispatch, page]);
useEffect(function loadStructTree() {
if (customTextRenderer) {
// TODO: Document why this is necessary
return;
}
if (!page) {
return;
}
const cancellable = makeCancellable(page.getStructTree());
const runningTask = cancellable;
cancellable.promise
.then((nextStructTree) => {
structTreeDispatch({ type: 'RESOLVE', value: nextStructTree });
})
.catch((error) => {
structTreeDispatch({ type: 'REJECT', error });
});
return () => cancelRunningTask(runningTask);
}, [customTextRenderer, page, structTreeDispatch]);
// biome-ignore lint/correctness/useExhaustiveDependencies: Ommitted callbacks so they are not called every time they change
useEffect(() => {
if (structTree === undefined) {
return;
}
if (structTree === false) {
onLoadError();
return;
}
onLoadSuccess();
}, [structTree]);
if (!structTree) {
return null;
}
return _jsx(StructTreeItem, { className: "react-pdf__Page__structTree structTree", node: structTree });
}

8
node_modules/react-pdf/dist/esm/StructTreeItem.d.ts generated vendored Normal file
View File

@@ -0,0 +1,8 @@
import type { StructTreeContent } from 'pdfjs-dist/types/src/display/api.js';
import type { StructTreeNodeWithExtraAttributes } from './shared/types.js';
type StructTreeItemProps = {
className?: string;
node: StructTreeNodeWithExtraAttributes | StructTreeContent;
};
export default function StructTreeItem({ className, node, }: StructTreeItemProps): React.ReactElement;
export {};

20
node_modules/react-pdf/dist/esm/StructTreeItem.js generated vendored Normal file
View File

@@ -0,0 +1,20 @@
import { jsx as _jsx } from "react/jsx-runtime";
import { useMemo } from 'react';
import { getAttributes, isStructTreeNode, isStructTreeNodeWithOnlyContentChild, } from './shared/structTreeUtils.js';
export default function StructTreeItem({ className, node, }) {
const attributes = useMemo(() => getAttributes(node), [node]);
const children = useMemo(() => {
if (!isStructTreeNode(node)) {
return null;
}
if (isStructTreeNodeWithOnlyContentChild(node)) {
return null;
}
return node.children.map((child, index) => {
return (
// biome-ignore lint/suspicious/noArrayIndexKey: index is stable here
_jsx(StructTreeItem, { node: child }, index));
});
}, [node]);
return (_jsx("span", Object.assign({ className: className }, attributes, { children: children })));
}

23
node_modules/react-pdf/dist/esm/Thumbnail.d.ts generated vendored Normal file
View File

@@ -0,0 +1,23 @@
import type { PageProps } from './Page.js';
import type { ClassName, OnItemClickArgs } from './shared/types.js';
export type ThumbnailProps = Omit<PageProps, 'className' | 'customTextRenderer' | 'onGetAnnotationsError' | 'onGetAnnotationsSuccess' | 'onGetTextError' | 'onGetTextSuccess' | 'onRenderAnnotationLayerError' | 'onRenderAnnotationLayerSuccess' | 'onRenderTextLayerError' | 'onRenderTextLayerSuccess' | 'renderAnnotationLayer' | 'renderForms' | 'renderTextLayer'> & {
/**
* Class name(s) that will be added to rendered element along with the default `react-pdf__Thumbnail`.
*
* @example 'custom-class-name-1 custom-class-name-2'
* @example ['custom-class-name-1', 'custom-class-name-2']
*/
className?: ClassName;
/**
* Function called when a thumbnail has been clicked. Usually, you would like to use this callback to move the user wherever they requested to.
*
* @example ({ dest, pageIndex, pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!')
*/
onItemClick?: (args: OnItemClickArgs) => void;
};
/**
* Displays a thumbnail of a page. Does not render the annotation layer or the text layer. Does not register itself as a link target, so the user will not be scrolled to a Thumbnail component when clicked on an internal link (e.g. in Table of Contents). When clicked, attempts to navigate to the page clicked (similarly to a link in Outline).
*
* Should be placed inside `<Document />`. Alternatively, it can have `pdf` prop passed, which can be obtained from `<Document />`'s `onLoadSuccess` callback function.
*/
export default function Thumbnail(props: ThumbnailProps): React.ReactElement;

49
node_modules/react-pdf/dist/esm/Thumbnail.js generated vendored Normal file
View File

@@ -0,0 +1,49 @@
'use client';
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
import { jsx as _jsx } from "react/jsx-runtime";
import clsx from 'clsx';
import invariant from 'tiny-invariant';
import Page from './Page.js';
import { isProvided } from './shared/utils.js';
import useDocumentContext from './shared/hooks/useDocumentContext.js';
/**
* Displays a thumbnail of a page. Does not render the annotation layer or the text layer. Does not register itself as a link target, so the user will not be scrolled to a Thumbnail component when clicked on an internal link (e.g. in Table of Contents). When clicked, attempts to navigate to the page clicked (similarly to a link in Outline).
*
* Should be placed inside `<Document />`. Alternatively, it can have `pdf` prop passed, which can be obtained from `<Document />`'s `onLoadSuccess` callback function.
*/
export default function Thumbnail(props) {
const documentContext = useDocumentContext();
const mergedProps = Object.assign(Object.assign({}, documentContext), props);
const { className, linkService, onItemClick, pageIndex: pageIndexProps, pageNumber: pageNumberProps, pdf, } = mergedProps;
invariant(pdf, 'Attempted to load a thumbnail, but no document was specified. Wrap <Thumbnail /> in a <Document /> or pass explicit `pdf` prop.');
const pageIndex = isProvided(pageNumberProps) ? pageNumberProps - 1 : (pageIndexProps !== null && pageIndexProps !== void 0 ? pageIndexProps : null);
const pageNumber = pageNumberProps !== null && pageNumberProps !== void 0 ? pageNumberProps : (isProvided(pageIndexProps) ? pageIndexProps + 1 : null);
function onClick(event) {
event.preventDefault();
if (!isProvided(pageIndex) || !pageNumber) {
return;
}
invariant(onItemClick || linkService, 'Either onItemClick callback or linkService must be defined in order to navigate to an outline item.');
if (onItemClick) {
onItemClick({
pageIndex,
pageNumber,
});
}
else if (linkService) {
linkService.goToPage(pageNumber);
}
}
const { className: classNameProps, onItemClick: onItemClickProps } = props, pageProps = __rest(props, ["className", "onItemClick"]);
return (_jsx("a", { className: clsx('react-pdf__Thumbnail', className), href: pageNumber ? '#' : undefined, onClick: onClick, children: _jsx(Page, Object.assign({}, pageProps, { _className: "react-pdf__Thumbnail__page", _enableRegisterUnregisterPage: false, renderAnnotationLayer: false, renderTextLayer: false })) }));
}

14
node_modules/react-pdf/dist/esm/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,14 @@
import * as pdfjs from 'pdfjs-dist';
import Document from './Document.js';
import Outline from './Outline.js';
import Page from './Page.js';
import Thumbnail from './Thumbnail.js';
import useDocumentContext from './shared/hooks/useDocumentContext.js';
import useOutlineContext from './shared/hooks/useOutlineContext.js';
import usePageContext from './shared/hooks/usePageContext.js';
import PasswordResponses from './PasswordResponses.js';
export type { DocumentProps } from './Document.js';
export type { OutlineProps } from './Outline.js';
export type { PageProps } from './Page.js';
export type { ThumbnailProps } from './Thumbnail.js';
export { pdfjs, Document, Outline, Page, Thumbnail, useDocumentContext, useOutlineContext, usePageContext, PasswordResponses, };

Some files were not shown because too many files have changed in this diff Show More