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. class PeersUI {
  8. constructor() {
  9. Events.on('peer-joined', e => this._onPeerJoined(e.detail));
  10. Events.on('peer-left', e => this._onPeerLeft(e.detail));
  11. Events.on('peers', e => this._onPeers(e.detail));
  12. Events.on('file-progress', e => this._onFileProgress(e.detail));
  13. Events.on('paste', e => this._onPaste(e));
  14. }
  15. _onPeerJoined(peer) {
  16. if (document.getElementById(peer.id)) return;
  17. const peerUI = new PeerUI(peer);
  18. $$('x-peers').appendChild(peerUI.$el);
  19. }
  20. _onPeers(peers) {
  21. this._clearPeers();
  22. peers.forEach(peer => this._onPeerJoined(peer));
  23. }
  24. _onPeerLeft(peerId) {
  25. const $peer = $(peerId);
  26. if (!$peer) return;
  27. $peer.remove();
  28. }
  29. _onFileProgress(progress) {
  30. const peerId = progress.sender || progress.recipient;
  31. const $peer = $(peerId);
  32. if (!$peer) return;
  33. $peer.ui.setProgress(progress.progress);
  34. }
  35. _clearPeers() {
  36. const $peers = $$('x-peers').innerHTML = '';
  37. }
  38. _onPaste(e) {
  39. const files = e.clipboardData.files || e.clipboardData.items
  40. .filter(i => i.type.indexOf('image') > -1)
  41. .map(i => i.getAsFile());
  42. const peers = document.querySelectorAll('x-peer');
  43. // send the pasted image content to the only peer if there is one
  44. // otherwise, select the peer somehow by notifying the client that
  45. // "image data has been pasted, click the client to which to send it"
  46. // not implemented
  47. if (files.length > 0 && peers.length === 1) {
  48. Events.fire('files-selected', {
  49. files: files,
  50. to: $$('x-peer').id
  51. });
  52. }
  53. }
  54. }
  55. class PeerUI {
  56. html() {
  57. return `
  58. <label class="column center">
  59. <input type="file" multiple>
  60. <x-icon shadow="1">
  61. <svg class="icon"><use xlink:href="#"/></svg>
  62. </x-icon>
  63. <div class="progress">
  64. <div class="circle"></div>
  65. <div class="circle right"></div>
  66. </div>
  67. <div class="name font-subheading"></div>
  68. <div class="status font-body2"></div>
  69. </label>`
  70. }
  71. constructor(peer) {
  72. this._peer = peer;
  73. this._initDom();
  74. this._bindListeners(this.$el);
  75. }
  76. _initDom() {
  77. const el = document.createElement('x-peer');
  78. el.id = this._peer.id;
  79. el.innerHTML = this.html();
  80. el.ui = this;
  81. el.querySelector('svg use').setAttribute('xlink:href', this._icon());
  82. el.querySelector('.name').textContent = this._name();
  83. this.$el = el;
  84. this.$progress = el.querySelector('.progress');
  85. }
  86. _bindListeners(el) {
  87. el.querySelector('input').addEventListener('change', e => this._onFilesSelected(e));
  88. el.addEventListener('drop', e => this._onDrop(e));
  89. el.addEventListener('dragend', e => this._onDragEnd(e));
  90. el.addEventListener('dragleave', e => this._onDragEnd(e));
  91. el.addEventListener('dragover', e => this._onDragOver(e));
  92. el.addEventListener('contextmenu', e => this._onRightClick(e));
  93. el.addEventListener('touchstart', e => this._onTouchStart(e));
  94. el.addEventListener('touchend', e => this._onTouchEnd(e));
  95. // prevent browser's default file drop behavior
  96. Events.on('dragover', e => e.preventDefault());
  97. Events.on('drop', e => e.preventDefault());
  98. }
  99. _name() {
  100. return this._peer.name.displayName;
  101. }
  102. _icon() {
  103. const device = this._peer.name.device || this._peer.name;
  104. if (device.type === 'mobile') {
  105. return '#phone-iphone';
  106. }
  107. if (device.type === 'tablet') {
  108. return '#tablet-mac';
  109. }
  110. return '#desktop-mac';
  111. }
  112. _onFilesSelected(e) {
  113. const $input = e.target;
  114. const files = $input.files;
  115. Events.fire('files-selected', {
  116. files: files,
  117. to: this._peer.id
  118. });
  119. $input.value = null; // reset input
  120. this.setProgress(0.01);
  121. }
  122. setProgress(progress) {
  123. if (progress > 0) {
  124. this.$el.setAttribute('transfer', '1');
  125. }
  126. if (progress > 0.5) {
  127. this.$progress.classList.add('over50');
  128. } else {
  129. this.$progress.classList.remove('over50');
  130. }
  131. const degrees = `rotate(${360 * progress}deg)`;
  132. this.$progress.style.setProperty('--progress', degrees);
  133. if (progress >= 1) {
  134. this.setProgress(0);
  135. this.$el.removeAttribute('transfer');
  136. }
  137. }
  138. _onDrop(e) {
  139. e.preventDefault();
  140. const files = e.dataTransfer.files;
  141. Events.fire('files-selected', {
  142. files: files,
  143. to: this._peer.id
  144. });
  145. this._onDragEnd();
  146. }
  147. _onDragOver() {
  148. this.$el.setAttribute('drop', 1);
  149. }
  150. _onDragEnd() {
  151. this.$el.removeAttribute('drop');
  152. }
  153. _onRightClick(e) {
  154. e.preventDefault();
  155. Events.fire('text-recipient', this._peer.id);
  156. }
  157. _onTouchStart(e) {
  158. this._touchStart = Date.now();
  159. this._touchTimer = setTimeout(_ => this._onTouchEnd(), 610);
  160. }
  161. _onTouchEnd(e) {
  162. if (Date.now() - this._touchStart < 500) {
  163. clearTimeout(this._touchTimer);
  164. } else { // this was a long tap
  165. if (e) e.preventDefault();
  166. Events.fire('text-recipient', this._peer.id);
  167. }
  168. }
  169. }
  170. class Dialog {
  171. constructor(id) {
  172. this.$el = $(id);
  173. this.$el.querySelectorAll('[close]').forEach(el => el.addEventListener('click', e => this.hide()))
  174. this.$autoFocus = this.$el.querySelector('[autofocus]');
  175. }
  176. show() {
  177. this.$el.setAttribute('show', 1);
  178. if (this.$autoFocus) this.$autoFocus.focus();
  179. }
  180. hide() {
  181. this.$el.removeAttribute('show');
  182. document.activeElement.blur();
  183. window.blur();
  184. }
  185. }
  186. class ReceiveDialog extends Dialog {
  187. constructor() {
  188. super('receiveDialog');
  189. Events.on('file-received', e => {
  190. this._nextFile(e.detail);
  191. window.blop.play();
  192. });
  193. this._filesQueue = [];
  194. }
  195. _nextFile(nextFile) {
  196. if (nextFile) this._filesQueue.push(nextFile);
  197. if (this._busy) return;
  198. this._busy = true;
  199. const file = this._filesQueue.shift();
  200. this._displayFile(file);
  201. }
  202. _dequeueFile() {
  203. if (!this._filesQueue.length) { // nothing to do
  204. this._busy = false;
  205. return;
  206. }
  207. // dequeue next file
  208. setTimeout(_ => {
  209. this._busy = false;
  210. this._nextFile();
  211. }, 300);
  212. }
  213. _displayFile(file) {
  214. const $a = this.$el.querySelector('#download');
  215. const url = URL.createObjectURL(file.blob);
  216. $a.href = url;
  217. $a.download = file.name;
  218. this.$el.querySelector('#fileName').textContent = file.name;
  219. this.$el.querySelector('#fileSize').textContent = this._formatFileSize(file.size);
  220. this.show();
  221. if (window.isDownloadSupported) return;
  222. // fallback for iOS
  223. $a.target = '_blank';
  224. const reader = new FileReader();
  225. reader.onload = e => $a.href = reader.result;
  226. reader.readAsDataURL(file.blob);
  227. }
  228. _formatFileSize(bytes) {
  229. if (bytes >= 1e9) {
  230. return (Math.round(bytes / 1e8) / 10) + ' GB';
  231. } else if (bytes >= 1e6) {
  232. return (Math.round(bytes / 1e5) / 10) + ' MB';
  233. } else if (bytes > 1000) {
  234. return Math.round(bytes / 1000) + ' KB';
  235. } else {
  236. return bytes + ' Bytes';
  237. }
  238. }
  239. hide() {
  240. super.hide();
  241. this._dequeueFile();
  242. }
  243. }
  244. class SendTextDialog extends Dialog {
  245. constructor() {
  246. super('sendTextDialog');
  247. Events.on('text-recipient', e => this._onRecipient(e.detail))
  248. this.$text = this.$el.querySelector('#textInput');
  249. const button = this.$el.querySelector('form');
  250. button.addEventListener('submit', e => this._send(e));
  251. }
  252. _onRecipient(recipient) {
  253. this._recipient = recipient;
  254. this._handleShareTargetText();
  255. this.show();
  256. this.$text.setSelectionRange(0, this.$text.value.length)
  257. }
  258. _handleShareTargetText() {
  259. if (!window.shareTargetText) return;
  260. this.$text.value = window.shareTargetText;
  261. window.shareTargetText = '';
  262. }
  263. _send(e) {
  264. e.preventDefault();
  265. Events.fire('send-text', {
  266. to: this._recipient,
  267. text: this.$text.value
  268. });
  269. }
  270. }
  271. class ReceiveTextDialog extends Dialog {
  272. constructor() {
  273. super('receiveTextDialog');
  274. Events.on('text-received', e => this._onText(e.detail))
  275. this.$text = this.$el.querySelector('#text');
  276. const $copy = this.$el.querySelector('#copy');
  277. copy.addEventListener('click', _ => this._onCopy());
  278. }
  279. _onText(e) {
  280. this.$text.innerHTML = '';
  281. const text = e.text;
  282. if (isURL(text)) {
  283. const $a = document.createElement('a');
  284. $a.href = text;
  285. $a.target = '_blank';
  286. $a.textContent = text;
  287. this.$text.appendChild($a);
  288. } else {
  289. this.$text.textContent = text;
  290. }
  291. this.show();
  292. window.blop.play();
  293. }
  294. _onCopy() {
  295. if (!document.copy(this.$text.textContent)) return;
  296. Events.fire('notify-user', 'Copied to clipboard');
  297. }
  298. }
  299. class Toast extends Dialog {
  300. constructor() {
  301. super('toast');
  302. Events.on('notify-user', e => this._onNotfiy(e.detail));
  303. }
  304. _onNotfiy(message) {
  305. this.$el.textContent = message;
  306. this.show();
  307. setTimeout(_ => this.hide(), 3000);
  308. }
  309. }
  310. class Notifications {
  311. constructor() {
  312. // Check if the browser supports notifications
  313. if (!('Notification' in window)) return;
  314. // Check whether notification permissions have already been granted
  315. if (Notification.permission !== 'granted') {
  316. this.$button = $('notification');
  317. this.$button.removeAttribute('hidden');
  318. this.$button.addEventListener('click', e => this._requestPermission());
  319. }
  320. Events.on('text-received', e => this._messageNotification(e.detail.text));
  321. Events.on('file-received', e => this._downloadNotification(e.detail.name));
  322. }
  323. _requestPermission() {
  324. Notification.requestPermission(permission => {
  325. if (permission !== 'granted') {
  326. Events.fire('notify-user', Notifications.PERMISSION_ERROR || 'Error');
  327. return;
  328. }
  329. this._notify('Even more snappy sharing!');
  330. this.$button.setAttribute('hidden', 1);
  331. });
  332. }
  333. _notify(message, body, closeTimeout = 20000) {
  334. const config = {
  335. body: body,
  336. icon: '/images/logo_transparent_128x128.png',
  337. }
  338. let notification;
  339. try {
  340. notification = new Notification(message, config);
  341. } catch (e) {
  342. // Android doesn't support "new Notification" if service worker is installed
  343. if (!serviceWorker || !serviceWorker.showNotification) return;
  344. notification = serviceWorker.showNotification(message, config);
  345. }
  346. // Notification is persistent on Android. We have to close it manually
  347. if (closeTimeout) {
  348. setTimeout(_ => notification.close(), closeTimeout);
  349. }
  350. return notification;
  351. }
  352. _messageNotification(message) {
  353. if (isURL(message)) {
  354. const notification = this._notify(message, 'Click to open link');
  355. this._bind(notification, e => window.open(message, '_blank', null, true));
  356. } else {
  357. const notification = this._notify(message, 'Click to copy text');
  358. this._bind(notification, e => this._copyText(message, notification));
  359. }
  360. }
  361. _downloadNotification(message) {
  362. const notification = this._notify(message, 'Click to download');
  363. if (!window.isDownloadSupported) return;
  364. this._bind(notification, e => this._download(notification));
  365. }
  366. _download(notification) {
  367. document.querySelector('x-dialog [download]').click();
  368. notification.close();
  369. }
  370. _copyText(message, notification) {
  371. notification.close();
  372. if (!document.copy(message)) return;
  373. this._notify('Copied text to clipboard');
  374. }
  375. _bind(notification, handler) {
  376. if (notification.then) {
  377. notification.then(e => serviceWorker.getNotifications().then(notifications => {
  378. serviceWorker.addEventListener('notificationclick', handler);
  379. }));
  380. } else {
  381. notification.onclick = handler;
  382. }
  383. }
  384. }
  385. class NetworkStatusUI {
  386. constructor() {
  387. window.addEventListener('offline', e => this._showOfflineMessage(), false);
  388. window.addEventListener('online', e => this._showOnlineMessage(), false);
  389. if (!navigator.onLine) this._showOfflineMessage();
  390. }
  391. _showOfflineMessage() {
  392. Events.fire('notify-user', 'You are offline');
  393. }
  394. _showOnlineMessage() {
  395. Events.fire('notify-user', 'You are back online');
  396. }
  397. }
  398. class WebShareTargetUI {
  399. constructor() {
  400. const parsedUrl = new URL(window.location);
  401. const title = parsedUrl.searchParams.get('title');
  402. const text = parsedUrl.searchParams.get('text');
  403. const url = parsedUrl.searchParams.get('url');
  404. let shareTargetText = title ? title : '';
  405. shareTargetText += text ? shareTargetText ? ' ' + text : text : '';
  406. shareTargetText += url ? shareTargetText ? ' ' + url : url : '';
  407. if (!shareTargetText) return;
  408. window.shareTargetText = shareTargetText;
  409. history.pushState({}, 'URL Rewrite', '/');
  410. console.log('Shared Target Text:', '"' + shareTargetText + '"');
  411. }
  412. }
  413. class Snapdrop {
  414. constructor() {
  415. const server = new ServerConnection();
  416. const peers = new PeersManager(server);
  417. const peersUI = new PeersUI();
  418. Events.on('load', e => {
  419. const receiveDialog = new ReceiveDialog();
  420. const sendTextDialog = new SendTextDialog();
  421. const receiveTextDialog = new ReceiveTextDialog();
  422. const toast = new Toast();
  423. const notifications = new Notifications();
  424. const networkStatusUI = new NetworkStatusUI();
  425. const webShareTargetUI = new WebShareTargetUI();
  426. });
  427. // set display name
  428. Events.on('displayName', e => {
  429. $("displayName").textContent = "You are known as " + e.detail.message;
  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. }