-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathindex.tsx
75 lines (69 loc) · 3.05 KB
/
index.tsx
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
import 'core-js/proposals/promise-with-resolvers';
// eslint-disable-next-line import/extensions
import pdfWorkerSource from 'pdfjs-dist/build/pdf.worker.min.mjs';
// eslint-disable-next-line import/extensions
import pdfWorkerLegacySource from 'pdfjs-dist/legacy/build/pdf.worker.min.mjs';
import React, {useMemo, useState} from 'react';
import {View} from 'react-native';
import {Document, pdfjs, Thumbnail} from 'react-pdf';
import FullScreenLoadingIndicator from '@components/FullscreenLoadingIndicator';
import useThemeStyles from '@hooks/useThemeStyles';
import addEncryptedAuthTokenToURL from '@libs/addEncryptedAuthTokenToURL';
import {isMobileSafari, isModernSafari} from '@libs/Browser';
import PDFThumbnailError from './PDFThumbnailError';
import type PDFThumbnailProps from './types';
const shouldUseLegacyWorker = isMobileSafari() && !isModernSafari();
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const pdfWorker = shouldUseLegacyWorker ? pdfWorkerLegacySource : pdfWorkerSource;
if (!pdfjs.GlobalWorkerOptions.workerSrc) {
pdfjs.GlobalWorkerOptions.workerSrc = URL.createObjectURL(new Blob([pdfWorker], {type: 'text/javascript'}));
}
function PDFThumbnail({previewSourceURL, style, isAuthTokenRequired = false, enabled = true, onPassword, onLoadError, onLoadSuccess}: PDFThumbnailProps) {
const styles = useThemeStyles();
const [failedToLoad, setFailedToLoad] = useState(false);
const thumbnail = useMemo(
() => (
<Document
loading={<FullScreenLoadingIndicator />}
file={isAuthTokenRequired ? addEncryptedAuthTokenToURL(previewSourceURL) : previewSourceURL}
options={{
cMapUrl: 'cmaps/',
cMapPacked: true,
}}
externalLinkTarget="_blank"
onPassword={onPassword}
onLoad={() => {
setFailedToLoad(false);
}}
onLoadSuccess={() => {
if (!onLoadSuccess) {
return;
}
onLoadSuccess();
}}
onLoadError={() => {
if (onLoadError) {
onLoadError();
}
setFailedToLoad(true);
}}
error={() => null}
>
<View pointerEvents="none">
<Thumbnail pageIndex={0} />
</View>
</Document>
),
[isAuthTokenRequired, previewSourceURL, onPassword, onLoadError, onLoadSuccess],
);
return (
<View style={[style, styles.overflowHidden, failedToLoad && styles.h100]}>
<View style={[styles.w100, styles.h100, !failedToLoad && {...styles.alignItemsCenter, ...styles.justifyContentCenter}]}>
{enabled && !failedToLoad && thumbnail}
{failedToLoad && <PDFThumbnailError />}
</View>
</View>
);
}
PDFThumbnail.displayName = 'PDFThumbnail';
export default React.memo(PDFThumbnail);