ui.js 19 KB

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