Chain jQuery calls, do not use events alias and store often used selectors

This commit is contained in:
Johann-S 2017-08-04 22:41:06 +02:00
parent 2dfbee090a
commit 3c640061f0
2 changed files with 139 additions and 106 deletions

View File

@ -9,16 +9,22 @@ const links = require('./links');
const $ = require('jquery'); const $ = require('jquery');
require('jquery-circle-progress'); require('jquery-circle-progress');
$(document).ready(function() { $(() => {
gcmCompliant() gcmCompliant()
.then(function() { .then(() => {
$('.send-new').click(function() { const $downloadBtn = $('#download-btn');
const $sendNew = $('.send-new');
const $dlProgress = $('#dl-progress');
const $progressText = $('.progress-text');
const $title = $('.title');
$sendNew.on('click', () => {
sendEvent('recipient', 'restarted', { sendEvent('recipient', 'restarted', {
cd2: 'completed' cd2: 'completed'
}); });
}); });
$('.legal-links a, .social-links a, #dl-firefox').click(function(target) { $('.legal-links a, .social-links a, #dl-firefox').on('click', function(target) {
const metric = findMetric(target.currentTarget.href); const metric = findMetric(target.currentTarget.href);
// record exited event by recipient // record exited event by recipient
sendEvent('recipient', 'exited', { sendEvent('recipient', 'exited', {
@ -31,17 +37,17 @@ $(document).ready(function() {
const timeToExpiry = Number($('#dl-ttl').text()); const timeToExpiry = Number($('#dl-ttl').text());
//initiate progress bar //initiate progress bar
$('#dl-progress').circleProgress({ $dlProgress.circleProgress({
value: 0.0, value: 0.0,
startAngle: -Math.PI / 2, startAngle: -Math.PI / 2,
fill: '#3B9DFF', fill: '#3B9DFF',
size: 158, size: 158,
animation: { duration: 300 } animation: { duration: 300 }
}); });
$('#download-btn').click(download);
function download() { const download = () => {
// Disable the download button to avoid accidental double clicks. // Disable the download button to avoid accidental double clicks.
$('#download-btn').attr('disabled', 'disabled'); $downloadBtn.attr('disabled', 'disabled');
links.setOpenInNewTab(true); links.setOpenInNewTab(true);
storage.totalDownloads += 1; storage.totalDownloads += 1;
@ -66,9 +72,9 @@ $(document).ready(function() {
$('#download-progress').removeAttr('hidden'); $('#download-progress').removeAttr('hidden');
const percent = progress[0] / progress[1]; const percent = progress[0] / progress[1];
// update progress bar // update progress bar
$('#dl-progress').circleProgress('value', percent); $dlProgress.circleProgress('value', percent);
$('.percent-number').text(`${Math.floor(percent * 100)}`); $('.percent-number').text(`${Math.floor(percent * 100)}`);
$('.progress-text').text( $progressText.text(
`${filename} (${bytes(progress[0], { `${filename} (${bytes(progress[0], {
decimalPlaces: 1, decimalPlaces: 1,
fixedDecimals: true fixedDecimals: true
@ -83,7 +89,7 @@ $(document).ready(function() {
fileReceiver.removeAllListeners('progress'); fileReceiver.removeAllListeners('progress');
window.onunload = null; window.onunload = null;
document.l10n.formatValue('decryptingFile').then(decryptingFile => { document.l10n.formatValue('decryptingFile').then(decryptingFile => {
$('.progress-text').text(decryptingFile); $progressText.text(decryptingFile);
}); });
} else { } else {
downloadEnd = Date.now(); downloadEnd = Date.now();
@ -94,15 +100,15 @@ $(document).ready(function() {
// The file is being hashed to make sure a malicious user hasn't tampered with it // The file is being hashed to make sure a malicious user hasn't tampered with it
if (isStillHashing) { if (isStillHashing) {
document.l10n.formatValue('verifyingFile').then(verifyingFile => { document.l10n.formatValue('verifyingFile').then(verifyingFile => {
$('.progress-text').text(verifyingFile); $progressText.text(verifyingFile);
}); });
} else { } else {
$('.progress-text').text(' '); $progressText.text(' ');
document.l10n document.l10n
.formatValues('downloadNotification', 'downloadFinish') .formatValues('downloadNotification', 'downloadFinish')
.then(translated => { .then(translated => {
notify(translated[0]); notify(translated[0]);
$('.title').text(translated[1]); $title.text(translated[1]);
}); });
} }
}); });
@ -135,9 +141,9 @@ $(document).ready(function() {
location.reload(); location.reload();
} else { } else {
document.l10n.formatValue('errorPageHeader').then(translated => { document.l10n.formatValue('errorPageHeader').then(translated => {
$('.title').text(translated); $title.text(translated);
}); });
$('#download-btn').attr('hidden', true); $downloadBtn.attr('hidden', true);
$('#expired-img').removeAttr('hidden'); $('#expired-img').removeAttr('hidden');
} }
throw err; throw err;
@ -181,6 +187,8 @@ $(document).ready(function() {
}) })
.then(() => links.setOpenInNewTab(false)); .then(() => links.setOpenInNewTab(false));
} }
$downloadBtn.on('click', download);
}) })
.catch(err => { .catch(err => {
sendEvent('sender', 'unsupported', { sendEvent('sender', 'unsupported', {

View File

@ -26,21 +26,30 @@ const allowedCopy = () => {
return support ? document.queryCommandSupported('copy') : false; return support ? document.queryCommandSupported('copy') : false;
}; };
$(document).ready(function() { $(() => {
gcmCompliant() gcmCompliant()
.then(function() { .then(function () {
$('#page-one').removeAttr('hidden'); const $pageOne = $('#page-one');
$('#file-upload').change(onUpload); const $copyBtn = $('#copy-btn');
const $link = $('#link');
const $uploadWindow = $('.upload-window');
const $ulProgress = $('#ul-progress');
const $uploadError = $('#upload-error');
const $uploadProgress = $('#upload-progress');
const $progressText = $('.progress-text');
const $fileList = $('#file-list');
$('.legal-links a, .social-links a, #dl-firefox').click(function(target) { $pageOne.removeAttr('hidden');
const metric = findMetric(target.currentTarget.href); $('#file-upload').on('change', onUpload);
$('.legal-links a, .social-links a, #dl-firefox').on('click', function(target) {
// record exited event by recipient // record exited event by recipient
sendEvent('sender', 'exited', { sendEvent('sender', 'exited', {
cd3: metric cd3: findMetric(target.currentTarget.href)
}); });
}); });
$('#send-new-completed').click(function() { $('#send-new-completed').on('click', function() {
// record restarted event // record restarted event
storage.referrer = 'errored-upload'; storage.referrer = 'errored-upload';
sendEvent('sender', 'restarted', { sendEvent('sender', 'restarted', {
@ -48,7 +57,7 @@ $(document).ready(function() {
}); });
}); });
$('#send-new-error').click(function() { $('#send-new-error').on('click', function() {
// record restarted event // record restarted event
storage.referrer = 'errored-upload'; storage.referrer = 'errored-upload';
sendEvent('sender', 'restarted', { sendEvent('sender', 'restarted', {
@ -56,12 +65,26 @@ $(document).ready(function() {
}); });
}); });
$('body').on('dragover', allowDrop).on('drop', onUpload); $(document.body)
.on('dragover', allowDrop)
.on('drop', onUpload);
// reset copy button // reset copy button
const $copyBtn = $('#copy-btn'); $copyBtn.attr({
$copyBtn.attr('disabled', false); disabled: !allowedCopy(),
$('#link').attr('disabled', false); 'data-l10n-id': 'copyUrlFormButton'
$copyBtn.attr('data-l10n-id', 'copyUrlFormButton'); })
$link.attr('disabled', false);
const toggleHeader = () => {
//hide table header if empty list
if (document.querySelector('tbody').childNodes.length === 1) {
$fileList.attr('hidden', true);
} else {
$fileList.removeAttr('hidden');
}
}
const files = storage.files; const files = storage.files;
if (files.length === 0) { if (files.length === 0) {
@ -76,34 +99,38 @@ $(document).ready(function() {
} }
// copy link to clipboard // copy link to clipboard
$copyBtn.click(() => { $copyBtn.on('click', () => {
if (allowedCopy() && copyToClipboard($('#link').attr('value'))) { if (allowedCopy() && copyToClipboard($link.attr('value'))) {
// record copied event from success screen // record copied event from success screen
sendEvent('sender', 'copied', { sendEvent('sender', 'copied', {
cd4: 'success-screen' cd4: 'success-screen'
}); });
//disable button for 3s //disable button for 3s
$copyBtn.attr('disabled', true); $copyBtn.attr('disabled', true);
$('#link').attr('disabled', true); $link.attr('disabled', true);
$copyBtn.html( $copyBtn.html(
'<img src="/resources/check-16.svg" class="icon-check"></img>' '<img src="/resources/check-16.svg" class="icon-check"></img>'
); );
window.setTimeout(() => { setTimeout(() => {
$copyBtn.attr('disabled', false); $copyBtn.attr({
$('#link').attr('disabled', false); disabled: false,
$copyBtn.attr('data-l10n-id', 'copyUrlFormButton'); 'data-l10n-id': 'copyUrlFormButton'
});
$link.attr('disabled', false);
}, 3000); }, 3000);
} }
}); });
$('.upload-window').on('dragover', () => { $uploadWindow.on('dragover', () => {
$('.upload-window').addClass('ondrag'); $uploadWindow.addClass('ondrag');
}); })
$('.upload-window').on('dragleave', () => { .on('dragleave', () => {
$('.upload-window').removeClass('ondrag'); $uploadWindow.removeClass('ondrag');
}); });
//initiate progress bar //initiate progress bar
$('#ul-progress').circleProgress({ $ulProgress.circleProgress({
value: 0.0, value: 0.0,
startAngle: -Math.PI / 2, startAngle: -Math.PI / 2,
fill: '#3B9DFF', fill: '#3B9DFF',
@ -119,7 +146,7 @@ $(document).ready(function() {
event.preventDefault(); event.preventDefault();
// don't allow upload if not on upload page // don't allow upload if not on upload page
if ($('#page-one').attr('hidden')) { if ($pageOne.attr('hidden')) {
return; return;
} }
@ -128,14 +155,14 @@ $(document).ready(function() {
let file = ''; let file = '';
if (event.type === 'drop') { if (event.type === 'drop') {
if (!event.originalEvent.dataTransfer.files[0]) { if (!event.originalEvent.dataTransfer.files[0]) {
$('.upload-window').removeClass('ondrag'); $uploadWindow.removeClass('ondrag');
return; return;
} }
if ( if (
event.originalEvent.dataTransfer.files.length > 1 || event.originalEvent.dataTransfer.files.length > 1 ||
event.originalEvent.dataTransfer.files[0].size === 0 event.originalEvent.dataTransfer.files[0].size === 0
) { ) {
$('.upload-window').removeClass('ondrag'); $uploadWindow.removeClass('ondrag');
document.l10n document.l10n
.formatValue('uploadPageMultipleFilesAlert') .formatValue('uploadPageMultipleFilesAlert')
.then(str => { .then(str => {
@ -154,17 +181,17 @@ $(document).ready(function() {
.then(alert); .then(alert);
} }
$('#page-one').attr('hidden', true); $pageOne.attr('hidden', true);
$('#upload-error').attr('hidden', true); $uploadError.attr('hidden', true);
$('#upload-progress').removeAttr('hidden'); $uploadProgress.removeAttr('hidden');
document.l10n.formatValue('importingFile').then(importingFile => { document.l10n.formatValue('importingFile').then(importingFile => {
$('.progress-text').text(importingFile); $progressText.text(importingFile);
}); });
//don't allow drag and drop when not on page-one //don't allow drag and drop when not on page-one
$('body').off('drop', onUpload); $(document.body).off('drop', onUpload);
const fileSender = new FileSender(file); const fileSender = new FileSender(file);
$('#cancel-upload').click(() => { $('#cancel-upload').on('click', () => {
fileSender.cancel(); fileSender.cancel();
storage.referrer = 'cancelled-upload'; storage.referrer = 'cancelled-upload';
@ -183,13 +210,11 @@ $(document).ready(function() {
fileSender.on('progress', progress => { fileSender.on('progress', progress => {
const percent = progress[0] / progress[1]; const percent = progress[0] / progress[1];
// update progress bar // update progress bar
$('#ul-progress').circleProgress('value', percent); $ulProgress.circleProgress('value', percent);
$('#ul-progress') $ulProgress.circleProgress().on('circle-animation-end', function() {
.circleProgress() $('.percent-number').text(`${Math.floor(percent * 100)}`);
.on('circle-animation-end', function() { });
$('.percent-number').text(`${Math.floor(percent * 100)}`); $progressText.text(
});
$('.progress-text').text(
`${file.name} (${bytes(progress[0], { `${file.name} (${bytes(progress[0], {
decimalPlaces: 1, decimalPlaces: 1,
fixedDecimals: true fixedDecimals: true
@ -201,7 +226,7 @@ $(document).ready(function() {
// The file is being hashed // The file is being hashed
if (isStillHashing) { if (isStillHashing) {
document.l10n.formatValue('verifyingFile').then(verifyingFile => { document.l10n.formatValue('verifyingFile').then(verifyingFile => {
$('.progress-text').text(verifyingFile); $progressText.text(verifyingFile);
}); });
} }
}); });
@ -211,7 +236,7 @@ $(document).ready(function() {
// The file is being encrypted // The file is being encrypted
if (isStillEncrypting) { if (isStillEncrypting) {
document.l10n.formatValue('encryptingFile').then(encryptingFile => { document.l10n.formatValue('encryptingFile').then(encryptingFile => {
$('.progress-text').text(encryptingFile); $progressText.text(encryptingFile);
}); });
} else { } else {
uploadStart = Date.now(); uploadStart = Date.now();
@ -276,9 +301,9 @@ $(document).ready(function() {
'uploadSuccessConfirmHeader' 'uploadSuccessConfirmHeader'
); );
t = window.setTimeout(() => { t = window.setTimeout(() => {
$('#page-one').attr('hidden', true); $pageOne.attr('hidden', true);
$('#upload-progress').attr('hidden', true); $uploadProgress.attr('hidden', true);
$('#upload-error').attr('hidden', true); $uploadError.attr('hidden', true);
$('#share-link').removeAttr('hidden'); $('#share-link').removeAttr('hidden');
}, 1000); }, 1000);
@ -294,9 +319,9 @@ $(document).ready(function() {
} }
// only show error page when the error is anything other than user cancelling the upload // only show error page when the error is anything other than user cancelling the upload
Raven.captureException(err); Raven.captureException(err);
$('#page-one').attr('hidden', true); $pageOne.attr('hidden', true);
$('#upload-progress').attr('hidden', true); $uploadProgress.attr('hidden', true);
$('#upload-error').removeAttr('hidden'); $uploadError.removeAttr('hidden');
window.clearTimeout(t); window.clearTimeout(t);
// record upload-stopped (errored) by sender // record upload-stopped (errored) by sender
@ -338,7 +363,7 @@ $(document).ready(function() {
} }
//update file table with current files in storage //update file table with current files in storage
function populateFileList(file) { const populateFileList = (file) => {
const row = document.createElement('tr'); const row = document.createElement('tr');
const name = document.createElement('td'); const name = document.createElement('td');
const link = document.createElement('td'); const link = document.createElement('td');
@ -361,12 +386,11 @@ $(document).ready(function() {
const url = file.url.trim() + `#${file.secretKey}`.trim(); const url = file.url.trim() + `#${file.secretKey}`.trim();
$('#link').attr('value', url); $link.attr('value', url);
$('#copy-text').attr( $('#copy-text')
'data-l10n-args', .attr('data-l10n-args', `{"filename": "${file.name}"}`)
'{"filename": "' + file.name + '"}' .attr('data-l10n-id', 'copyUrlFormLabelWithName');
);
$('#copy-text').attr('data-l10n-id', 'copyUrlFormLabelWithName');
$popupText.attr('tabindex', '-1'); $popupText.attr('tabindex', '-1');
name.appendChild(cellText); name.appendChild(cellText);
@ -374,19 +398,21 @@ $(document).ready(function() {
// create delete button // create delete button
const delSpan = document.createElement('span'); const delSpan = document.createElement('span');
$(delSpan).addClass('icon-cancel-1'); $(delSpan)
$(delSpan).attr('data-l10n-id', 'deleteButtonHover'); .addClass('icon-cancel-1')
.attr('data-l10n-id', 'deleteButtonHover');
del.appendChild(delSpan); del.appendChild(delSpan);
const linkSpan = document.createElement('span'); const linkSpan = document.createElement('span');
$(linkSpan).addClass('icon-docs'); $(linkSpan)
$(linkSpan).attr('data-l10n-id', 'copyUrlHover'); .addClass('icon-docs')
link.appendChild(linkSpan); .attr('data-l10n-id', 'copyUrlHover');
link.appendChild(linkSpan);
link.style.color = '#0A8DFF'; link.style.color = '#0A8DFF';
//copy link to clipboard when icon clicked //copy link to clipboard when icon clicked
$copyIcon.click(function() { $copyIcon.on('click', () => {
// record copied event from upload list // record copied event from upload list
sendEvent('sender', 'copied', { sendEvent('sender', 'copied', {
cd4: 'upload-list' cd4: 'upload-list'
@ -395,11 +421,13 @@ $(document).ready(function() {
document.l10n.formatValue('copiedUrl').then(translated => { document.l10n.formatValue('copiedUrl').then(translated => {
link.innerHTML = translated; link.innerHTML = translated;
}); });
window.setTimeout(() => { setTimeout(() => {
const linkImg = document.createElement('img'); const linkImg = document.createElement('img');
$(linkImg).addClass('icon-copy'); $(linkImg)
$(linkImg).attr('data-l10n-id', 'copyUrlHover'); .addClass('icon-copy')
$(linkImg).attr('src', '/resources/copy-16.svg'); .attr('data-l10n-id', 'copyUrlHover')
.attr('src', '/resources/copy-16.svg');
$(link).html(linkImg); $(link).html(linkImg);
}, 500); }, 500);
}); });
@ -415,9 +443,7 @@ $(document).ready(function() {
let hours = Math.floor(minutes / 60); let hours = Math.floor(minutes / 60);
let seconds = Math.floor(countdown / 1000 % 60); let seconds = Math.floor(countdown / 1000 % 60);
poll(); const poll = () => {
function poll() {
countdown = future.getTime() - Date.now(); countdown = future.getTime() - Date.now();
minutes = Math.floor(countdown / 1000 / 60); minutes = Math.floor(countdown / 1000 / 60);
hours = Math.floor(minutes / 60); hours = Math.floor(minutes / 60);
@ -426,7 +452,7 @@ $(document).ready(function() {
if (hours >= 1) { if (hours >= 1) {
expiry.innerHTML = hours + 'h ' + minutes % 60 + 'm'; expiry.innerHTML = hours + 'h ' + minutes % 60 + 'm';
t = window.setTimeout(() => { t = setTimeout(() => {
poll(); poll();
}, 60000); }, 60000);
} else if (hours === 0) { } else if (hours === 0) {
@ -444,6 +470,8 @@ $(document).ready(function() {
} }
} }
poll();
// create popup // create popup
popupDiv.classList.add('popup'); popupDiv.classList.add('popup');
const $popupMessage = $('<div>', { class: 'popup-message' }); const $popupMessage = $('<div>', { class: 'popup-message' });
@ -471,7 +499,7 @@ $(document).ready(function() {
const unexpiredFiles = storage.numFiles; const unexpiredFiles = storage.numFiles;
// delete file // delete file
$popupText.find('.popup-yes').click(e => { $popupText.find('.popup-yes').on('click', e => {
FileSender.delete(file.fileId, file.deleteToken).then(() => { FileSender.delete(file.fileId, file.deleteToken).then(() => {
$(e.target).parents('tr').remove(); $(e.target).parents('tr').remove();
const timeToExpiry = const timeToExpiry =
@ -494,7 +522,7 @@ $(document).ready(function() {
}); });
}); });
document.getElementById('delete-file').onclick = () => { $('#delete-file').on('click', () => {
FileSender.delete(file.fileId, file.deleteToken).then(() => { FileSender.delete(file.fileId, file.deleteToken).then(() => {
const timeToExpiry = const timeToExpiry =
ONE_DAY_IN_MS - (Date.now() - file.creationDate.getTime()); ONE_DAY_IN_MS - (Date.now() - file.creationDate.getTime());
@ -514,35 +542,32 @@ $(document).ready(function() {
location.reload(); location.reload();
}); });
}); });
};
// show popup
$delIcon.click(function() {
$popupText.addClass('show');
$popupText.focus();
}); });
// show popup
$delIcon.on('click', () => {
$popupText
.addClass('show')
.focus();
});
// hide popup // hide popup
$popupText.find('.popup-no').click(function(e) { $popupText.find('.popup-no').on('click', e => {
e.stopPropagation(); e.stopPropagation();
$popupText.removeClass('show'); $popupText.removeClass('show');
}); });
$popupText.click(function(e) {
$popupText.on('click', e => {
e.stopPropagation(); e.stopPropagation();
}); });
//close when popup loses focus //close when popup loses focus
$popupText.blur(() => { $popupText.on('blur', () => {
$popupText.removeClass('show'); $popupText.removeClass('show');
}); });
toggleHeader(); toggleHeader();
} }
function toggleHeader() {
//hide table header if empty list
if (document.querySelector('tbody').childNodes.length === 1) {
$('#file-list').attr('hidden', true);
} else {
$('#file-list').removeAttr('hidden');
}
}
}) })
.catch(err => { .catch(err => {
sendEvent('sender', 'unsupported', { sendEvent('sender', 'unsupported', {