/
main.js
521 lines (424 loc) · 14.6 KB
/
main.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
/*
* CoreMob Camera
* Vanilla JavaScript App
* https://github.com/coremob/camera/vanilla
*
* W3C Core Mobile Web Platform Community Group
* License: -----
*/
var CoreMobCamera = (function() {
var maxFilesize = 1048576 * 3.5; // Max image size is 3.5MB (iPhone5, Galaxy SIII, Lumia920 < 3MB)
var numPhotosSaved = 0;
var imgCrop;
var finalPhotoDimension = 612;
var viewWidth;
var isBlobSupported = true;
// UI
var loader = document.getElementById('loader'),
firstRun = document.getElementById('firstrun'),
sectionMain = document.getElementById('main'),
sectionPhotoCrop = document.getElementById('photoCrop'),
fileinfo = document.getElementById('fileinfo'),
sectionPhotoEffect = document.getElementById('photoEffect'),
sectionFilterDrawer = document.getElementById('filterDrawer'),
resultPhoto = document.getElementById('resultPhoto'),
sectionSingleView = document.getElementById('singleView');
return {
init: init
};
function init() {
var prefetchImg = new Image();
prefetchImg.src = 'images/effects-thumbs.png';
var prefetchImg2 = new Image();
prefetchImg2.src = 'images/effects/bokeh-stars.png';
viewWidth = (window.innerWidth < finalPhotoDimension) ? window.innerWidth : finalPhotoDimension;
bindEvents();
createGallery();
checkMediaCaptureSupport();
console.log(navigator.userAgent);
}
function showUI(uiElem) {
uiElem.removeAttribute('hidden');
}
function hideUI(uiElem) {
uiElem.setAttribute('hidden', 'hidden');
}
function reInit() {
hideUI(firstRun);
showUI(sectionMain);
hideUI(sectionPhotoEffect);
hideUI(sectionFilterDrawer);
var index = numPhotosSaved-1;
var q = '[data-index="' + index + '"]';
var oldClone = document.querySelector('.swiper-wrapper');
oldClone.parentNode.removeChild(oldClone);
cloneThumbNode();
}
// Note: IE10 and Maxthon return the window.FileReader as 'function' but fail to read image
// I need to write another capability check besides this function
function checkMediaCaptureSupport() {
if(typeof window.FileReader === 'undefined') {
showUI(document.getElementById('warningMediaCapture'));
document.querySelector('.camera').classList.add('no-support'); //disable the button
}
}
function checkHistorySupport() {
if (typeof history.pushState === 'undefined') {
showUI(document.getElementById('warningHistory'));
}
}
function renderFirstRun() {
showUI(firstRun);
var arrowHight = window.innerHeight * .5;
document.getElementsByClassName('arrow-container')[0].style.height = arrowHight + 'px';
}
function bindEvents() {
// Screen orientation/size change
var orientationEvent = ('onorientationchange' in window) ? 'orientationchange' : 'resize';
window.addEventListener(orientationEvent, function() {
displayThumbnails();
}, false);
// A photo taken (or a file chosen)
document.getElementById('camera').addEventListener('change', function() {
showUI(loader);
fileSelected('camera');
}, false);
// Warning Icons
document.getElementById('warnings').addEventListener('click', function(e) {console.log(e.target);
if(e.target.classList.contains('icon-warning')) {
e.target.classList.toggle('full');
} else if(e.target.parentNode.classList.contains('icon-warning')) {
e.target.parentNode.classList.toggle('full');
}
}, false);
// Filter Effects selected
document.getElementById('filterButtons').addEventListener('click', prepFilterEffect, false);
// View a photo in carousel
document.getElementById('thumbnails').addEventListener('click', viewSinglePhoto, false);
// Pop back to Main
window.addEventListener('popstate', function(e){
console.log(history.state);
if (history.state === null || history.state.stage == 'main') {
showUI(sectionMain);
hideUI(sectionSingleView);
history.replaceState({stage: 'main'}, null);
}
}, false);
// popstate alternative
document.getElementById('dismissSingleView').addEventListener('click', function(e){
e.preventDefault();
if (typeof history.pushState === 'function') {
history.go(-1); // pop one state manially
}
showUI(sectionMain);
hideUI(sectionSingleView);
}, false);
// Photo Crop
document.getElementById('cropCancel').addEventListener('click', cancelCrop, false);
document.getElementById('cropApply').addEventListener('click', applyCrop, false);
// Uploading a photo -- not inplemented yet
document.getElementById('uploadButton').addEventListener('click', function(){
//showUI(loader);
//startUpload();
alert('This feature has not implemented yet.')
}, false);
// Uploading a photo -- not inplemented yet
document.getElementById('shareButton').addEventListener('click', function(e){
e.preventDefault();
//showUI(loader);
//startUpload();
alert('This feature has not implemented yet.')
}, false);
// Save a photo in iDB as blob
document.getElementById('saveButton').addEventListener('click', savePhoto, false);
// Delete All - temp
document.getElementById('clearDB').addEventListener('click', function() {
var confirmDelete = confirm('Are you sure you want to delete all photos?');
if(confirmDelete) {
CoreMobCameraiDB.deleteDB(deleteDbCallback);
}
function deleteDbCallback() {
// do stuff
}
}, false);
}
function cancelCrop(e){
imgCrop.removeResult();
document.getElementById('userPhoto').src = '';
document.getElementById('filePickerContainer').reset();
showUI(sectionMain);
hideUI(sectionPhotoCrop);
}
function applyCrop(e){
var newImg = imgCrop.getDataURL();
resultPhoto.src = newImg;
resultPhoto.style.width = resultPhoto.style.height = viewWidth +'px';
// Removing the previously created canvas, if any
var prevEffect = document.getElementById('filteredPhoto');
if(prevEffect) {
prevEffect.parentNode.removeChild(prevEffect);
showUI(resultPhoto);
}
hideUI(sectionPhotoCrop);
showUI(sectionPhotoEffect);
showUI(sectionFilterDrawer);
}
function prepFilterEffect(e) {
var filterButton = getFilterButton(e.target);
if(!filterButton) return;
showUI(loader);
// Removing the previously created canvas
var prevFilteredPhoto = document.getElementById('filteredPhoto');
if(prevFilteredPhoto) {
prevFilteredPhoto.parentNode.removeChild(prevFilteredPhoto);
}
setTimeout(function(){
ApplyEffects[filterButton.id](resultPhoto);
}, 1);
(function () {
var newFilteredPhoto = document.getElementById('filteredPhoto');
if(newFilteredPhoto) {
console.log('canvas loaded yet!');
newFilteredPhoto.style.width = newFilteredPhoto.style.height = viewWidth +'px';
hideUI(loader);
} else {
console.log('canvas not loaded yet...');
setTimeout(arguments.callee, 100);
}
})();
function getFilterButton(target) {
var button;
if(target.classList.contains('filter')) {
button = target;
} else if (target.parentNode.classList.contains('filter')) {
button = target.parentNode;
}
return button;
}
}
/**
* View a single photo from the Gallery
*/
function viewSinglePhoto(e) {
if(e.target.classList.contains('thumb')) {
var index = parseInt(e.target.dataset.index);
var revIndex = numPhotosSaved - index -1;
var swiper = new Swiper('.swiper-container', {
pagination: '.pagination',
initialSlide: revIndex
});
history.pushState({stage: 'singleView'}, null);
showUI(sectionSingleView);
hideUI(sectionMain);
}
}
/**
* Save Photo (either blob or data url string) in iDB
* saving blob is currently only supported by Firefox and IE10
*/
function savePhoto(e) {
var data = {};
var canvas = document.getElementById('filteredPhoto') || document.getElementById('croppedPhoto');
if(!canvas) return;
if(isBlobSupported === false) {
// no blob support. Storing dataURL string instead of blob.
data.photo = canvas.toDataURL('image/jpeg');
data.timestamp = new Date().getTime(); // doing this for Chrome18 :-(
}
else if (canvas.toBlob) {
//canvas.blob() supported. Store blob.
var blob = canvas.toBlob(function(blob){
data.photo = blob;
}, 'image/jpeg');
} else {
// get Base64 dataurl from canvas, then convert it to Blob
var dataUrl = canvas.toDataURL('image/jpeg');
data.photo = util.dataUrlToBlob(dataUrl);
if(data.photo == null) {
// Failed. storing dataURL string instead.
console.log('The browser does not support Blob Constructing.');
data.photo = canvas.toDataURL('image/jpeg');
}
}
data.title = util.stripHtml(window.prompt('Description:'));
CoreMobCameraiDB.putPhotoInDB(data, addSuccess, blobFailure);
function addSuccess(dbPhotos){
numPhotosSaved++;
renderPhotos(dbPhotos);
reInit();
}
function blobFailure() {
// pass Data URL instead of blob
isBlobSupported = false;
data.photo = canvas.toDataURL('image/jpeg');
data.timestamp = new Date().getTime(); // added because Chrome 18 does not support auto-increment id
CoreMobCameraiDB.putPhotoInDB(data, addSuccess);
var warning = document.getElementById('warningIndexedDbBlob');
showUI(warning);
}
}
function createGallery() {
CoreMobCameraiDB.openDB(dbSuccess, dbFailure);
function dbSuccess(dbPhotos) {
renderPhotos(dbPhotos);
displayThumbnails();
cloneThumbNode();
scrollInfinitely();
}
function dbFailure() {
renderFirstRun();
var warning = document.getElementById('warningIndexedDb');
showUI(warning);
document.getElementById('saveButton').setAttribute('disabled', 'disabled');
}
}
// Call back after iDB success
function renderPhotos(dataArray) {
var data;
var wrapper = document.querySelector('.thumbnail-wrapper');
if(dataArray.photo) {
data = dataArray;
var imgUrl = dataArray.photo;
var el = thumb(dataArray.title, imgUrl, numPhotosSaved-1);
wrapper.insertBefore(el, wrapper.firstChild);
return;
}
if (dataArray.length == 0) {
renderFirstRun();
return;
}
numPhotosSaved = dataArray.length;
firstRun.setAttribute('hidden', 'hidden');
function thumb(title, imgUrl, index) {
var el = document.createElement('figure');
el.className = 'thumb';
el.setAttribute('data-index', index);
el.style.backgroundImage = 'url('+imgUrl+')';
var cap = document.createElement('figcaption');
cap.textContent = title;
el.appendChild(cap);
return el;
}
makeThumbsFromArray();
function makeThumbsFromArray() {
var figureEl, imgUrl;
setTimeout(function() {
revokeDataUrls(dataArray.slice())
}, 10);
while (data = dataArray.pop()) {
if(data.photo) {
imgUrl = data.photo;
figureEl = thumb(data.title, imgUrl, dataArray.length);
wrapper.appendChild(figureEl);
}
}
}
function revokeDataUrls(dataArrayCopy) {
for(var i = 0; i < dataArrayCopy.length; i++) {
window.URL.revokeObjectURL(dataArrayCopy[i].photo);
}
}
}
function displayThumbnails(resizeScreen) {
var eachWidth = 105, // css .thumb
thumbsPerRow = (window.innerWidth / eachWidth) >>> 0;
document.getElementById('thumbnails').style.width = thumbsPerRow * eachWidth + 'px';
var container = document.querySelector('.swiper-container');
container.style.width = viewWidth +'px';
container.style.height = (viewWidth + 40) + 'px';
}
function cloneThumbNode() {
var container = document.querySelector('.swiper-container');
var thumbNode = document.querySelector('.thumbnail-wrapper');
var thumbViewNode = thumbNode.cloneNode(true);
thumbViewNode.className = 'swiper-wrapper';
var children = thumbViewNode.children;
for (var i = 0; i < children.length; i++) {
children[i].className = 'swiper-slide';
}
container.appendChild(thumbViewNode);
}
function scrollInfinitely() {
// TO DO
}
function cropAndResize() {
var photoObj = document.getElementById('userPhoto');
imgCrop = new PhotoCrop(photoObj, {
size: {w: finalPhotoDimension, h: finalPhotoDimension}
});
imgCrop.displayResult();
hideUI(sectionMain);
showUI(sectionPhotoCrop);
document.getElementById('textDimension').textContent = finalPhotoDimension + ' x ' + finalPhotoDimension;
var displayPhoto = document.getElementById('croppedPhoto');
displayPhoto.style.width = displayPhoto.style.height = viewWidth +'px';
}
/**
* File Picker
*/
function fileSelected(capture) {
var localFile = document.getElementById(capture).files[0],
imgFmt = /^(image\/bmp|image\/gif|image\/jpeg|image\/png)$/i;
if (! imgFmt.test(localFile.type)) {
alert('The image format, ' + localFile.type + ' is not supported.');
hideUI(loader);
return;
}
if (localFile.size > maxFilesize) { //this should exclude a huge panorama pics
alert('The file size is too large.');
hideUI(loader);
return;
}
// display the selected image
var orig = document.getElementById('userPhoto');
var imgFile = new FileReader();
imgFile.onload = function(e){
// e.target.result contains the Base64 DataURL
orig.onload = function () {
cropAndResize();
displayFileInfo(localFile, orig);
hideUI(loader);
};
orig.src = e.target.result;
};
imgFile.readAsDataURL(localFile);
}
function displayFileInfo(file, img) {
showUI(fileinfo);
document.getElementById('filename').textContent = 'File name: ' + file.name;
document.getElementById('filedim').textContent = 'Original dimension was: ' + img.naturalWidth + ' x ' + img.naturalHeight;
}
/**
* XHR2 File Upload to server --- Not done yet
*/
function startUpload() {
// Get form data - no, not uploading the file from form
//var formData = new FormData(document.getElementById('uploadForm'));
// TO DO ---------
var data = 'some data to be stored. TO DO';
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', uploadProgress, false);
xhr.addEventListener('load', uploadFinish, false);
xhr.addEventListener('error', uploadError, false);
xhr.addEventListener('abort', uploadAbort, false);
xhr.open('POST', '/upload');
xhr.send(data);
}
function uploadProgress(e) {
if (e.lengthComputable) {
// Display the upload progress status
}
}
function uploadFinish(e) {
hideUI(loader);
}
function uploadError(e) {
console.log('An error occurred while uploading the file');
}
function uploadAbort(e) {
console.log('The upload has been aborted by the user or the connection has been dropped.');
}
}());
onload = function() {
CoreMobCamera.init();
}