import 'dart:async'; import 'dart:js_interop'; import 'package:web/web.dart' as web; import 'agent_notice.dart'; import 'page_signals.dart'; /// The browser page's own signals: `document.visibilityState`, /// `document.hasFocus()`, `document.title` and a Web Audio tone. /// /// Focus is read from the document rather than the app lifecycle, because a /// click into an embedded HTML view moves window focus into its iframe while /// the operator is still looking at the page. class BrowserPageSignals implements PageSignals { BrowserPageSignals() { _onFocus = ((web.Event _) => _maybeFocused()).toJS; web.window.addEventListener('focus', _onFocus); web.document.addEventListener('visibilitychange', _onFocus); } late final JSFunction _onFocus; final _focused = StreamController.broadcast(); web.AudioContext? _audio; void _maybeFocused() { if (presence == PagePresence.focused) _focused.add(null); } @override PagePresence get presence { if (web.document.visibilityState == 'hidden') return PagePresence.hidden; return web.document.hasFocus() ? PagePresence.focused : PagePresence.visible; } @override Stream get focused => _focused.stream; @override void setBadge(int count) { final next = badgedTitle(web.document.title, count); if (next != web.document.title) web.document.title = next; } @override void chime() { try { final audio = _audio ??= web.AudioContext(); // A context created before any gesture starts suspended; resuming it // succeeds once the operator has interacted with the page. if (audio.state == 'suspended') unawaited(audio.resume().toDart); final now = audio.currentTime; final tone = audio.createOscillator()..type = 'sine'; tone.frequency.value = 880; final volume = audio.createGain(); volume.gain.value = 0.06; tone.connect(volume); volume.connect(audio.destination); tone.start(now); tone.stop(now + 0.18); } catch (_) { // No audio (blocked autoplay, no device): the toast and title remain. } } @override void dispose() { web.window.removeEventListener('focus', _onFocus); web.document.removeEventListener('visibilitychange', _onFocus); unawaited(_focused.close()); final audio = _audio; if (audio != null) unawaited(audio.close().toDart); } } PageSignals createPageSignals() => BrowserPageSignals();