RedditWebViewStore.swift 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import AppKit
  2. import WebKit
  3. @MainActor
  4. final class RedditWebViewStore {
  5. static let shared = RedditWebViewStore()
  6. private(set) var container: RedditWebViewContainer?
  7. private var isWindowMinimized = false
  8. private var isRedditPageActive = false
  9. private var isPaywallPresented = false
  10. private var isAwaitingReturnFromSubscriptionManagement = false
  11. private var isMediaPlaybackSuspended = false
  12. private init() {}
  13. func containerIfNeeded() -> RedditWebViewContainer {
  14. if let container {
  15. return container
  16. }
  17. let webView = RedditWebViewManager.makeWebView()
  18. let newContainer = RedditWebViewContainer(webView: webView)
  19. container = newContainer
  20. updateMediaPlaybackSuspension()
  21. return newContainer
  22. }
  23. func setRedditPageActive(_ active: Bool) {
  24. isRedditPageActive = active
  25. updateMediaPlaybackSuspension()
  26. }
  27. func setPaywallPresented(_ presented: Bool) {
  28. isPaywallPresented = presented
  29. updateMediaPlaybackSuspension()
  30. }
  31. func suspendForSubscriptionManagement() {
  32. isAwaitingReturnFromSubscriptionManagement = true
  33. updateMediaPlaybackSuspension()
  34. }
  35. func handleApplicationDidBecomeActive() {
  36. guard isAwaitingReturnFromSubscriptionManagement else { return }
  37. isAwaitingReturnFromSubscriptionManagement = false
  38. updateMediaPlaybackSuspension()
  39. }
  40. func suspendMediaPlaybackForWindowMinimize() {
  41. isWindowMinimized = true
  42. updateMediaPlaybackSuspension()
  43. }
  44. func resumeMediaPlaybackAfterWindowDeminiaturize() {
  45. isWindowMinimized = false
  46. updateMediaPlaybackSuspension()
  47. }
  48. private func updateMediaPlaybackSuspension() {
  49. let shouldSuspend = isWindowMinimized
  50. || !isRedditPageActive
  51. || isPaywallPresented
  52. || isAwaitingReturnFromSubscriptionManagement
  53. guard let webView = container?.webView else { return }
  54. if shouldSuspend, !isMediaPlaybackSuspended {
  55. isMediaPlaybackSuspended = true
  56. webView.setAllMediaPlaybackSuspended(true, completionHandler: nil)
  57. } else if !shouldSuspend, isMediaPlaybackSuspended {
  58. isMediaPlaybackSuspended = false
  59. webView.setAllMediaPlaybackSuspended(false, completionHandler: nil)
  60. }
  61. }
  62. }