-
Notifications
You must be signed in to change notification settings - Fork 102
/
index.js
57 lines (48 loc) · 1.45 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
import { NativeEventEmitter, NativeModules, Platform } from "react-native";
const { RNFileViewer } = NativeModules;
const eventEmitter = new NativeEventEmitter(RNFileViewer);
let lastId = 0;
function open(path, options = {}) {
const _options =
typeof options === "string" ? { displayName: options } : options;
const { onDismiss, ...nativeOptions } = _options;
if (!["android", "ios"].includes(Platform.OS)) {
return RNFileViewer.open(path, nativeOptions);
}
return new Promise((resolve, reject) => {
const currentId = ++lastId;
const openSubscription = eventEmitter.addListener(
"RNFileViewerDidOpen",
({ id, error }) => {
if (id === currentId) {
openSubscription.remove();
return error ? reject(new Error(error)) : resolve();
}
}
);
const dismissSubscription = eventEmitter.addListener(
"RNFileViewerDidDismiss",
({ id }) => {
if (id === currentId) {
dismissSubscription.remove();
onDismiss && onDismiss();
}
}
);
RNFileViewer.open(normalize(path), currentId, nativeOptions);
});
}
function normalize(path) {
if (Platform.OS === "ios" || Platform.OS === "android") {
const filePrefix = "file://";
if (path.startsWith(filePrefix)) {
path = path.substring(filePrefix.length);
try {
path = decodeURI(path);
} catch (e) {}
}
}
return path;
}
export default { open };
export { open };