-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsvtogeocoder.js
270 lines (261 loc) · 11 KB
/
csvtogeocoder.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
/*globals CSVToGeocoder Papa*/
'use strict';
var CSVToGeocoder = function (options) {
options = options || {};
options.i18n = options.i18n || {};
var _ = function (k) {
return options.i18n[k] || k;
};
var createNode = function (what, attrs, parent, content) {
var el = document.createElement(what);
for (var attr in attrs || {}) el[attr] = attrs[attr];
if (typeof parent !== 'undefined') parent.appendChild(el);
if (content) {
if (content.nodeType && content.nodeType === 1) el.appendChild(content);
else el.innerHTML = content;
}
return el;
};
CSVToGeocoder.createNode = createNode;
var hasClass = function (el, name) {
return el.className.length && new RegExp('(^|\\s)' + name + '(\\s|$)').test(el.className);
};
var addClass = function (el, name) {
el.className = (el.className ? el.className + ' ' : '') + name;
};
var removeClass = function (el, name) {
el.className = ((' ' + el.className + ' ').replace(' ' + name + ' ', ' ')).trim();
};
var reader = new FileReader(), file, container, blob, parsed;
if (options.container) {
if (typeof options.container === 'string') container = document.querySelector(options.container);
else container = options.container;
} else {
container = document.body;
}
var download = document.createElement('a');
container.appendChild(download);
download.style.display = 'none';
container.setAttribute('class', (container.getAttribute('class') ? container.getAttribute('class') + ' ' : '') + 'csvtogeocoder');
createNode('h2', {}, container, '1. ' + _('Choose a file'));
var fileInput = createNode('input', {type: 'file', id: 'fileInput'}, container);
var holder = createNode('div', {id: 'holder'}, container, _('Drag your file here') + ', ' + _('or') + ' <a id="browseLink" href="#">' + _('browse') + '</a>');
createNode('h2', {className: 'step-title', id: 'next'}, container, '2. ' + _('Preview the file and check encoding'));
var step2 = createNode('div', {className: 'step'}, container);
var previewContainer = createNode('table', {className: 'preview'}, step2);
var helpEncoding = createNode('p', {id: 'helpEncoding'}, step2, _('If you see weird characters in the preview, you can try with another encoding') + ': ');
var selectEncoding = createNode('select', {}, helpEncoding);
for (var i = 0; i < options.encodings.length; i++) {
createNode('option', {value: options.encodings[i]}, selectEncoding, options.encodings[i]);
}
createNode('h2', {className: 'step-title'}, container, '3. ' + _('Choose the columns you want to use to compute the addresses'));
var step3 = createNode('div', {className: 'step'}, container);
var availableColumns = createNode('ul', {id: 'availableColumns'}, step3);
var chosenColumns = createNode('ul', {id: 'chosenColumns'}, step3);
if (options.onBuild) options.onBuild({container: container});
var lastStep = createNode('div', {className: 'step'}, container);
var submitButton = createNode('input', {type: 'button', value: _('Geocode'), disabled: 'disabled'}, lastStep);
var errorContainer = createNode('div', {className: 'error'}, lastStep);
var error = function (message) {
if (options.onError) {
options.onError(message);
} else {
errorContainer.innerHTML = message;
if (!hasClass(container, 'error')) addClass(container, 'error');
}
};
var stop = function (e) {
e.stopPropagation();
e.preventDefault();
};
var submit = function () {
removeClass(container, 'error');
var progressBar = createNode('progress', {}, container);
progressBar.max = 100;
var xhr = new XMLHttpRequest();
xhr.open('POST', options.postURL || '.');
xhr.overrideMimeType('text/csv');
var columns = document.querySelectorAll('#chosenColumns li');
var formData = new FormData();
for (var i = 0; i < columns.length; i++) {
formData.append('columns', columns[i].id);
}
formData.append('data', blob, file.name);
formData.append('encoding', getEncoding());
formData.append('delimiter', parsed.meta.delimiter);
if (options.onSubmit) options.onSubmit({form: formData});
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
progressBar.parentNode.removeChild(progressBar);
if (xhr.status === 200) {
window.URL = window.URL || window.webkitURL;
var url = window.URL.createObjectURL(new Blob([xhr.responseText], {type: 'text/csv; charset=utf-8'}));
download.href = url;
download.download = downloadFileName();
download.click();
} else {
error(_('Sorry, something went wrong…'));
}
}
};
xhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
var percentage = Math.round((e.loaded * 100) / e.total);
progressBar.value = percentage;
}
}, false);
xhr.upload.addEventListener('load', function (){
progressBar.removeAttribute('value'); // Switch to undeterminate state.
}, false);
xhr.send(formData);
return false;
};
var getEncoding = function () {
return selectEncoding.options[selectEncoding.selectedIndex].value;
};
var processFile = function () {
reader.readAsText(file, getEncoding());
holder.innerHTML = '<strong>' + file.name + '</strong> (' + _('or drag another file here') + ', ' + _('or') + ' <a id="browseLink" href="#">' + _('browse') + '</a>)';
listenBrowseLink();
};
var onFileDrop = function (e) {
this.className = '';
stop(e);
file = e.dataTransfer.files[0];
processFile();
};
var onDragOver = function (e) {
stop(e);
this.className = 'hover';
};
var onDragLeave = function (e) {
stop(e);
this.className = '';
return false;
};
var onDragEnter = function (e) {
stop(e);
};
var onFileLoad = function () {
parsed = Papa.parse(reader.result, {header: true});
if (!parsed.data.length) return;
var headers = parsed.meta.fields, column;
availableColumns.innerHTML = '';
chosenColumns.innerHTML = '';
populatePreview();
for (var j = 0; j < headers.length; j++) {
column = document.createElement('li');
column.setAttribute('draggable', 'true');
column.innerHTML = column.value = column.id = headers[j];
column.ondragstart = onColumnDragStart;
column.onclick = onColumnClick;
column.ondrop = onColumnDrop;
column.ondragover = onColumnDragOver;
column.ondragleave = onColumnDragLeave;
availableColumns.appendChild(column);
}
submitButton.disabled = false;
blob = new Blob([reader.result], {type: 'text/csv; charset=' + getEncoding()});
if (!hasClass(container, 'active')) addClass(container, 'active');
window.location.hash = '#next';
if (options.onFileLoad) options.onFileLoad({file: blob, headers: headers});
};
var populatePreview = function () {
previewContainer.innerHTML = '';
var row = createNode('tr', {}, previewContainer);
for (var i = 0; i < parsed.meta.fields.length; i++) {
createNode('th', {}, row, parsed.meta.fields[i]);
}
for (i = 0; i < Math.min(parsed.data.length, 4); i++) {
row = createNode('tr', {}, previewContainer);
for (var j = 0; j < parsed.meta.fields.length; j++) {
createNode('td', {}, row, parsed.data[i][parsed.meta.fields[j]]);
}
}
helpEncoding.style.display = 'block';
};
var onSubmit = function (e) {
stop(e);
submit(file);
return false;
};
var onColumnDragStart = function (e) {
e.dataTransfer.effectAllowed = 'copy';
e.dataTransfer.setData('text/plain', this.id);
};
var onColumnDropboxDragover = function (e) {
stop(e);
this.className = 'hover';
e.dataTransfer.dropEffect = 'copy';
};
var onColumnDropboxDragleave = function (e) {
stop(e);
this.className = '';
};
var onColumnDropboxDrop = function (e) {
this.className = '';
stop(e);
var el = document.getElementById(e.dataTransfer.getData('text/plain'));
chosenColumns.appendChild(el);
return false;
};
var onColumnDrop = function (e) {
stop(e);
var el = document.getElementById(e.dataTransfer.getData('text/plain'));
this.parentNode.insertBefore(el, this);
};
var onColumnClick = function () {
this.className = '';
var from, to;
if (this.parentNode === chosenColumns) {
from = chosenColumns;
to = availableColumns;
} else {
from = availableColumns;
to = chosenColumns;
}
from.removeChild(this);
to.appendChild(this);
};
var onColumnDragOver = function () {
this.className = 'hover';
};
var onColumnDragLeave = function () {
this.className = '';
};
var onFileInputChange = function (e) {
stop(e);
file = this.files[0];
processFile();
};
var onSelectEncodingChange = function () {
processFile();
};
var listenBrowseLink = function () {
var browseLink = document.querySelector('#browseLink');
var onBrowseLinkClick = function (e) {
stop(e);
fileInput.click();
};
browseLink.addEventListener('click', onBrowseLinkClick, false);
};
var downloadFileName = function () {
// As we are in CORS ajax, we can't access the Content-Disposition header,
// so built the file name from here.
var name = file.name || 'file';
if (name.indexOf('.csv', name.length - 4) !== -1) name = name.slice(0, name.length - 4);
return name + '.geocoded.csv';
};
listenBrowseLink();
reader.addEventListener('load', onFileLoad, false);
holder.addEventListener('dragenter', onDragEnter, false);
holder.addEventListener('dragover', onDragOver, false);
holder.addEventListener('dragleave', onDragLeave, false);
holder.addEventListener('drop', onFileDrop, false);
submitButton.addEventListener('click', onSubmit, false);
chosenColumns.addEventListener('dragover', onColumnDropboxDragover, false);
chosenColumns.addEventListener('dragleave', onColumnDropboxDragleave, false);
chosenColumns.addEventListener('drop', onColumnDropboxDrop, false);
fileInput.addEventListener('change', onFileInputChange, false);
selectEncoding.addEventListener('change', onSelectEncodingChange, false);
};