// The right sidebar's web browser: an address bar over an embedded WebView, // with history navigation, reload/stop and opening the page in the system // browser. The panel keeps its page while another tab is shown (the tab stack // keeps it alive). import 'dart:io' show Platform; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:webview_flutter/webview_flutter.dart'; import '../l10n.dart'; class BrowserPanel extends StatefulWidget { const BrowserPanel({super.key}); @override State createState() => _BrowserPanelState(); } class _BrowserPanelState extends State { static const MethodChannel _channel = MethodChannel('openchamber/browser'); final TextEditingController _url = TextEditingController(); final List _history = []; WebViewController? _web; bool _loading = false; bool _hasPage = false; bool _canBack = false; bool _canForward = false; int _progress = 0; String? _error; bool get _supported => Platform.isAndroid || Platform.isIOS; @override void initState() { super.initState(); if (!_supported) return; _web = WebViewController() ..setJavaScriptMode(JavaScriptMode.unrestricted) ..setBackgroundColor(Colors.transparent) ..setNavigationDelegate(NavigationDelegate( onPageStarted: (url) { if (!mounted) return; setState(() { _loading = true; _hasPage = true; _progress = 0; _error = null; _setUrl(url); }); _syncNavigation(); }, onPageFinished: (url) { if (!mounted) return; setState(() { _loading = false; _progress = 100; _setUrl(url); }); _remember(url); _syncNavigation(); }, onProgress: (value) { if (mounted) setState(() => _progress = value); }, onUrlChange: (change) { final url = change.url; if (url != null && mounted) setState(() => _setUrl(url)); }, onWebResourceError: (error) { if ((error.isForMainFrame ?? true) && mounted) { setState(() => _error = error.description); } }, )); } @override void dispose() { _url.dispose(); super.dispose(); } Future _syncNavigation() async { final web = _web; if (web == null) return; final back = await web.canGoBack(); final forward = await web.canGoForward(); if (!mounted) return; setState(() { _canBack = back; _canForward = forward; }); } /// Puts [url] in the address field with the caret at its end, so the part /// that was just visited stays visible in the narrow bar. void _setUrl(String url) { _url.value = TextEditingValue( text: url, selection: TextSelection.collapsed(offset: url.length), ); } void _remember(String url) { if (url.isEmpty) return; _history.remove(url); _history.insert(0, url); if (_history.length > 20) _history.removeLast(); } void _navigate(String raw) { var text = raw.trim(); if (text.isEmpty) return; if (!text.contains('://')) { final host = text.split('/').first.split(':').first; final local = host == 'localhost' || host == '127.0.0.1' || host == '[::1]' || host == '0.0.0.0'; text = '${local ? 'http' : 'https'}://$text'; } final uri = Uri.tryParse(text); if (uri == null || !uri.hasAuthority) { _snack(tr('Invalid URL')); return; } FocusScope.of(context).unfocus(); _setUrl(text); _web?.loadRequest(uri); } Future _openExternal() async { if (!Platform.isAndroid) return; final url = _url.text.trim(); if (url.isEmpty) return; try { await _channel.invokeMethod('openUrl', {'url': url}); } catch (e) { if (mounted) _snack(trArgs('Could not open the browser: {0}', [e])); } } void _snack(String text) { ScaffoldMessenger.of(context) ..hideCurrentSnackBar() ..showSnackBar(SnackBar(content: AppText(text))); } @override Widget build(BuildContext context) { final theme = Theme.of(context); if (!_supported) { return Center( child: Padding( padding: const EdgeInsets.all(32), child: Column( mainAxisSize: MainAxisSize.min, children: [ Icon(Icons.public_off, size: 40, color: theme.hintColor), const SizedBox(height: 12), const AppText( 'Browser is only available on Android and iOS', textAlign: TextAlign.center, style: TextStyle(fontSize: 13), ), ], ), ), ); } return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ _addressBar(theme), if (_loading) LinearProgressIndicator( value: _progress > 0 && _progress < 100 ? _progress / 100 : null, minHeight: 2, ), if (_error != null) _errorBar(theme), Expanded( // Keep the WebView attached even before the first address: a // loadRequest on a controller with no platform view is lost. The // empty state is an overlay until a page starts. child: Stack( children: [ Positioned.fill(child: WebViewWidget(controller: _web!)), if (!_hasPage) Positioned.fill( child: ColoredBox( color: theme.colorScheme.surface, child: _empty(theme), ), ), ], ), ), ], ); } Widget _addressBar(ThemeData theme) { final web = _web; return Padding( padding: const EdgeInsets.fromLTRB(4, 6, 4, 6), child: Row( children: [ Expanded( child: TextField( controller: _url, keyboardType: TextInputType.url, textInputAction: TextInputAction.go, onSubmitted: _navigate, decoration: InputDecoration( isDense: true, hintText: tr('Enter a URL'), prefixIcon: const Icon(Icons.public, size: 18), suffixIcon: IconButton( icon: const Icon(Icons.arrow_forward, size: 18), tooltip: tr('Go'), onPressed: () => _navigate(_url.text), ), border: OutlineInputBorder( borderRadius: BorderRadius.circular(10)), ), ), ), IconButton( icon: Icon(_loading ? Icons.stop : Icons.refresh, size: 20), tooltip: _loading ? tr('Stop') : tr('Reload'), onPressed: _loading ? () => web?.runJavaScript('window.stop()') : web?.reload, ), MenuAnchor( builder: (context, controller, child) => IconButton( icon: const Icon(Icons.more_vert, size: 20), tooltip: tr('More'), onPressed: () => controller.isOpen ? controller.close() : controller.open(), ), menuChildren: [ MenuItemButton( leadingIcon: const Icon(Icons.arrow_back, size: 18), onPressed: _canBack ? () => web?.goBack() : null, child: const AppText('Back'), ), MenuItemButton( leadingIcon: const Icon(Icons.arrow_forward, size: 18), onPressed: _canForward ? () => web?.goForward() : null, child: const AppText('Forward'), ), if (Platform.isAndroid) MenuItemButton( leadingIcon: const Icon(Icons.open_in_browser, size: 18), onPressed: _openExternal, child: const AppText('Open in system browser'), ), SubmenuButton( leadingIcon: const Icon(Icons.history, size: 18), menuChildren: _history.isEmpty ? [ const MenuItemButton( onPressed: null, child: AppText('No history'), ), ] : [ for (final url in _history) MenuItemButton( onPressed: () { _setUrl(url); _navigate(url); }, child: Text(url, maxLines: 1, overflow: TextOverflow.ellipsis), ), ], child: const AppText('History'), ), ], ), ], ), ); } Widget _errorBar(ThemeData theme) { return Container( color: theme.colorScheme.errorContainer.withValues(alpha: 0.4), padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), child: Row( children: [ Icon(Icons.error_outline, size: 16, color: theme.colorScheme.error), const SizedBox(width: 8), Expanded( child: Text( _error!, maxLines: 2, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 12, color: theme.colorScheme.error), ), ), TextButton( onPressed: () => _web?.reload(), child: const AppText('Retry'), ), ], ), ); } Widget _empty(ThemeData theme) { return Center( child: SingleChildScrollView( padding: const EdgeInsets.all(24), child: Column( mainAxisSize: MainAxisSize.min, children: [ Icon(Icons.public, size: 48, color: theme.hintColor), const SizedBox(height: 12), const AppText( 'Web browser', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600), ), const SizedBox(height: 4), const AppText( 'Enter a URL above to start browsing', textAlign: TextAlign.center, style: TextStyle(fontSize: 12.5), ), const SizedBox(height: 16), AppText( 'The browser runs on this device; for a dev server on the OpenChamber host, enter the host\'s LAN address.', textAlign: TextAlign.center, style: TextStyle(fontSize: 11.5, color: theme.hintColor), ), ], ), ), ); } }