ui.js 19 KB

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