ui.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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.show();
  242. this.$text.setSelectionRange(0, this.$text.value.length)
  243. }
  244. _send(e) {
  245. e.preventDefault();
  246. Events.fire('send-text', {
  247. to: this._recipient,
  248. text: this.$text.value
  249. });
  250. }
  251. }
  252. class ReceiveTextDialog extends Dialog {
  253. constructor() {
  254. super('receiveTextDialog');
  255. Events.on('text-received', e => this._onText(e.detail))
  256. this.$text = this.$el.querySelector('#text');
  257. const $copy = this.$el.querySelector('#copy');
  258. copy.addEventListener('click', _ => this._onCopy());
  259. }
  260. _onText(e) {
  261. this.$text.innerHTML = '';
  262. const text = e.text;
  263. if (isURL(text)) {
  264. const $a = document.createElement('a');
  265. $a.href = text;
  266. $a.target = '_blank';
  267. $a.textContent = text;
  268. this.$text.appendChild($a);
  269. } else {
  270. this.$text.textContent = text;
  271. }
  272. this.show();
  273. window.blop.play();
  274. }
  275. _onCopy() {
  276. if (!document.copy(this.$text.textContent)) return;
  277. Events.fire('notify-user', 'Copied to clipboard');
  278. }
  279. }
  280. class Toast extends Dialog {
  281. constructor() {
  282. super('toast');
  283. Events.on('notify-user', e => this._onNotfiy(e.detail));
  284. }
  285. _onNotfiy(message) {
  286. this.$el.textContent = message;
  287. this.show();
  288. setTimeout(_ => this.hide(), 3000);
  289. }
  290. }
  291. class Notifications {
  292. constructor() {
  293. // Check if the browser supports notifications
  294. if (!('Notification' in window)) return;
  295. // Check whether notification permissions have already been granted
  296. if (Notification.permission !== 'granted') {
  297. this.$button = $('notification');
  298. this.$button.removeAttribute('hidden');
  299. this.$button.addEventListener('click', e => this._requestPermission());
  300. }
  301. Events.on('text-received', e => this._messageNotification(e.detail.text));
  302. Events.on('file-received', e => this._downloadNotification(e.detail.name));
  303. }
  304. _requestPermission() {
  305. Notification.requestPermission(permission => {
  306. if (permission !== 'granted') {
  307. Events.fire('notify-user', Notifications.PERMISSION_ERROR || 'Error');
  308. return;
  309. }
  310. this._notify('Even more snappy sharing!');
  311. this.$button.setAttribute('hidden', 1);
  312. });
  313. }
  314. _notify(message, body) {
  315. const config = {
  316. body: body,
  317. icon: '/images/logo_transparent_128x128.png',
  318. }
  319. try {
  320. return new Notification(message, config);
  321. } catch (e) {
  322. // android doesn't support "new Notification" if service worker is installed
  323. if (!serviceWorker || !serviceWorker.showNotification) return;
  324. return serviceWorker.showNotification(message, config);
  325. }
  326. }
  327. _messageNotification(message) {
  328. if (isURL(message)) {
  329. const notification = this._notify(message, 'Click to open link');
  330. this._bind(notification, e => window.open(message, '_blank', null, true));
  331. } else {
  332. const notification = this._notify(message, 'Click to copy text');
  333. this._bind(notification, e => this._copyText(message, notification));
  334. }
  335. }
  336. _downloadNotification(message) {
  337. const notification = this._notify(message, 'Click to download');
  338. if (!window.isDownloadSupported) return;
  339. this._bind(notification, e => this._download(notification));
  340. }
  341. _download(notification) {
  342. document.querySelector('x-dialog [download]').click();
  343. notification.close();
  344. }
  345. _copyText(message, notification) {
  346. notification.close();
  347. if(!document.copy(message)) return;
  348. this._notify('Copied text to clipboard');
  349. }
  350. _bind(notification, handler) {
  351. if (notification.then) {
  352. notification.then(e => serviceWorker.getNotifications().then(notifications => {
  353. serviceWorker.addEventListener('notificationclick', handler);
  354. }));
  355. } else {
  356. notification.onclick = handler;
  357. }
  358. }
  359. }
  360. class Snapdrop {
  361. constructor() {
  362. const server = new ServerConnection();
  363. const peers = new PeersManager(server);
  364. const peersUI = new PeersUI();
  365. Events.on('load', e => {
  366. const receiveDialog = new ReceiveDialog();
  367. const sendTextDialog = new SendTextDialog();
  368. const receiveTextDialog = new ReceiveTextDialog();
  369. const toast = new Toast();
  370. const notifications = new Notifications();
  371. })
  372. }
  373. }
  374. const snapdrop = new Snapdrop();
  375. document.copy = text => {
  376. // A <span> contains the text to copy
  377. const span = document.createElement('span');
  378. span.textContent = text;
  379. span.style.whiteSpace = 'pre'; // Preserve consecutive spaces and newlines
  380. // Paint the span outside the viewport
  381. span.style.position = 'absolute';
  382. span.style.left = '-9999px';
  383. span.style.top = '-9999px';
  384. const win = window;
  385. const selection = win.getSelection();
  386. win.document.body.appendChild(span);
  387. const range = win.document.createRange();
  388. selection.removeAllRanges();
  389. range.selectNode(span);
  390. selection.addRange(range);
  391. let success = false;
  392. try {
  393. success = win.document.execCommand('copy');
  394. } catch (err) {}
  395. selection.removeAllRanges();
  396. span.remove();
  397. return success;
  398. }
  399. if ('serviceWorker' in navigator && !window.iOS) {
  400. // SW on iOS is buggy. see: https://stackoverflow.com/questions/18103103/failed-to-load-resource-plugin-handled-load-on-ios
  401. navigator.serviceWorker
  402. .register('/service-worker.js')
  403. .then(serviceWorker => {
  404. console.log('Service Worker registered');
  405. window.serviceWorker = serviceWorker
  406. });
  407. }
  408. // Background Animation
  409. Events.on('load', () => {
  410. var requestAnimFrame = (function() {
  411. return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
  412. function(callback) {
  413. window.setTimeout(callback, 1000 / 60);
  414. };
  415. })();
  416. var c = document.createElement('canvas');
  417. document.body.appendChild(c);
  418. var style = c.style;
  419. style.width = '100%';
  420. style.position = 'absolute';
  421. style.zIndex = -1;
  422. var ctx = c.getContext('2d');
  423. var x0, y0, w, h, dw;
  424. function init() {
  425. w = window.innerWidth;
  426. h = window.innerHeight;
  427. c.width = w;
  428. c.height = h;
  429. var offset = h > 380 ? 100 : 65;
  430. x0 = w / 2;
  431. y0 = h - offset;
  432. dw = Math.max(w, h, 1000) / 13;
  433. drawCircles();
  434. }
  435. window.onresize = init;
  436. function drawCicrle(radius) {
  437. ctx.beginPath();
  438. var color = Math.round(255 * (1 - radius / Math.max(w, h)));
  439. ctx.strokeStyle = 'rgba(' + color + ',' + color + ',' + color + ',0.1)';
  440. ctx.arc(x0, y0, radius, 0, 2 * Math.PI);
  441. ctx.stroke();
  442. ctx.lineWidth = 2;
  443. }
  444. var step = 0;
  445. function drawCircles() {
  446. ctx.clearRect(0, 0, w, h);
  447. for (var i = 0; i < 8; i++) {
  448. drawCicrle(dw * i + step % dw);
  449. }
  450. step += 1;
  451. }
  452. var loading = true;
  453. function animate() {
  454. if (loading || step % dw < dw - 5) {
  455. requestAnimFrame(function() {
  456. drawCircles();
  457. animate();
  458. });
  459. }
  460. }
  461. window.animateBackground = function(l) {
  462. loading = l;
  463. animate();
  464. };
  465. init();
  466. animate();
  467. setTimeout(e => window.animateBackground(false), 3000);
  468. });
  469. Notifications.PERMISSION_ERROR = `
  470. Notifications permission has been blocked
  471. as the user has dismissed the permission prompt several times.
  472. This can be reset in Page Info
  473. which can be accessed by clicking the lock icon next to the URL.`;
  474. document.body.onclick = e => { // safari hack to fix audio
  475. document.body.onclick = null;
  476. if (!(/.*Version.*Safari.*/.test(navigator.userAgent))) return;
  477. blop.play();
  478. }