forked from rubyforgood/casa
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimport.js
More file actions
75 lines (65 loc) · 2.23 KB
/
import.js
File metadata and controls
75 lines (65 loc) · 2.23 KB
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
/* global atob */
/* global Blob */
/* global FileReader */
/* global localStorage */
/* global File */
/* global DataTransfer */
function dataURItoBlob (dataURI) {
// convert base64 to raw binary data held in a string
const byteString = atob(dataURI.split(',')[1])
// separate out the mime component
const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
// write the bytes of the string to an ArrayBuffer
const arrayBuffer = new ArrayBuffer(byteString.length)
const _ia = new Uint8Array(arrayBuffer)
for (let i = 0; i < byteString.length; i++) {
_ia[i] = byteString.charCodeAt(i)
}
const dataView = new DataView(arrayBuffer)
const blob = new Blob([dataView], { type: mimeString })
return blob
}
function storeCSVFile (file, key) {
const reader = new FileReader()
reader.onload = (fileEvent) => {
localStorage[key] = JSON.stringify({
name: file.name,
data: fileEvent.target.result
})
}
reader.readAsDataURL(file)
}
function fetchCSVFile (key) {
const storedFileData = JSON.parse(localStorage[key])
const fileContent = dataURItoBlob(storedFileData.data)
const file = new File([fileContent], storedFileData.name, { type: 'text/csv' })
return file
}
function populateFileInput (inputId) {
const csvInput = document.getElementById(inputId)
if (csvInput.files.length === 0 && localStorage[inputId]) {
const file = fetchCSVFile(inputId)
const container = new DataTransfer()
container.items.add(file)
csvInput.files = container.files
}
}
$(() => { // JQuery's callback for the DOM loading
['volunteer', 'supervisor'].forEach((importType) => {
const inputFileElementId = `${importType}-file`
const inputFileElement = $(`#${inputFileElementId}`)[0]
const importButtonElement = $(`#${importType}-import-button`)[0]
if (inputFileElement && importButtonElement) {
inputFileElement.addEventListener('change', function (event) {
importButtonElement.disabled = event.target.value === ''
const file = inputFileElement.files[0]
storeCSVFile(file, inputFileElementId)
})
if ($('#smsOptIn') == null) {
delete localStorage[inputFileElementId]
} else {
populateFileInput(inputFileElementId)
}
}
})
})