notification.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Monitors the gallery and sends a browser notification when the leading image is new.
  2. let lastHeadImg = null;
  3. let notificationButton = null;
  4. onAfterUiUpdate(function() {
  5. if (notificationButton == null) {
  6. notificationButton = gradioApp().getElementById('request_notifications');
  7. if (notificationButton != null) {
  8. notificationButton.addEventListener('click', () => {
  9. void Notification.requestPermission();
  10. }, true);
  11. }
  12. }
  13. const galleryPreviews = gradioApp().querySelectorAll('div[id^="tab_"] div[id$="_results"] .thumbnail-item > img');
  14. if (galleryPreviews == null) return;
  15. const headImg = galleryPreviews[0]?.src;
  16. if (headImg == null || headImg == lastHeadImg) return;
  17. lastHeadImg = headImg;
  18. // play notification sound if available
  19. const notificationAudio = gradioApp().querySelector('#audio_notification audio');
  20. if (notificationAudio) {
  21. notificationAudio.volume = opts.notification_volume / 100.0 || 1.0;
  22. notificationAudio.play();
  23. }
  24. if (document.hasFocus()) return;
  25. // Multiple copies of the images are in the DOM when one is selected. Dedup with a Set to get the real number generated.
  26. const imgs = new Set(Array.from(galleryPreviews).map(img => img.src));
  27. const notification = new Notification(
  28. 'Stable Diffusion',
  29. {
  30. body: `Generated ${imgs.size > 1 ? imgs.size - opts.return_grid : 1} image${imgs.size > 1 ? 's' : ''}`,
  31. icon: headImg,
  32. image: headImg,
  33. }
  34. );
  35. notification.onclick = function(_) {
  36. parent.focus();
  37. this.close();
  38. };
  39. });