PairDrop/client/scripts/ui.js

547 lines
16 KiB
JavaScript
Raw Normal View History

2018-09-21 16:05:03 +02:00
const $ = query => document.getElementById(query);
const $$ = query => document.body.querySelector(query);
const isURL = text => /^((https?:\/\/|www)[^\s]+)/g.test(text.toLowerCase());
2018-09-21 23:23:07 +02:00
window.isDownloadSupported = (typeof document.createElement('a').download !== 'undefined');
window.isProductionEnvironment = !window.location.host.startsWith('localhost');
2018-09-21 16:05:03 +02:00
class PeersUI {
constructor() {
Events.on('peer-joined', e => this._onPeerJoined(e.detail));
Events.on('peer-left', e => this._onPeerLeft(e.detail));
Events.on('peers', e => this._onPeers(e.detail));
Events.on('file-progress', e => this._onFileProgress(e.detail));
}
_onPeerJoined(peer) {
if (document.getElementById(peer.id)) return;
const peerUI = new PeerUI(peer);
$$('x-peers').appendChild(peerUI.$el);
}
_onPeers(peers) {
this._clearPeers();
peers.forEach(peer => this._onPeerJoined(peer));
}
_onPeerLeft(peerId) {
const peer = $(peerId);
if (!peer) return;
peer.remove();
}
_onFileProgress(progress) {
const peerId = progress.sender || progress.recipient;
const peer = $(peerId);
if (!peer) return;
peer.ui.setProgress(progress.progress);
}
_clearPeers() {
const $peers = $$('x-peers').innerHTML = '';
}
}
class PeerUI {
html() {
return `
<label class="column center">
<input type="file" multiple>
<x-icon shadow="1">
<svg class="icon"><use xlink:href="#"/></svg>
</x-icon>
<div class="progress">
<div class="circle"></div>
<div class="circle right"></div>
</div>
<div class="name font-subheading"></div>
<div class="status font-body2"></div>
</label>`
}
constructor(peer) {
this._peer = peer;
this._initDom();
this._bindListeners(this.$el);
}
_initDom() {
const el = document.createElement('x-peer');
el.id = this._peer.id;
el.innerHTML = this.html();
el.ui = this;
el.querySelector('svg use').setAttribute('xlink:href', this._icon());
el.querySelector('.name').textContent = this._name();
this.$el = el;
this.$progress = el.querySelector('.progress');
}
_bindListeners(el) {
el.querySelector('input').addEventListener('change', e => this._onFilesSelected(e));
el.addEventListener('drop', e => this._onDrop(e));
el.addEventListener('dragend', e => this._onDragEnd(e));
el.addEventListener('dragleave', e => this._onDragEnd(e));
el.addEventListener('dragover', e => this._onDragOver(e));
el.addEventListener('contextmenu', e => this._onRightClick(e));
el.addEventListener('touchstart', e => this._onTouchStart(e));
el.addEventListener('touchend', e => this._onTouchEnd(e));
// prevent browser's default file drop behavior
Events.on('dragover', e => e.preventDefault());
Events.on('drop', e => e.preventDefault());
}
_name() {
if (this._peer.name.model) {
return this._peer.name.os + ' ' + this._peer.name.model;
}
this._peer.name.os = this._peer.name.os.replace('Mac OS', 'Mac');
return this._peer.name.os + ' ' + this._peer.name.browser;
}
_icon() {
const device = this._peer.name.device || this._peer.name;
if (device.type === 'mobile') {
return '#phone-iphone';
}
if (device.type === 'tablet') {
return '#tablet-mac';
}
return '#desktop-mac';
}
_onFilesSelected(e) {
const $input = e.target;
const files = $input.files;
Events.fire('files-selected', {
files: files,
to: this._peer.id
});
$input.value = null; // reset input
this.setProgress(0.01);
}
setProgress(progress) {
if (progress > 0) {
this.$el.setAttribute('transfer', '1');
}
if (progress > 0.5) {
this.$progress.classList.add('over50');
} else {
this.$progress.classList.remove('over50');
}
const degrees = `rotate(${360 * progress}deg)`;
this.$progress.style.setProperty('--progress', degrees);
if (progress >= 1) {
this.setProgress(0);
this.$el.removeAttribute('transfer');
}
}
_onDrop(e) {
e.preventDefault();
const files = e.dataTransfer.files;
Events.fire('files-selected', {
files: files,
to: this._peer.id
});
this._onDragEnd();
}
_onDragOver() {
this.$el.setAttribute('drop', 1);
}
_onDragEnd() {
this.$el.removeAttribute('drop');
}
_onRightClick(e) {
e.preventDefault();
Events.fire('text-recipient', this._peer.id);
}
_onTouchStart(e) {
this._touchStart = Date.now();
this._touchTimer = setTimeout(_ => this._onTouchEnd(), 610);
}
_onTouchEnd(e) {
if (Date.now() - this._touchStart < 500) {
clearTimeout(this._touchTimer);
} else { // this was a long tap
if (e) e.preventDefault();
Events.fire('text-recipient', this._peer.id);
}
}
}
class Dialog {
constructor(id) {
this.$el = $(id);
this.$el.querySelectorAll('[close]').forEach(el => el.addEventListener('click', e => this.hide()))
this.$autoFocus = this.$el.querySelector('[autofocus]');
}
show() {
this.$el.setAttribute('show', 1);
if (this.$autoFocus) this.$autoFocus.focus();
}
hide() {
this.$el.removeAttribute('show');
document.activeElement.blur();
window.blur();
}
}
class ReceiveDialog extends Dialog {
constructor() {
super('receiveDialog');
Events.on('file-received', e => {
this._nextFile(e.detail);
window.blop.play();
});
this._filesQueue = [];
}
_nextFile(nextFile) {
if (nextFile) this._filesQueue.push(nextFile);
if (this._busy) return;
this._busy = true;
const file = this._filesQueue.shift();
this._displayFile(file);
}
_dequeueFile() {
if (!this._filesQueue.length) { // nothing to do
this._busy = false;
return;
}
// dequeue next file
setTimeout(_ => {
this._busy = false;
this._nextFile();
}, 300);
}
_displayFile(file) {
const $a = this.$el.querySelector('#download');
$a.href = file.url;
$a.download = file.name;
this.$el.querySelector('#fileName').textContent = file.name;
this.$el.querySelector('#fileSize').textContent = this._formatFileSize(file.size);
this.show();
2018-09-21 23:23:07 +02:00
if (window.isDownloadSupported) return;
$a.target = "_blank"; // fallback
2018-09-21 16:05:03 +02:00
}
_formatFileSize(bytes) {
if (bytes >= 1e9) {
return (Math.round(bytes / 1e8) / 10) + ' GB';
} else if (bytes >= 1e6) {
return (Math.round(bytes / 1e5) / 10) + ' MB';
} else if (bytes > 1000) {
return Math.round(bytes / 1000) + ' KB';
} else {
return bytes + ' Bytes';
}
}
hide() {
super.hide();
this._dequeueFile();
}
}
class SendTextDialog extends Dialog {
constructor() {
super('sendTextDialog');
Events.on('text-recipient', e => this._onRecipient(e.detail))
this.$text = this.$el.querySelector('#textInput');
const button = this.$el.querySelector('form');
button.addEventListener('submit', e => this._send(e));
}
_onRecipient(recipient) {
this._recipient = recipient;
this.show();
this.$text.setSelectionRange(0, this.$text.value.length)
}
_send(e) {
e.preventDefault();
Events.fire('send-text', {
to: this._recipient,
text: this.$text.value
});
}
}
class ReceiveTextDialog extends Dialog {
constructor() {
super('receiveTextDialog');
Events.on('text-received', e => this._onText(e.detail))
this.$text = this.$el.querySelector('#text');
const $copy = this.$el.querySelector('#copy');
copy.addEventListener('click', _ => this._onCopy());
}
_onText(e) {
this.$text.innerHTML = '';
const text = e.text;
if (isURL(text)) {
const $a = document.createElement('a');
$a.href = text;
$a.target = '_blank';
$a.textContent = text;
this.$text.appendChild($a);
} else {
this.$text.textContent = text;
}
this.show();
window.blop.play();
}
_onCopy() {
if (!document.copy(this.$text.textContent)) return;
Events.fire('notify-user', 'Copied to clipboard');
}
}
class Toast extends Dialog {
constructor() {
super('toast');
Events.on('notify-user', e => this._onNotfiy(e.detail));
}
_onNotfiy(message) {
this.$el.textContent = message;
this.show();
setTimeout(_ => this.hide(), 3000);
}
}
class Notifications {
constructor() {
// Check if the browser supports notifications
if (!('Notification' in window)) return;
2018-09-21 23:23:07 +02:00
2018-09-21 16:05:03 +02:00
// Check whether notification permissions have already been granted
if (Notification.permission !== 'granted') {
this.$button = $('notification');
this.$button.removeAttribute('hidden');
this.$button.addEventListener('click', e => this._requestPermission());
}
Events.on('text-received', e => this._messageNotification(e.detail.text));
Events.on('file-received', e => this._downloadNotification(e.detail.name));
}
_requestPermission() {
Notification.requestPermission(permission => {
if (permission !== 'granted') {
Events.fire('notify-user', Notifications.PERMISSION_ERROR || 'Error');
return;
}
this._notify('Even more snappy sharing!');
this.$button.setAttribute('hidden', 1);
});
}
_notify(message, body) {
2018-09-21 19:51:29 +02:00
const config = {
2018-09-21 16:05:03 +02:00
body: body,
2018-09-21 19:51:29 +02:00
icon: '/images/logo_transparent_128x128.png',
}
2018-09-21 23:23:07 +02:00
try {
return new Notification(message, config);
} catch (e) {
2018-09-21 19:51:29 +02:00
// android doesn't support "new Notification" if service worker is installed
2018-09-21 23:23:07 +02:00
if (!serviceWorker || !serviceWorker.showNotification) return;
2018-09-21 19:51:29 +02:00
return serviceWorker.showNotification(message, config);
}
2018-09-21 23:23:07 +02:00
2018-09-21 16:05:03 +02:00
}
_messageNotification(message) {
if (isURL(message)) {
const notification = this._notify(message, 'Click to open link');
2018-09-21 23:23:07 +02:00
this._bind(notification, e => window.open(message, '_blank', null, true));
2018-09-21 16:05:03 +02:00
} else {
const notification = this._notify(message, 'Click to copy text');
2018-09-21 23:23:07 +02:00
this._bind(notification, e => this._copyText(message, notification));
2018-09-21 16:05:03 +02:00
}
}
_downloadNotification(message) {
const notification = this._notify(message, 'Click to download');
2018-09-21 23:23:07 +02:00
if (!window.isDownloadSupported) return;
this._bind(notification, e => this._download(notification));
2018-09-21 16:05:03 +02:00
}
2018-09-21 23:23:07 +02:00
_download(notification) {
document.querySelector('x-dialog [download]').click();
notification.close();
}
_copyText(message, notification) {
notification.close();
Squashed commit of the following: commit c04cdad7db20fcd66a8e191c99282d21aa1a4ca2 Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Sat Sep 22 08:47:40 2018 +0200 Cleanup commit 891859680a1565cead8fe3dca771449b5e1e3035 Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Sat Sep 22 05:55:09 2018 +0200 Refactor about page commit 04415ef28f8e7281c13546f168f2582a82bcb34f Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Sat Sep 22 04:44:17 2018 +0200 Cleanup commit 52bd7692e951c5fafdcdb182a69646b78f03884d Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 23:19:54 2018 +0200 Notifications Android & Desktop commit f537b9621350fd1ea6694e7a2a8d3eca1edbf012 Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 22:32:39 2018 +0200 Notifications commit 476cb0ae6525177d7ea0519c9f0c4de67d2bf0f3 Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 22:31:46 2018 +0200 Notifications commit 5a631d3833a63e76d3611dc97ec073e471af58ba Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 21:21:44 2018 +0200 Notfication API on android commit 600d3551f4765d65a4348a33012b57ee370b3da3 Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 21:12:11 2018 +0200 Add will-change commit 3ac40fb3d7467df6c0f66b0d156202cbfbf80f09 Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 21:04:48 2018 +0200 Don’t reconnect if already connecting commit 9c9ca70d05fb2894d4e8113acc3a99a7b582ec78 Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 20:55:15 2018 +0200 Reconnect on rejoin room commit 7194c65c74681883089d21c574275dfc01864d50 Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 20:51:56 2018 +0200 Reconnect on rejoin room commit 0ede41f8d5397e8b7beb62ba6abe2571296f4690 Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 20:34:49 2018 +0200 Cancel keep alive on join room commit 1d9581632fe3a99c2068d8c0cece9345c9397cc8 Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 20:25:54 2018 +0200 Cancel keep alive on join room commit e71564a97cc083b606f144db4de3e35e5e172bfb Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 20:15:55 2018 +0200 Cancel keep alive on join room commit 0731a21d685c35e45985a39e3df32549730953db Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 20:09:49 2018 +0200 Cancel keep alive on join room commit 61697d3abc5430ad58478b12a9b7fc36d8978881 Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 20:01:59 2018 +0200 Cancel keep alive on join room commit b0fd89eb96f69279a01b64ce5db29c020838f87d Merge: 4cf2bed b67afca Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 19:55:32 2018 +0200 Merge remote-tracking branch 'origin/master' into dev # Conflicts: # server/index.js commit 4cf2beda9075d75e1efc6dca3dc0e390612882fd Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 19:49:16 2018 +0200 Fix beforeunload on iphone commit 728aabd449ed8f70231c643d756488fef7431aae Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 19:32:59 2018 +0200 Fix typo in server commit 96e37aef40c7a69203b172655b290732dc236dc3 Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 19:25:01 2018 +0200 Fix typo commit 31e5f635d19a69ebe719194aeb8465368e9f672d Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 19:24:01 2018 +0200 Add connection state handler commit e573d5741979fa48fdbfebed4f3cedd7f82f9ea5 Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 19:17:07 2018 +0200 STUN server tests commit 6a1de2926782ad0ca861b078c31ad3de2bc6e172 Merge: 6317c25 92a5f3b Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 19:15:31 2018 +0200 Merge branch 'dev' of github.com:RobinLinus/snapdrop into dev # Conflicts: # client/scripts/network.js commit 6317c25b10f3d885c8ccc3374fb1e873e2c18f44 Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 19:14:25 2018 +0200 Cleanup; fix STUN servers commit 92a5f3b782b4037beaf9b404683239cf71105586 Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 19:14:25 2018 +0200 Cleanup; fix STUN servers commit e9eeea48e5ea76214971daa1a879b0ae2ba1a196 Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 18:54:52 2018 +0200 Fix notifications on android commit 36ec13d4285b1d8633cc3bddd26df8fddbb8e59e Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 18:53:31 2018 +0200 Fix uncaught error in server commit abf96c02282c5171793f5487880918f4719e8f15 Author: RobinLinus <robinlinus@users.noreply.github.com> Date: Fri Sep 21 16:36:59 2018 +0200 Test
2018-09-24 13:14:11 +02:00
if(!document.copy(message)) return;
2018-09-21 23:23:07 +02:00
this._notify('Copied text to clipboard');
}
_bind(notification, handler) {
if (notification.then) {
notification.then(e => serviceWorker.getNotifications().then(notifications => {
serviceWorker.addEventListener('notificationclick', handler);
}));
} else {
notification.onclick = handler;
}
}
2018-09-21 16:05:03 +02:00
}
class Snapdrop {
constructor() {
const server = new ServerConnection();
const peers = new PeersManager(server);
const peersUI = new PeersUI();
Events.on('load', e => {
const receiveDialog = new ReceiveDialog();
const sendTextDialog = new SendTextDialog();
const receiveTextDialog = new ReceiveTextDialog();
const toast = new Toast();
const notifications = new Notifications();
})
}
}
const snapdrop = new Snapdrop();
document.copy = text => {
// A <span> contains the text to copy
const span = document.createElement('span');
span.textContent = text;
span.style.whiteSpace = 'pre'; // Preserve consecutive spaces and newlines
// Paint the span outside the viewport
span.style.position = 'absolute';
span.style.left = '-9999px';
span.style.top = '-9999px';
const win = window;
const selection = win.getSelection();
win.document.body.appendChild(span);
const range = win.document.createRange();
selection.removeAllRanges();
range.selectNode(span);
selection.addRange(range);
let success = false;
try {
success = win.document.execCommand('copy');
} catch (err) {}
selection.removeAllRanges();
span.remove();
return success;
}
2018-09-21 19:51:29 +02:00
if ('serviceWorker' in navigator) {
2018-09-21 16:05:03 +02:00
navigator.serviceWorker
.register('/service-worker.js')
2018-09-21 19:51:29 +02:00
.then(serviceWorker => {
console.log('Service Worker registered');
window.serviceWorker = serviceWorker
});
2018-09-21 16:05:03 +02:00
}
// Background Animation
Events.on('load', () => {
var requestAnimFrame = (function() {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var c = document.createElement('canvas');
document.body.appendChild(c);
var style = c.style;
style.width = '100%';
style.position = 'absolute';
style.zIndex = -1;
var ctx = c.getContext('2d');
var x0, y0, w, h, dw;
function init() {
w = window.innerWidth;
h = window.innerHeight;
c.width = w;
c.height = h;
var offset = h > 380 ? 100 : 65;
x0 = w / 2;
y0 = h - offset;
dw = Math.max(w, h, 1000) / 13;
drawCircles();
}
window.onresize = init;
function drawCicrle(radius) {
ctx.beginPath();
var color = Math.round(255 * (1 - radius / Math.max(w, h)));
ctx.strokeStyle = 'rgba(' + color + ',' + color + ',' + color + ',0.1)';
ctx.arc(x0, y0, radius, 0, 2 * Math.PI);
ctx.stroke();
ctx.lineWidth = 2;
}
var step = 0;
function drawCircles() {
ctx.clearRect(0, 0, w, h);
for (var i = 0; i < 8; i++) {
drawCicrle(dw * i + step % dw);
}
step += 1;
}
var loading = true;
function animate() {
if (loading || step % dw < dw - 5) {
requestAnimFrame(function() {
drawCircles();
animate();
});
}
}
window.animateBackground = function(l) {
loading = l;
animate();
};
init();
animate();
setTimeout(e => window.animateBackground(false), 3000);
});
Notifications.PERMISSION_ERROR = `
Notifications permission has been blocked
as the user has dismissed the permission prompt several times.
This can be reset in Page Info
which can be accessed by clicking the lock icon next to the URL.`;
document.body.onclick = e => { // safari hack to fix audio
document.body.onclick = null;
if (!(/.*Version.*Safari.*/.test(navigator.userAgent))) return;
blop.play();
}