ui.js 19 KB

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