ui.js 18 KB

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