-
Notifications
You must be signed in to change notification settings - Fork 28
/
index.js
296 lines (264 loc) · 10.9 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
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
'use strict';
// Business logic for base64 encoder (index.html).
// Requires asyncToBase64 and asyncFromBase64 from base64.js
// Initialization of these conversion type constants and locals is done in DOMContentLoaded.
var LeftConversionTypes, RightConversionTypes;
var leftConversionType, rightConversionType;
// This state variable lets us change the conversion type without overwriting the user's last input.
var userLastChangedRightSide = false;
// FIXME: Check if this can be cleared more often to reduce peak memory usage.
var currentFile;
// Cached DOM lookups.
var left, leftImageArea, leftTextarea, leftImageInput, leftTypeSelect, leftTypeText;
var right, rightTextarea, rightTypeSelect, rightTypeText;
window.addEventListener('DOMContentLoaded', function() {
// Must keep in sync with the #left type's customSelect DOM.
LeftConversionTypes = {
'text': {displayName: 'Text', isImage: false},
'image': {displayName: 'Image', isImage: true}
}
// Must keep in sync with the #right type's customSelect DOM.
RightConversionTypes = {
'base64utf8': {displayName: 'Base64', encoding: 'utf8', forImage: false},
'base64ascii': {displayName: 'Base64 (ascii)', encoding: 'ascii', forImage: false},
'base64image': {displayName: 'Base64 (image)', encoding: 'utf8', forImage: true}
}
leftConversionType = LeftConversionTypes[Object.keys(LeftConversionTypes)[0]];
rightConversionType = RightConversionTypes[Object.keys(RightConversionTypes)[0]];
left = document.getElementById('left');
leftImageArea = left.querySelector('.imagearea');
leftTextarea = left.querySelector('textarea');
leftImageInput = left.querySelector('.customUpload input');
leftTypeSelect = left.querySelector('.type select');
leftTypeText = left.querySelector('.type span');
right = document.getElementById('right');
rightTextarea = right.querySelector('textarea');
rightTypeSelect = right.querySelector('.type select');
rightTypeText = right.querySelector('.type span');
leftTextarea.addEventListener('input', function() {
userLastChangedRightSide = false;
updateConversion();
});
leftImageInput.addEventListener('change', function(event) {
if (event.target.files[0]) {
currentFile = event.target.files[0];
userLastChangedRightSide = false;
updateConversion();
}
});
rightTextarea.addEventListener('input', function() {
userLastChangedRightSide = true;
updateConversion();
});
leftTypeSelect.addEventListener('change', function() {
onLeftTypeChanged();
});
rightTypeSelect.addEventListener('change', function() {
onRightTypeChanged();
});
// Drag and drop support.
var insideCount = 0;
var leftContent = left.querySelector('.content');
leftContent.addEventListener('dragenter', function(event) {
insideCount++;
leftTextarea.classList.add('dragover');
leftImageArea.classList.add('dragover');
});
leftContent.addEventListener('dragleave', function(event) {
if (--insideCount === 0) {
leftTextarea.classList.remove('dragover');
leftImageArea.classList.remove('dragover');
}
});
document.body.addEventListener('dragover', function(event) {
// Required for the drop event to work properly.
event.preventDefault();
});
document.body.addEventListener('drop', function(event) {
event.preventDefault();
event.stopPropagation();
insideCount = 0;
leftTextarea.classList.remove('dragover');
leftImageArea.classList.remove('dragover');
if (event.dataTransfer.files.length > 0)
onDropFiles(event.dataTransfer.files);
});
// Update state if a select value is already present (e.g., if the user navigated back.)
var leftConversionTypeFromDOM = LeftConversionTypes[leftTypeSelect.value];
if (leftConversionTypeFromDOM !== leftConversionType)
onLeftTypeChanged();
var rightConversionTypeFromDOM = RightConversionTypes[rightTypeSelect.value];
if (rightConversionTypeFromDOM !== rightConversionType)
onRightTypeChanged();
// We queue a task to setup the offline cache so it doesn't affect the critical path.
setTimeout(function() {
setupOfflineCache();
}, 500);
});
function updateConversion() {
// Cleanup any leftover errors.
leftImageArea.classList.remove('errorSource');
leftTextarea.classList.remove('errorSource');
rightTextarea.classList.remove('errorSource');
leftTextarea.classList.remove('errorDestination');
rightTextarea.classList.remove('errorDestination');
if (leftConversionType.isImage)
convertImage();
else
bidirectionalTextConversion(!userLastChangedRightSide)
}
// TODO: Gracefully disable this if the FileReader/etc APIs are not available.
function convertImage() {
var setBackgroundImage = function(optionalDataUri) {
if (optionalDataUri) {
leftImageArea.classList.add('containsImage');
leftImageArea.style.backgroundImage = 'url(' + optionalDataUri + ')';
} else {
leftImageArea.classList.remove('containsImage');
leftImageArea.style.backgroundImage = '';
}
}
var success = function(value) {
var dataUri = 'data:' + imageType(currentFile) + ';base64,' + value;
rightTextarea.value = '<img src="' + dataUri + '">';
setBackgroundImage(dataUri);
}
var error = function(message) {
leftImageArea.classList.add('errorSource');
rightTextarea.classList.add('errorDestination');
rightTextarea.value = message;
setBackgroundImage(undefined);
}
if (!currentFile) {
rightTextarea.value = 'No image';
setBackgroundImage(undefined);
return;
}
if (imageType(currentFile).indexOf('image') === -1) {
error('Image type \'' + imageType(currentFile) + '\' was not recognized.');
return;
}
var reader = new FileReader();
reader.onload = function(result) {
var imageFileAsArray = new Uint8Array(result.target.result);
asyncToBase64(imageFileAsArray, undefined, success, error);
};
reader.onerror = function(result) {
error(result.message);
};
reader.readAsArrayBuffer(currentFile);
}
function bidirectionalTextConversion(convertLeftToRight) {
var inputElement = convertLeftToRight ? leftTextarea : rightTextarea;
var outputElement = convertLeftToRight ? rightTextarea : leftTextarea;
var success = function(value) {
outputElement.value = value;
}
var error = function(message) {
inputElement.classList.add('errorSource');
outputElement.classList.add('errorDestination');
outputElement.value = message;
}
var converter = convertLeftToRight ? asyncToBase64 : asyncFromBase64;
converter(inputElement.value, rightConversionType.encoding, success, error);
}
function onLeftTypeChanged(optionalSkipConversionUpdate) {
var selectedValue = leftTypeSelect.options[leftTypeSelect.selectedIndex].value;
var newType = LeftConversionTypes[selectedValue];
if (newType === leftConversionType)
return;
if (newType === undefined)
throw 'Unknown conversion type: ' + selectedValue;
leftConversionType = newType;
leftTypeText.textContent = leftConversionType.displayName;
// Ensure the correct (image / text) left view is visible.
if (leftConversionType.isImage == leftImageArea.classList.contains('hidden')) {
leftImageArea.classList.toggle('hidden');
leftTextarea.classList.toggle('hidden');
}
updateRightTypeAfterLeftTypeChange();
if (!optionalSkipConversionUpdate)
updateConversion();
}
function onRightTypeChanged(optionalSkipConversionUpdate) {
var selectedValue = rightTypeSelect.options[rightTypeSelect.selectedIndex].value;
var newType = RightConversionTypes[selectedValue];
if (newType === rightConversionType)
return;
if (newType === undefined)
throw 'Unknown conversion type: ' + selectedValue;
rightConversionType = newType;
rightTypeText.textContent = rightConversionType.displayName;
if (rightConversionType.forImage)
rightTextarea.setAttribute('readonly', 'readonly');
else
rightTextarea.removeAttribute('readonly');
if (rightConversionType.forImage)
userLastChangedRightSide = false;
if (!optionalSkipConversionUpdate)
updateConversion();
}
function updateRightTypeAfterLeftTypeChange() {
var firstEnabledIndex, firstEnabledType;
for (var optionIndex = 0; optionIndex < rightTypeSelect.options.length; optionIndex++) {
var option = rightTypeSelect.options[optionIndex];
var rightType = RightConversionTypes[option.value];
if (rightType === undefined)
throw 'Unknown conversion type: ' + selectedValue;
var enabled = leftConversionType.isImage === rightType.forImage;
option.disabled = !enabled;
if (!firstEnabledIndex && !firstEnabledType && enabled) {
firstEnabledIndex = optionIndex;
firstEnabledType = rightType;
}
}
if (leftConversionType.isImage != rightConversionType.forImage) {
rightTypeSelect.selectedIndex = firstEnabledIndex;
onRightTypeChanged(true);
}
}
function onDropFiles(files) {
if (files.length === 0)
return;
currentFile = files[0];
if (!leftConversionType.isImage) {
// Switch to the first image type.
var leftConversions = Object.keys(LeftConversionTypes);
for (var index = 0; index < leftConversions.length; index++) {
if (LeftConversionTypes[leftConversions[index]].isImage) {
leftTypeSelect.selectedIndex = index;
onLeftTypeChanged(true);
break;
}
}
}
updateConversion();
}
function imageType(file) {
if (file.type !== '')
return file.type;
// The stock browser on Android 4.3 returns an empty string for type. If the type is empty but a
// file was uploaded, synthesize a mimetype from the filename.
if (!file.name || file.name.length <= 0)
return '';
var extension = file.name.substr(file.name.lastIndexOf('.') + 1);
switch (extension) {
case('bmp'): return 'image/bmp';
case('gif'): return 'image/gif';
case('jpeg'): return 'image/jpeg';
case('jpg'): return 'image/jpeg';
case('jpe'): return 'image/jpeg';
case('png'): return 'image/png';
case('svg'): return 'image/svg+xml';
case('svgz'): return 'image/svg+xml';
case('webp'): return 'image/webp';
case('ico'): return 'image/x-icon';
}
return '';
}
function setupOfflineCache() {
if (!('serviceWorker' in navigator))
return;
// Disabled for testing.
// navigator.serviceWorker.register('single-page-offline-service-worker.js');
}