import 'dart:js_interop'; import 'dart:js_interop_unsafe'; import 'package:web/web.dart' as web; import 'terminal_browser_keys.dart'; /// The Keyboard Lock API (`navigator.keyboard.lock()`), which Chrome and /// Edge honour only in full screen: the page enters full screen, then locks /// every key. The browser keeps holding Esc as the way out; leaving full /// screen ends the lock. class TerminalBrowserKeysPlatform implements TerminalBrowserKeysBackend { TerminalBrowserKeysPlatform() { web.document.addEventListener( 'fullscreenchange', ((web.Event _) { if (web.document.fullscreenElement == null) _onReleased?.call(); }).toJS, ); } void Function()? _onReleased; JSObject? get _keyboard { final keyboard = (web.window.navigator as JSObject)['keyboard']; return keyboard.isUndefinedOrNull ? null : keyboard as JSObject; } @override bool get supported { final keyboard = _keyboard; return keyboard != null && keyboard.has('lock') && web.document.fullscreenEnabled; } @override Future lock() async { final keyboard = _keyboard; final root = web.document.documentElement; if (keyboard == null || root == null) return false; try { if (web.document.fullscreenElement == null) { await root.requestFullscreen().toDart; } await keyboard.callMethod>('lock'.toJS).toDart; return true; } catch (_) { // Refused (no user gesture, a policy, an iframe): back out of full // screen so the page is as it was. await _exitFullscreen(); return false; } } @override Future unlock() async { _keyboard?.callMethod('unlock'.toJS); await _exitFullscreen(); } Future _exitFullscreen() async { if (web.document.fullscreenElement == null) return; try { await web.document.exitFullscreen().toDart; } catch (_) { // Already leaving full screen. } } @override set onReleased(void Function() callback) => _onReleased = callback; }