import 'dart:async'; import 'dart:js_interop'; import 'dart:ui'; import 'package:web/web.dart' as web; import 'detached_platform.dart'; import 'detached_route.dart'; DetachedPlatform createDetachedPlatform() => WebDetachedPlatform(); DetachedRoute? launchedDetachedRoute(List args) => DetachedRoute.parse(Uri.base.toString()); /// Detached windows as browser windows of the same origin: the session /// cookie and the local preferences are shared, and each window is its own /// app instance with its own connection. class WebDetachedPlatform extends DetachedPlatform { final Map _opened = {}; StreamController? _messages; JSFunction? _listener; @override bool get supported => true; @override Future launch( DetachedRoute route, { required String title, required Size size, bool tab = false, }) async { final name = _name(route); final open = _opened[name]; if (open != null && !open.closed) { open.focus(); return DetachedLaunch.opened; } final url = _url(route); final web.Window? window; try { window = tab ? web.window.open(url, name) : web.window.open( url, name, 'popup,width=${size.width.round()},height=${size.height.round()}', ); } catch (_) { return DetachedLaunch.failed; } if (window == null) { return tab ? DetachedLaunch.failed : DetachedLaunch.blocked; } _opened[name] = window; return DetachedLaunch.opened; } /// One browser window per item: opening it again brings that one forward. static String _name(DetachedRoute route) => 'pipelines-${route.kind.name}-' '${route.id.replaceAll(RegExp(r'[^A-Za-z0-9_-]'), '_')}'; static String _url(DetachedRoute route) { final base = Uri.base.resolve(route.path); final extra = DetachedPlatform.extraQuery?.call() ?? const {}; if (extra.isEmpty) return base.toString(); return base .replace(queryParameters: {...extra, ...base.queryParameters}) .toString(); } @override Stream get messages { final existing = _messages; if (existing != null) return existing.stream; final controller = _messages = StreamController.broadcast(); final listener = ((web.MessageEvent event) { if (event.origin != web.window.location.origin) return; final data = event.data; if (!data.isA()) return; final message = decodeDetachedMessage((data as JSString).toDart); if (message != null) controller.add(message); }).toJS; _listener = listener; web.window.addEventListener('message', listener); return controller.stream; } /// `shared_preferences` keeps its values under this prefix in /// `localStorage`; another window's write raises `storage` here. @override Stream get preferencesChanged { late final StreamController controller; final listener = ((web.StorageEvent event) { final key = event.key; if (key == null || key.startsWith('flutter.')) controller.add(null); }).toJS; controller = StreamController( onListen: () => web.window.addEventListener('storage', listener), onCancel: () => web.window.removeEventListener('storage', listener), ); return controller.stream; } static String _key(String token) => 'pipelines.detached.$token'; @override Future put(String token, String json) async { try { web.window.localStorage.setItem(_key(token), json); } catch (_) { // Storage full or off: the window says the diff is gone. } } /// The hand-over is read once from the shared storage, then kept in this /// window's own session storage so a reload still has it. @override Future take(String token) async { final key = _key(token); try { final shared = web.window.localStorage.getItem(key); if (shared != null) { web.window.localStorage.removeItem(key); web.window.sessionStorage.setItem(key, shared); return shared; } return web.window.sessionStorage.getItem(key); } catch (_) { return null; } } web.Window? get _opener { final opener = web.window.opener; // The opener is a window of another realm: `instanceof Window` (isA) // would refuse it, so it is taken as one. if (opener == null) return null; final window = opener as web.Window; try { return window.closed ? null : window; } catch (_) { return null; } } @override Future sendToMain(DetachedMessage message) async { final opener = _opener; if (opener == null) return false; try { opener.postMessage( encodeDetachedMessage(message).toJS, web.window.location.origin.toJS, ); opener.focus(); return true; } catch (_) { return false; } } @override Future closeSelf() async => web.window.close(); @override Future becomeMain(String appPath) async { web.window.location.assign(appPath); return true; } void dispose() { final listener = _listener; if (listener != null) { web.window.removeEventListener('message', listener); } unawaited(_messages?.close()); } }