-
-
Notifications
You must be signed in to change notification settings - Fork 903
/
Document.jsx
388 lines (314 loc) · 9.57 KB
/
Document.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/**
* Loads a PDF document. Passes it to all children.
*/
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import makeEventProps from 'make-event-props';
import makeCancellable from 'make-cancellable-promise';
import clsx from 'clsx';
import invariant from 'tiny-invariant';
import warning from 'tiny-warning';
import * as pdfjs from 'pdfjs-dist/build/pdf';
import DocumentContext from './DocumentContext';
import Message from './Message';
import LinkService from './LinkService';
import PasswordResponses from './PasswordResponses';
import {
cancelRunningTask,
dataURItoByteString,
displayCORSWarning,
isArrayBuffer,
isBlob,
isBrowser,
isDataURI,
isFile,
loadFromFile,
} from './shared/utils';
import { eventProps, isClassName, isFile as isFileProp, isRef } from './shared/propTypes';
const { PDFDataRangeTransport } = pdfjs;
export default class Document extends PureComponent {
state = {
pdf: null,
};
viewer = {
scrollPageIntoView: ({ dest, pageIndex, pageNumber }) => {
// Handling jumping to internal links target
const { onItemClick } = this.props;
// 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 = this.pages[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>.`,
);
},
};
linkService = new LinkService();
componentDidMount() {
this.loadDocument();
this.setupLinkService();
}
componentDidUpdate(prevProps) {
const { file } = this.props;
if (file !== prevProps.file) {
this.loadDocument();
}
}
componentWillUnmount() {
// If rendering is in progress, let's cancel it
cancelRunningTask(this.runningTask);
// If loading is in progress, let's destroy it
if (this.loadingTask) this.loadingTask.destroy();
}
loadDocument = () => {
// If another rendering is in progress, let's cancel it
cancelRunningTask(this.runningTask);
// If another loading is in progress, let's destroy it
if (this.loadingTask) this.loadingTask.destroy();
const cancellable = makeCancellable(this.findDocumentSource());
this.runningTask = cancellable;
cancellable.promise
.then((source) => {
this.onSourceSuccess();
if (!source) {
return;
}
this.setState((prevState) => {
if (!prevState.pdf) {
return null;
}
return { pdf: null };
});
const { options, onLoadProgress, onPassword } = this.props;
const destroyable = pdfjs.getDocument({ ...source, ...options });
destroyable.onPassword = onPassword;
if (onLoadProgress) {
destroyable.onProgress = onLoadProgress;
}
this.loadingTask = destroyable;
destroyable.promise
.then((pdf) => {
this.setState((prevState) => {
if (prevState.pdf && prevState.pdf.fingerprint === pdf.fingerprint) {
return null;
}
return { pdf };
}, this.onLoadSuccess);
})
.catch((error) => {
this.onLoadError(error);
});
})
.catch((error) => {
this.onSourceError(error);
});
};
setupLinkService = () => {
const { externalLinkRel, externalLinkTarget } = this.props;
this.linkService.setViewer(this.viewer);
this.linkService.setExternalLinkRel(externalLinkRel);
this.linkService.setExternalLinkTarget(externalLinkTarget);
};
get childContext() {
const { linkService, registerPage, unregisterPage } = this;
const { imageResourcesPath, renderMode, rotate } = this.props;
const { pdf } = this.state;
return {
imageResourcesPath,
linkService,
pdf,
registerPage,
renderMode,
rotate,
unregisterPage,
};
}
get eventProps() {
return makeEventProps(this.props, () => this.state.pdf);
}
/**
* Called when a document source is resolved correctly
*/
onSourceSuccess = () => {
const { onSourceSuccess } = this.props;
if (onSourceSuccess) onSourceSuccess();
};
/**
* Called when a document source failed to be resolved correctly
*/
onSourceError = (error) => {
warning(error);
const { onSourceError } = this.props;
if (onSourceError) onSourceError(error);
};
/**
* Called when a document is read successfully
*/
onLoadSuccess = () => {
const { onLoadSuccess } = this.props;
const { pdf } = this.state;
if (onLoadSuccess) onLoadSuccess(pdf);
this.pages = new Array(pdf.numPages);
this.linkService.setDocument(pdf);
};
/**
* Called when a document failed to read successfully
*/
onLoadError = (error) => {
this.setState({ pdf: false });
warning(error);
const { onLoadError } = this.props;
if (onLoadError) onLoadError(error);
};
/**
* Finds a document source based on props.
*/
findDocumentSource = () =>
new Promise((resolve) => {
const { file } = this.props;
if (!file) {
resolve(null);
}
// File is a string
if (typeof file === 'string') {
if (isDataURI(file)) {
const fileByteString = dataURItoByteString(file);
resolve({ data: fileByteString });
}
displayCORSWarning();
resolve({ url: file });
}
// File is PDFDataRangeTransport
if (file instanceof PDFDataRangeTransport) {
resolve({ range: file });
}
// File is an ArrayBuffer
if (isArrayBuffer(file)) {
resolve({ 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) || isFile(file)) {
loadFromFile(file).then((data) => {
resolve({ data });
});
return;
}
}
// 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(
file.url || file.data || file.range,
'Invalid parameter object: need either .data, .range or .url',
);
// File .url is a string
if (typeof file.url === 'string') {
if (isDataURI(file.url)) {
const { url, ...otherParams } = file;
const fileByteString = dataURItoByteString(url);
resolve({ data: fileByteString, ...otherParams });
}
displayCORSWarning();
}
resolve(file);
});
registerPage = (pageIndex, ref) => {
this.pages[pageIndex] = ref;
};
unregisterPage = (pageIndex) => {
delete this.pages[pageIndex];
};
renderChildren() {
const { children } = this.props;
return (
<DocumentContext.Provider value={this.childContext}>{children}</DocumentContext.Provider>
);
}
renderContent() {
const { file } = this.props;
const { pdf } = this.state;
if (!file) {
const { noData } = this.props;
return <Message type="no-data">{typeof noData === 'function' ? noData() : noData}</Message>;
}
if (pdf === null) {
const { loading } = this.props;
return (
<Message type="loading">{typeof loading === 'function' ? loading() : loading}</Message>
);
}
if (pdf === false) {
const { error } = this.props;
return <Message type="error">{typeof error === 'function' ? error() : error}</Message>;
}
return this.renderChildren();
}
render() {
const { className, inputRef } = this.props;
return (
<div className={clsx('react-pdf__Document', className)} ref={inputRef} {...this.eventProps}>
{this.renderContent()}
</div>
);
}
}
Document.defaultProps = {
error: 'Failed to load PDF file.',
loading: 'Loading PDF…',
noData: 'No PDF file specified.',
onPassword: (callback, reason) => {
switch (reason) {
case PasswordResponses.NEED_PASSWORD: {
// eslint-disable-next-line no-alert
const password = prompt('Enter the password to open this PDF file.');
callback(password);
break;
}
case PasswordResponses.INCORRECT_PASSWORD: {
// eslint-disable-next-line no-alert
const password = prompt('Invalid password. Please try again.');
callback(password);
break;
}
default:
}
},
};
const isFunctionOrNode = PropTypes.oneOfType([PropTypes.func, PropTypes.node]);
Document.propTypes = {
...eventProps,
children: PropTypes.node,
className: isClassName,
error: isFunctionOrNode,
externalLinkRel: PropTypes.string,
externalLinkTarget: PropTypes.string,
file: isFileProp,
imageResourcesPath: PropTypes.string,
inputRef: isRef,
loading: isFunctionOrNode,
noData: isFunctionOrNode,
onItemClick: PropTypes.func,
onLoadError: PropTypes.func,
onLoadProgress: PropTypes.func,
onLoadSuccess: PropTypes.func,
onPassword: PropTypes.func,
onSourceError: PropTypes.func,
onSourceSuccess: PropTypes.func,
rotate: PropTypes.number,
};