ui.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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. const range = document.createRange();
  275. const sel = window.getSelection();
  276. range.selectNodeContents(this.$text);
  277. sel.removeAllRanges();
  278. sel.addRange(range);
  279. }
  280. _handleShareTargetText() {
  281. if (!window.shareTargetText) return;
  282. this.$text.textContent = window.shareTargetText;
  283. window.shareTargetText = '';
  284. }
  285. _send(e) {
  286. e.preventDefault();
  287. Events.fire('send-text', {
  288. to: this._recipient,
  289. text: this.$text.innerText
  290. });
  291. }
  292. }
  293. class ReceiveTextDialog extends Dialog {
  294. constructor() {
  295. super('receiveTextDialog');
  296. Events.on('text-received', e => this._onText(e.detail))
  297. this.$text = this.$el.querySelector('#text');
  298. const $copy = this.$el.querySelector('#copy');
  299. copy.addEventListener('click', _ => this._onCopy());
  300. }
  301. _onText(e) {
  302. this.$text.innerHTML = '';
  303. const text = e.text;
  304. if (isURL(text)) {
  305. const $a = document.createElement('a');
  306. $a.href = text;
  307. $a.target = '_blank';
  308. $a.textContent = text;
  309. this.$text.appendChild($a);
  310. } else {
  311. this.$text.textContent = text;
  312. }
  313. this.show();
  314. window.blop.play();
  315. }
  316. async _onCopy() {
  317. await navigator.clipboard.writeText(this.$text.textContent);
  318. Events.fire('notify-user', 'Copied to clipboard');
  319. }
  320. }
  321. class Toast extends Dialog {
  322. constructor() {
  323. super('toast');
  324. Events.on('notify-user', e => this._onNotfiy(e.detail));
  325. }
  326. _onNotfiy(message) {
  327. this.$el.textContent = message;
  328. this.show();
  329. setTimeout(_ => this.hide(), 3000);
  330. }
  331. }
  332. class Notifications {
  333. constructor() {
  334. // Check if the browser supports notifications
  335. if (!('Notification' in window)) return;
  336. // Check whether notification permissions have already been granted
  337. if (Notification.permission !== 'granted') {
  338. this.$button = $('notification');
  339. this.$button.removeAttribute('hidden');
  340. this.$button.addEventListener('click', e => this._requestPermission());
  341. }
  342. Events.on('text-received', e => this._messageNotification(e.detail.text));
  343. Events.on('file-received', e => this._downloadNotification(e.detail.name));
  344. }
  345. _requestPermission() {
  346. Notification.requestPermission(permission => {
  347. if (permission !== 'granted') {
  348. Events.fire('notify-user', Notifications.PERMISSION_ERROR || 'Error');
  349. return;
  350. }
  351. this._notify('Even more snappy sharing!');
  352. this.$button.setAttribute('hidden', 1);
  353. });
  354. }
  355. _notify(message, body, closeTimeout = 20000) {
  356. const config = {
  357. body: body,
  358. icon: '/images/logo_transparent_128x128.png',
  359. }
  360. let notification;
  361. try {
  362. notification = new Notification(message, config);
  363. } catch (e) {
  364. // Android doesn't support "new Notification" if service worker is installed
  365. if (!serviceWorker || !serviceWorker.showNotification) return;
  366. notification = serviceWorker.showNotification(message, config);
  367. }
  368. // Notification is persistent on Android. We have to close it manually
  369. if (closeTimeout) {
  370. setTimeout(_ => notification.close(), closeTimeout);
  371. }
  372. return notification;
  373. }
  374. _messageNotification(message) {
  375. if (isURL(message)) {
  376. const notification = this._notify(message, 'Click to open link');
  377. this._bind(notification, e => window.open(message, '_blank', null, true));
  378. } else {
  379. const notification = this._notify(message, 'Click to copy text');
  380. this._bind(notification, e => this._copyText(message, notification));
  381. }
  382. }
  383. _downloadNotification(message) {
  384. const notification = this._notify(message, 'Click to download');
  385. if (!window.isDownloadSupported) return;
  386. this._bind(notification, e => this._download(notification));
  387. }
  388. _download(notification) {
  389. document.querySelector('x-dialog [download]').click();
  390. notification.close();
  391. }
  392. _copyText(message, notification) {
  393. notification.close();
  394. if (!navigator.clipboard.writeText(message)) return;
  395. this._notify('Copied text to clipboard');
  396. }
  397. _bind(notification, handler) {
  398. if (notification.then) {
  399. notification.then(e => serviceWorker.getNotifications().then(notifications => {
  400. serviceWorker.addEventListener('notificationclick', handler);
  401. }));
  402. } else {
  403. notification.onclick = handler;
  404. }
  405. }
  406. }
  407. class NetworkStatusUI {
  408. constructor() {
  409. window.addEventListener('offline', e => this._showOfflineMessage(), false);
  410. window.addEventListener('online', e => this._showOnlineMessage(), false);
  411. if (!navigator.onLine) this._showOfflineMessage();
  412. }
  413. _showOfflineMessage() {
  414. Events.fire('notify-user', 'You are offline');
  415. }
  416. _showOnlineMessage() {
  417. Events.fire('notify-user', 'You are back online');
  418. }
  419. }
  420. class WebShareTargetUI {
  421. constructor() {
  422. const parsedUrl = new URL(window.location);
  423. const title = parsedUrl.searchParams.get('title');
  424. const text = parsedUrl.searchParams.get('text');
  425. const url = parsedUrl.searchParams.get('url');
  426. let shareTargetText = title ? title : '';
  427. shareTargetText += text ? shareTargetText ? ' ' + text : text : '';
  428. if(url) shareTargetText = url; // We share only the Link - no text. Because link-only text becomes clickable.
  429. if (!shareTargetText) return;
  430. window.shareTargetText = shareTargetText;
  431. history.pushState({}, 'URL Rewrite', '/');
  432. console.log('Shared Target Text:', '"' + shareTargetText + '"');
  433. }
  434. }
  435. class Snapdrop {
  436. constructor() {
  437. const server = new ServerConnection();
  438. const peers = new PeersManager(server);
  439. const peersUI = new PeersUI();
  440. Events.on('load', e => {
  441. const receiveDialog = new ReceiveDialog();
  442. const sendTextDialog = new SendTextDialog();
  443. const receiveTextDialog = new ReceiveTextDialog();
  444. const toast = new Toast();
  445. const notifications = new Notifications();
  446. const networkStatusUI = new NetworkStatusUI();
  447. const webShareTargetUI = new WebShareTargetUI();
  448. });
  449. }
  450. }
  451. const snapdrop = new Snapdrop();
  452. if ('serviceWorker' in navigator) {
  453. navigator.serviceWorker.register('/service-worker.js')
  454. .then(serviceWorker => {
  455. console.log('Service Worker registered');
  456. window.serviceWorker = serviceWorker
  457. });
  458. }
  459. window.addEventListener('beforeinstallprompt', e => {
  460. if (window.matchMedia('(display-mode: standalone)').matches) {
  461. // don't display install banner when installed
  462. return e.preventDefault();
  463. } else {
  464. const btn = document.querySelector('#install')
  465. btn.hidden = false;
  466. btn.onclick = _ => e.prompt();
  467. return e.preventDefault();
  468. }
  469. });
  470. // Background Animation
  471. Events.on('load', () => {
  472. let c = document.createElement('canvas');
  473. document.body.appendChild(c);
  474. let style = c.style;
  475. style.width = '100%';
  476. style.position = 'absolute';
  477. style.zIndex = -1;
  478. style.top = 0;
  479. style.left = 0;
  480. let ctx = c.getContext('2d');
  481. let x0, y0, w, h, dw;
  482. function init() {
  483. w = window.innerWidth;
  484. h = window.innerHeight;
  485. c.width = w;
  486. c.height = h;
  487. let offset = h > 380 ? 100 : 65;
  488. offset = h > 800 ? 116 : offset;
  489. x0 = w / 2;
  490. y0 = h - offset;
  491. dw = Math.max(w, h, 1000) / 13;
  492. drawCircles();
  493. }
  494. window.onresize = init;
  495. function drawCircle(radius) {
  496. ctx.beginPath();
  497. let color = Math.round(255 * (1 - radius / Math.max(w, h)));
  498. ctx.strokeStyle = 'rgba(' + color + ',' + color + ',' + color + ',0.1)';
  499. ctx.arc(x0, y0, radius, 0, 2 * Math.PI);
  500. ctx.stroke();
  501. ctx.lineWidth = 2;
  502. }
  503. let step = 0;
  504. function drawCircles() {
  505. ctx.clearRect(0, 0, w, h);
  506. for (let i = 0; i < 8; i++) {
  507. drawCircle(dw * i + step % dw);
  508. }
  509. step += 1;
  510. }
  511. let loading = true;
  512. function animate() {
  513. if (loading || step % dw < dw - 5) {
  514. requestAnimationFrame(function() {
  515. drawCircles();
  516. animate();
  517. });
  518. }
  519. }
  520. window.animateBackground = function(l) {
  521. loading = l;
  522. animate();
  523. };
  524. init();
  525. animate();
  526. setTimeout(e => window.animateBackground(false), 3000);
  527. });
  528. Notifications.PERMISSION_ERROR = `
  529. Notifications permission has been blocked
  530. as the user has dismissed the permission prompt several times.
  531. This can be reset in Page Info
  532. which can be accessed by clicking the lock icon next to the URL.`;
  533. document.body.onclick = e => { // safari hack to fix audio
  534. document.body.onclick = null;
  535. if (!(/.*Version.*Safari.*/.test(navigator.userAgent))) return;
  536. blop.play();
  537. }