ui.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. const $ = query => document.getElementById(query);
  2. const $$ = query => document.body.querySelector(query);
  3. const isURL = text => /^((https?:\/\/|www)[^\s]+)/g.test(text.toLowerCase());
  4. window.isDownloadSupported = (typeof document.createElement('a').download !== 'undefined');
  5. window.isProductionEnvironment = !window.location.host.startsWith('localhost');
  6. class PeersUI {
  7. constructor() {
  8. Events.on('peer-joined', e => this._onPeerJoined(e.detail));
  9. Events.on('peer-left', e => this._onPeerLeft(e.detail));
  10. Events.on('peers', e => this._onPeers(e.detail));
  11. Events.on('file-progress', e => this._onFileProgress(e.detail));
  12. }
  13. _onPeerJoined(peer) {
  14. if (document.getElementById(peer.id)) return;
  15. const peerUI = new PeerUI(peer);
  16. $$('x-peers').appendChild(peerUI.$el);
  17. }
  18. _onPeers(peers) {
  19. this._clearPeers();
  20. peers.forEach(peer => this._onPeerJoined(peer));
  21. }
  22. _onPeerLeft(peerId) {
  23. const $peer = $(peerId);
  24. if (!$peer) return;
  25. $peer.remove();
  26. }
  27. _onFileProgress(progress) {
  28. const peerId = progress.sender || progress.recipient;
  29. const $peer = $(peerId);
  30. if (!$peer) return;
  31. $peer.ui.setProgress(progress.progress);
  32. }
  33. _clearPeers() {
  34. const $peers = $$('x-peers').innerHTML = '';
  35. }
  36. }
  37. class PeerUI {
  38. html() {
  39. return `
  40. <label class="column center">
  41. <input type="file" multiple>
  42. <x-icon shadow="1">
  43. <svg class="icon"><use xlink:href="#"/></svg>
  44. </x-icon>
  45. <div class="progress">
  46. <div class="circle"></div>
  47. <div class="circle right"></div>
  48. </div>
  49. <div class="name font-subheading"></div>
  50. <div class="status font-body2"></div>
  51. </label>`
  52. }
  53. constructor(peer) {
  54. this._peer = peer;
  55. this._initDom();
  56. this._bindListeners(this.$el);
  57. }
  58. _initDom() {
  59. const el = document.createElement('x-peer');
  60. el.id = this._peer.id;
  61. el.innerHTML = this.html();
  62. el.ui = this;
  63. el.querySelector('svg use').setAttribute('xlink:href', this._icon());
  64. el.querySelector('.name').textContent = this._name();
  65. this.$el = el;
  66. this.$progress = el.querySelector('.progress');
  67. }
  68. _bindListeners(el) {
  69. el.querySelector('input').addEventListener('change', e => this._onFilesSelected(e));
  70. el.addEventListener('drop', e => this._onDrop(e));
  71. el.addEventListener('dragend', e => this._onDragEnd(e));
  72. el.addEventListener('dragleave', e => this._onDragEnd(e));
  73. el.addEventListener('dragover', e => this._onDragOver(e));
  74. el.addEventListener('contextmenu', e => this._onRightClick(e));
  75. el.addEventListener('touchstart', e => this._onTouchStart(e));
  76. el.addEventListener('touchend', e => this._onTouchEnd(e));
  77. // prevent browser's default file drop behavior
  78. Events.on('dragover', e => e.preventDefault());
  79. Events.on('drop', e => e.preventDefault());
  80. }
  81. _name() {
  82. if (this._peer.name.model) {
  83. return this._peer.name.os + ' ' + this._peer.name.model;
  84. }
  85. this._peer.name.os = this._peer.name.os.replace('Mac OS', 'Mac');
  86. return this._peer.name.os + ' ' + this._peer.name.browser;
  87. }
  88. _icon() {
  89. const device = this._peer.name.device || this._peer.name;
  90. if (device.type === 'mobile') {
  91. return '#phone-iphone';
  92. }
  93. if (device.type === 'tablet') {
  94. return '#tablet-mac';
  95. }
  96. return '#desktop-mac';
  97. }
  98. _onFilesSelected(e) {
  99. const $input = e.target;
  100. const files = $input.files;
  101. Events.fire('files-selected', {
  102. files: files,
  103. to: this._peer.id
  104. });
  105. $input.value = null; // reset input
  106. this.setProgress(0.01);
  107. }
  108. setProgress(progress) {
  109. if (progress > 0) {
  110. this.$el.setAttribute('transfer', '1');
  111. }
  112. if (progress > 0.5) {
  113. this.$progress.classList.add('over50');
  114. } else {
  115. this.$progress.classList.remove('over50');
  116. }
  117. const degrees = `rotate(${360 * progress}deg)`;
  118. this.$progress.style.setProperty('--progress', degrees);
  119. if (progress >= 1) {
  120. this.setProgress(0);
  121. this.$el.removeAttribute('transfer');
  122. }
  123. }
  124. _onDrop(e) {
  125. e.preventDefault();
  126. const files = e.dataTransfer.files;
  127. Events.fire('files-selected', {
  128. files: files,
  129. to: this._peer.id
  130. });
  131. this._onDragEnd();
  132. }
  133. _onDragOver() {
  134. this.$el.setAttribute('drop', 1);
  135. }
  136. _onDragEnd() {
  137. this.$el.removeAttribute('drop');
  138. }
  139. _onRightClick(e) {
  140. e.preventDefault();
  141. Events.fire('text-recipient', this._peer.id);
  142. }
  143. _onTouchStart(e) {
  144. this._touchStart = Date.now();
  145. this._touchTimer = setTimeout(_ => this._onTouchEnd(), 610);
  146. }
  147. _onTouchEnd(e) {
  148. if (Date.now() - this._touchStart < 500) {
  149. clearTimeout(this._touchTimer);
  150. } else { // this was a long tap
  151. if (e) e.preventDefault();
  152. Events.fire('text-recipient', this._peer.id);
  153. }
  154. }
  155. }
  156. class Dialog {
  157. constructor(id) {
  158. this.$el = $(id);
  159. this.$el.querySelectorAll('[close]').forEach(el => el.addEventListener('click', e => this.hide()))
  160. this.$autoFocus = this.$el.querySelector('[autofocus]');
  161. }
  162. show() {
  163. this.$el.setAttribute('show', 1);
  164. if (this.$autoFocus) this.$autoFocus.focus();
  165. }
  166. hide() {
  167. this.$el.removeAttribute('show');
  168. document.activeElement.blur();
  169. window.blur();
  170. }
  171. }
  172. class ReceiveDialog extends Dialog {
  173. constructor() {
  174. super('receiveDialog');
  175. Events.on('file-received', e => {
  176. this._nextFile(e.detail);
  177. window.blop.play();
  178. });
  179. this._filesQueue = [];
  180. }
  181. _nextFile(nextFile) {
  182. if (nextFile) this._filesQueue.push(nextFile);
  183. if (this._busy) return;
  184. this._busy = true;
  185. const file = this._filesQueue.shift();
  186. this._displayFile(file);
  187. }
  188. _dequeueFile() {
  189. if (!this._filesQueue.length) { // nothing to do
  190. this._busy = false;
  191. return;
  192. }
  193. // dequeue next file
  194. setTimeout(_ => {
  195. this._busy = false;
  196. this._nextFile();
  197. }, 300);
  198. }
  199. _displayFile(file) {
  200. const $a = this.$el.querySelector('#download');
  201. $a.href = file.url;
  202. $a.download = file.name;
  203. this.$el.querySelector('#fileName').textContent = file.name;
  204. this.$el.querySelector('#fileSize').textContent = this._formatFileSize(file.size);
  205. this.show();
  206. if (window.isDownloadSupported) return;
  207. // $a.target = "_blank"; // fallback
  208. }
  209. _formatFileSize(bytes) {
  210. if (bytes >= 1e9) {
  211. return (Math.round(bytes / 1e8) / 10) + ' GB';
  212. } else if (bytes >= 1e6) {
  213. return (Math.round(bytes / 1e5) / 10) + ' MB';
  214. } else if (bytes > 1000) {
  215. return Math.round(bytes / 1000) + ' KB';
  216. } else {
  217. return bytes + ' Bytes';
  218. }
  219. }
  220. hide() {
  221. super.hide();
  222. this._dequeueFile();
  223. }
  224. }
  225. class SendTextDialog extends Dialog {
  226. constructor() {
  227. super('sendTextDialog');
  228. Events.on('text-recipient', e => this._onRecipient(e.detail))
  229. this.$text = this.$el.querySelector('#textInput');
  230. const button = this.$el.querySelector('form');
  231. button.addEventListener('submit', e => this._send(e));
  232. }
  233. _onRecipient(recipient) {
  234. this._recipient = recipient;
  235. this.show();
  236. this.$text.setSelectionRange(0, this.$text.value.length)
  237. }
  238. _send(e) {
  239. e.preventDefault();
  240. Events.fire('send-text', {
  241. to: this._recipient,
  242. text: this.$text.value
  243. });
  244. }
  245. }
  246. class ReceiveTextDialog extends Dialog {
  247. constructor() {
  248. super('receiveTextDialog');
  249. Events.on('text-received', e => this._onText(e.detail))
  250. this.$text = this.$el.querySelector('#text');
  251. const $copy = this.$el.querySelector('#copy');
  252. copy.addEventListener('click', _ => this._onCopy());
  253. }
  254. _onText(e) {
  255. this.$text.innerHTML = '';
  256. const text = e.text;
  257. if (isURL(text)) {
  258. const $a = document.createElement('a');
  259. $a.href = text;
  260. $a.target = '_blank';
  261. $a.textContent = text;
  262. this.$text.appendChild($a);
  263. } else {
  264. this.$text.textContent = text;
  265. }
  266. this.show();
  267. window.blop.play();
  268. }
  269. _onCopy() {
  270. if (!document.copy(this.$text.textContent)) return;
  271. Events.fire('notify-user', 'Copied to clipboard');
  272. }
  273. }
  274. class Toast extends Dialog {
  275. constructor() {
  276. super('toast');
  277. Events.on('notify-user', e => this._onNotfiy(e.detail));
  278. }
  279. _onNotfiy(message) {
  280. this.$el.textContent = message;
  281. this.show();
  282. setTimeout(_ => this.hide(), 3000);
  283. }
  284. }
  285. class Notifications {
  286. constructor() {
  287. // Check if the browser supports notifications
  288. if (!('Notification' in window)) return;
  289. // Check whether notification permissions have already been granted
  290. if (Notification.permission !== 'granted') {
  291. this.$button = $('notification');
  292. this.$button.removeAttribute('hidden');
  293. this.$button.addEventListener('click', e => this._requestPermission());
  294. }
  295. Events.on('text-received', e => this._messageNotification(e.detail.text));
  296. Events.on('file-received', e => this._downloadNotification(e.detail.name));
  297. }
  298. _requestPermission() {
  299. Notification.requestPermission(permission => {
  300. if (permission !== 'granted') {
  301. Events.fire('notify-user', Notifications.PERMISSION_ERROR || 'Error');
  302. return;
  303. }
  304. this._notify('Even more snappy sharing!');
  305. this.$button.setAttribute('hidden', 1);
  306. });
  307. }
  308. _notify(message, body) {
  309. const config = {
  310. body: body,
  311. icon: '/images/logo_transparent_128x128.png',
  312. }
  313. try {
  314. return new Notification(message, config);
  315. } catch (e) {
  316. // android doesn't support "new Notification" if service worker is installed
  317. if (!serviceWorker || !serviceWorker.showNotification) return;
  318. return serviceWorker.showNotification(message, config);
  319. }
  320. }
  321. _messageNotification(message) {
  322. if (isURL(message)) {
  323. const notification = this._notify(message, 'Click to open link');
  324. this._bind(notification, e => window.open(message, '_blank', null, true));
  325. } else {
  326. const notification = this._notify(message, 'Click to copy text');
  327. this._bind(notification, e => this._copyText(message, notification));
  328. }
  329. }
  330. _downloadNotification(message) {
  331. const notification = this._notify(message, 'Click to download');
  332. if (!window.isDownloadSupported) return;
  333. this._bind(notification, e => this._download(notification));
  334. }
  335. _download(notification) {
  336. document.querySelector('x-dialog [download]').click();
  337. notification.close();
  338. }
  339. _copyText(message, notification) {
  340. notification.close();
  341. if(!document.copy(message)) return;
  342. this._notify('Copied text to clipboard');
  343. }
  344. _bind(notification, handler) {
  345. if (notification.then) {
  346. notification.then(e => serviceWorker.getNotifications().then(notifications => {
  347. serviceWorker.addEventListener('notificationclick', handler);
  348. }));
  349. } else {
  350. notification.onclick = handler;
  351. }
  352. }
  353. }
  354. class Snapdrop {
  355. constructor() {
  356. const server = new ServerConnection();
  357. const peers = new PeersManager(server);
  358. const peersUI = new PeersUI();
  359. Events.on('load', e => {
  360. const receiveDialog = new ReceiveDialog();
  361. const sendTextDialog = new SendTextDialog();
  362. const receiveTextDialog = new ReceiveTextDialog();
  363. const toast = new Toast();
  364. const notifications = new Notifications();
  365. })
  366. }
  367. }
  368. const snapdrop = new Snapdrop();
  369. document.copy = text => {
  370. // A <span> contains the text to copy
  371. const span = document.createElement('span');
  372. span.textContent = text;
  373. span.style.whiteSpace = 'pre'; // Preserve consecutive spaces and newlines
  374. // Paint the span outside the viewport
  375. span.style.position = 'absolute';
  376. span.style.left = '-9999px';
  377. span.style.top = '-9999px';
  378. const win = window;
  379. const selection = win.getSelection();
  380. win.document.body.appendChild(span);
  381. const range = win.document.createRange();
  382. selection.removeAllRanges();
  383. range.selectNode(span);
  384. selection.addRange(range);
  385. let success = false;
  386. try {
  387. success = win.document.execCommand('copy');
  388. } catch (err) {}
  389. selection.removeAllRanges();
  390. span.remove();
  391. return success;
  392. }
  393. if ('serviceWorker' in navigator) {
  394. navigator.serviceWorker
  395. .register('/service-worker.js')
  396. .then(serviceWorker => {
  397. console.log('Service Worker registered');
  398. window.serviceWorker = serviceWorker
  399. });
  400. }
  401. // Background Animation
  402. Events.on('load', () => {
  403. var requestAnimFrame = (function() {
  404. return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
  405. function(callback) {
  406. window.setTimeout(callback, 1000 / 60);
  407. };
  408. })();
  409. var c = document.createElement('canvas');
  410. document.body.appendChild(c);
  411. var style = c.style;
  412. style.width = '100%';
  413. style.position = 'absolute';
  414. style.zIndex = -1;
  415. var ctx = c.getContext('2d');
  416. var x0, y0, w, h, dw;
  417. function init() {
  418. w = window.innerWidth;
  419. h = window.innerHeight;
  420. c.width = w;
  421. c.height = h;
  422. var offset = h > 380 ? 100 : 65;
  423. x0 = w / 2;
  424. y0 = h - offset;
  425. dw = Math.max(w, h, 1000) / 13;
  426. drawCircles();
  427. }
  428. window.onresize = init;
  429. function drawCicrle(radius) {
  430. ctx.beginPath();
  431. var color = Math.round(255 * (1 - radius / Math.max(w, h)));
  432. ctx.strokeStyle = 'rgba(' + color + ',' + color + ',' + color + ',0.1)';
  433. ctx.arc(x0, y0, radius, 0, 2 * Math.PI);
  434. ctx.stroke();
  435. ctx.lineWidth = 2;
  436. }
  437. var step = 0;
  438. function drawCircles() {
  439. ctx.clearRect(0, 0, w, h);
  440. for (var i = 0; i < 8; i++) {
  441. drawCicrle(dw * i + step % dw);
  442. }
  443. step += 1;
  444. }
  445. var loading = true;
  446. function animate() {
  447. if (loading || step % dw < dw - 5) {
  448. requestAnimFrame(function() {
  449. drawCircles();
  450. animate();
  451. });
  452. }
  453. }
  454. window.animateBackground = function(l) {
  455. loading = l;
  456. animate();
  457. };
  458. init();
  459. animate();
  460. setTimeout(e => window.animateBackground(false), 3000);
  461. });
  462. Notifications.PERMISSION_ERROR = `
  463. Notifications permission has been blocked
  464. as the user has dismissed the permission prompt several times.
  465. This can be reset in Page Info
  466. which can be accessed by clicking the lock icon next to the URL.`;
  467. document.body.onclick = e => { // safari hack to fix audio
  468. document.body.onclick = null;
  469. if (!(/.*Version.*Safari.*/.test(navigator.userAgent))) return;
  470. blop.play();
  471. }