notification.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Monitors the gallery and sends a browser notification when the leading image is new.
  2. let lastHeadImg = null;
  3. let notificationButton = null;
  4. onUiUpdate(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_"][style*="display: block"] 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. gradioApp().querySelector('#audio_notification audio')?.play();
  20. if (document.hasFocus()) return;
  21. // Multiple copies of the images are in the DOM when one is selected. Dedup with a Set to get the real number generated.
  22. const imgs = new Set(Array.from(galleryPreviews).map(img => img.src));
  23. const notification = new Notification(
  24. 'Stable Diffusion',
  25. {
  26. body: `Generated ${imgs.size > 1 ? imgs.size - opts.return_grid : 1} image${imgs.size > 1 ? 's' : ''}`,
  27. icon: headImg,
  28. image: headImg,
  29. }
  30. );
  31. notification.onclick = function(_) {
  32. parent.focus();
  33. this.close();
  34. };
  35. });