-
-
Notifications
You must be signed in to change notification settings - Fork 164
/
index.js
242 lines (214 loc) · 5.74 KB
/
index.js
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
// @flow
import React, { Component } from 'react'
import {
View,
ActivityIndicator,
Platform,
StyleSheet,
} from 'react-native'
import { WebView } from 'react-native-webview'
import * as FileSystem from 'expo-file-system'
import Constants from 'expo-constants'
const {
cacheDirectory,
writeAsStringAsync,
deleteAsync,
getInfoAsync,
} = FileSystem
function viewerHtml(base64: string): string {
return `
<!DOCTYPE html>
<html>
<head>
<title>PDF reader</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
</head>
<body>
<div id="file" data-file="${base64}"></div>
<div id="react-container"></div>
<script type="text/javascript" src="bundle.js"></script>
</body>
</html>
`
}
const bundleJsPath = `${cacheDirectory}bundle.js`
const htmlPath = `${cacheDirectory}index.html`
async function writeWebViewReaderFileAsync(data: string): Promise<*> {
const { exist, md5 } = await getInfoAsync(bundleJsPath, { md5: true })
const bundleContainer = require('./bundleContainer')
if (!exist || bundleContainer.getBundleMd5() !== md5) {
await writeAsStringAsync(bundleJsPath, bundleContainer.getBundle())
}
await writeAsStringAsync(htmlPath, viewerHtml(data))
}
export async function removeFilesAsync(): Promise<*> {
await deleteAsync(htmlPath)
}
function readAsTextAsync(mediaBlob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
try {
const reader = new FileReader()
reader.onloadend = e => {
if (typeof reader.result === 'string') {
return resolve(reader.result)
}
return reject(
`Unable to get result of file due to bad type, waiting string and getting ${typeof reader.result}.`,
)
}
reader.readAsDataURL(mediaBlob)
} catch (error) {
reject(error)
}
})
}
async function fetchPdfAsync(source: Source): Promise<string> {
const mediaBlob = await urlToBlob(source)
return readAsTextAsync(mediaBlob)
}
async function urlToBlob(source: Source) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest()
xhr.onerror = reject
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
resolve(xhr.response)
}
}
xhr.open('GET', source.uri)
if (source.headers && Object.keys(source.headers).length > 0) {
Object.keys(source.headers).forEach((key) => {
xhr.setRequestHeader(key, source.headers[key]);
});
}
xhr.responseType = 'blob'
xhr.send()
})
}
const Loader = () => (
<View style={{ flex: 1, justifyContent: 'center' }}>
<ActivityIndicator size="large" />
</View>
)
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
},
webview: {
flex: 1,
backgroundColor: 'rgb(82, 86, 89)',
},
})
type Source = {
uri?: string,
base64?: string,
headers: { [key: string]: string }
}
type Props = {
source: Source,
style: object,
webviewStyle: object,
onLoad: func,
noLoader: boolean
}
type State = {
ready: boolean,
android: boolean,
ios: boolean,
data?: string,
}
class PdfReader extends Component<Props, State> {
state = { ready: false, android: false, ios: false, data: undefined }
async init() {
const { onLoad } = this.props;
try {
const { source } = this.props
const ios = Platform.OS === 'ios'
const android = Platform.OS === 'android'
this.setState({ ios, android })
let ready = false
let data = undefined
if (
source.uri &&
android &&
(source.uri.startsWith('http') ||
source.uri.startsWith('file') ||
source.uri.startsWith('content'))
) {
data = await fetchPdfAsync(source)
ready= !!data
} else if (source.base64 && source.base64.startsWith('data')) {
data = source.base64
ready = true
} else if (ios) {
data = source.uri
} else {
alert('source props is not correct')
return
}
if (android) {
await writeWebViewReaderFileAsync(data)
}
if(onLoad && ready === true) {
onLoad();
}
this.setState({ ready, data })
} catch (error) {
alert('Sorry, an error occurred.')
console.error(error)
}
}
componentDidMount() {
this.init()
}
componentWillUnmount() {
if (this.state.android) {
removeFilesAsync()
}
}
render() {
const { ready, data, ios, android } = this.state
const { style, webviewStyle, onLoad, noLoader, onLoadEnd, onError } = this.props
if (data && ios) {
return (
<View style={[styles.container, style]}>
{!noLoader && !ready && <Loader />}
<WebView
onLoad={()=>{
this.setState({ready: true});
if(onLoad) {
onLoad();
}
}}
originWhitelist={['http://*', 'https://*', 'file://*', 'data:*']}
style={[styles.webview, webviewStyle]}
source={{ uri: data }}
/>
</View>
)
}
if (ready && data && android) {
return (
<View style={[styles.container, style]}>
<WebView
onLoad={onLoad}
onLoadEnd={onLoadEnd}
onError={onError}
allowFileAccess
originWhitelist={['http://*', 'https://*', 'file://*', 'data:*']}
style={[styles.webview, webviewStyle]}
source={{ uri: htmlPath }}
mixedContentMode="always"
scrollEnabled
height="100vh"
/>
</View>
)
}
return <Loader />
}
}
export default PdfReader