import 'dart:js_interop'; import 'dart:js_interop_unsafe'; import 'notification_bridge.dart'; import 'notification_models.dart'; /// The browser's `Notification` constructor. /// /// Declared with `dart:js_interop` rather than `dart:html`, so the same source /// compiles for the JavaScript and WebAssembly web targets. Every member is /// reached only after [_supported] has confirmed the global exists, so an /// unsupported browser never touches it. @JS('Notification') extension type _Notification._(JSObject _) implements JSObject { external factory _Notification(JSString title, _NotificationOptions options); external static JSString get permission; external static JSPromise requestPermission(); external set onclick(JSFunction? handler); } /// The `{ body, tag }` options object one notification is created with. extension type _NotificationOptions._(JSObject _) implements JSObject { external factory _NotificationOptions({JSString body, JSString tag}); } /// Whether `globalThis.Notification` is really a constructor right now. bool _supported() => globalContext.getProperty('Notification'.toJS).isA(); /// The browser's own secure-context flag; anything but a real boolean is false. bool _secureContext() { final value = globalContext.getProperty('isSecureContext'.toJS); return value.isA() && (value as JSBoolean).toDart; } /// The browser bridge: the real `Notification` API, reached through /// `dart:js_interop`. /// /// Nothing is fabricated. [environment] reports the constructor's own /// `permission` word and the page's own `isSecureContext`; an unsupported /// browser is reported as unsupported rather than as a default grant. class WebNotificationBridge implements NotificationBridge { const WebNotificationBridge(); @override NotificationEnvironment environment() { if (!_supported()) { return const NotificationEnvironment( supported: false, secureContext: false, permission: 'default', ); } final raw = _Notification.permission.toDart; return NotificationEnvironment( supported: true, secureContext: _secureContext(), permission: raw == 'granted' || raw == 'denied' ? raw : 'default', ); } @override Future requestPermission() async { if (!_supported()) return 'default'; try { return (await _Notification.requestPermission().toDart).toDart; } catch (_) { // A browser that refuses the request keeps the honest fallback wording. return 'default'; } } @override bool show(NotificationMessage message, {void Function()? onTap}) { if (!_supported()) return false; try { final notification = _Notification( message.title.toJS, _NotificationOptions(body: message.body.toJS, tag: message.tag.toJS), ); final open = onTap; if (open != null) notification.onclick = (() => open()).toJS; return true; } catch (_) { // Some browsers can throw even with permission granted; the in-app Needs // you surface remains the only honest channel and nothing is faked. return false; } } } NotificationBridge createNotificationBridge() => const WebNotificationBridge();