-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
index.js
68 lines (61 loc) · 2.39 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
import React from 'react';
import CONST from '../../CONST';
import {propTypes, defaultProps} from './attachmentPickerPropTypes';
import * as FileUtils from '../../libs/fileDownload/FileUtils';
/**
* Returns acceptable FileTypes based on ATTACHMENT_PICKER_TYPE
* @param {String} type
* @returns {String|undefined} Picker will accept all file types when its undefined
*/
function getAcceptableFileTypes(type) {
if (type !== CONST.ATTACHMENT_PICKER_TYPE.IMAGE) {
return;
}
return 'image/*';
}
/**
* This component renders a function as a child and
* returns a "show attachment picker" method that takes
* a callback. This is the web/mWeb/desktop version since
* on a Browser we must append a hidden input to the DOM
* and listen to onChange event.
*/
class AttachmentPicker extends React.Component {
render() {
return (
<>
<input
hidden
type="file"
ref={el => this.fileInput = el}
onChange={(e) => {
let file = e.target.files[0];
if (file) {
const cleanName = FileUtils.cleanFileName(file.name);
file.uri = URL.createObjectURL(file);
if (file.name !== cleanName) {
file = new File([file], cleanName);
}
this.onPicked(file);
}
// Cleanup after selecting a file to start from a fresh state
this.fileInput.value = null;
}}
// We are stopping the event propagation because triggering the `click()` on the hidden input
// causes the event to unexpectedly bubble up to anything wrapping this component e.g. Pressable
onClick={e => e.stopPropagation()}
accept={getAcceptableFileTypes(this.props.type)}
/>
{this.props.children({
openPicker: ({onPicked}) => {
this.onPicked = onPicked;
this.fileInput.click();
},
})}
</>
);
}
}
AttachmentPicker.propTypes = propTypes;
AttachmentPicker.defaultProps = defaultProps;
export default AttachmentPicker;