Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Improve the desktop layout and fix web media controls

Barnabasc6b668673b0e
diff --git a/lib/screens/admin_podcasts_screen.dart b/lib/screens/admin_podcasts_screen.dart
index 80a083cb..2858eafe 100644
--- a/lib/screens/admin_podcasts_screen.dart
+++ b/lib/screens/admin_podcasts_screen.dart
@@ -254,7 +254,7 @@ class _AdminPodcastsScreenState extends State<AdminPodcastsScreen> {
// ─── Show Detail ────────────────────────────────────────────
void _openShowDetail(Map<String, dynamic> item) {
- contentNavigator(context).push(MaterialPageRoute(
+ Navigator.of(context).push(MaterialPageRoute(
builder: (_) => _PodcastDetailScreen(item: item, libraryId: _libraryId, onChanged: _loadShows)));
}
}
@@ -2079,7 +2079,7 @@ class _PodcastDetailScreenState extends State<_PodcastDetailScreen> with SingleT
void _openEditInfo() {
final tags = (_media['tags'] as List<dynamic>?)?.whereType<String>().toList() ?? <String>[];
- contentNavigator(context).push(MaterialPageRoute(
+ Navigator.of(context).push(MaterialPageRoute(
builder: (_) => PodcastEditScreen(
itemId: _podcastId,
metadata: Map<String, dynamic>.from(_metadata),
diff --git a/lib/screens/admin_screen.dart b/lib/screens/admin_screen.dart
index 0fe51752..db500f25 100644
--- a/lib/screens/admin_screen.dart
+++ b/lib/screens/admin_screen.dart
@@ -5,6 +5,7 @@ import '../providers/auth_provider.dart';
import '../services/scoped_prefs.dart';
import '../services/server_task_tracker.dart';
import '../services/socket_service.dart';
+import '../widgets/admin_adaptive_frame.dart';
import '../widgets/admin_task_indicator.dart';
import '../widgets/absorb_page_header.dart';
import '../widgets/rmab_config_sheet.dart';
@@ -23,13 +24,50 @@ import 'admin_server_settings_screen.dart';
import 'admin_stats_screen.dart';
import 'admin_sessions_screen.dart';
+class _AdminNavigatorObserver extends NavigatorObserver {
+ final VoidCallback onStackChanged;
+ int routeDepth = 0;
+
+ _AdminNavigatorObserver(this.onStackChanged);
+
+ @override
+ void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
+ super.didPush(route, previousRoute);
+ routeDepth++;
+ onStackChanged();
+ }
+
+ @override
+ void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
+ super.didPop(route, previousRoute);
+ routeDepth--;
+ onStackChanged();
+ }
+
+ @override
+ void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
+ super.didRemove(route, previousRoute);
+ routeDepth--;
+ onStackChanged();
+ }
+
+ @override
+ void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
+ super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
+ onStackChanged();
+ }
+}
+
class AdminScreen extends StatefulWidget {
const AdminScreen({super.key});
@override State<AdminScreen> createState() => _AdminScreenState();
}
class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {
+ static const _overviewSection = 'overview';
+
bool _loading = true;
+ bool _loadedOnce = false;
List<dynamic> _users = [];
List<dynamic> _onlineUsers = [];
List<dynamic> _libraries = [];
@@ -50,20 +88,45 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {
Timer? _issuesDebounce;
Timer? _taskRefreshTimer;
bool _refreshingTasks = false;
+ final GlobalKey<NavigatorState> _desktopNavigatorKey = GlobalKey<NavigatorState>();
+ late final _AdminNavigatorObserver _desktopNavigatorObserver;
+ String _desktopSection = _overviewSection;
+ bool _desktopNavigatorCanPop = false;
+ bool _desktopNavigationChanging = false;
+ int _desktopNavigationSerial = 0;
+ bool _desktopUsersDirty = false;
+ bool _desktopLibrariesDirty = false;
+ bool _desktopOverviewDirty = false;
+ int _desktopUsersDirtyGeneration = 0;
+ int _desktopLibrariesDirtyGeneration = 0;
+ int _desktopOverviewDirtyGeneration = 0;
+ bool _desktopOverviewRefreshActive = false;
+ Future<void>? _desktopUsersRefresh;
+ Future<void>? _desktopLibrariesRefresh;
+ bool? _desktopPresentation;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
+ _desktopNavigatorObserver = _AdminNavigatorObserver(_onDesktopStackChanged);
+ DesktopWorkspaceNavigator.registerExitGuard(this, _prepareForDesktopPaneReset);
_taskTracker = ServerTaskTracker();
_startTaskRefreshTimer();
_loadAll();
SocketService().addItemsChangedListener(_onItemsChanged);
}
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ _desktopPresentation ??= isDesktopWorkspace(context);
+ }
+
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
+ DesktopWorkspaceNavigator.unregisterExitGuard(this);
SocketService().removeItemsChangedListener(_onItemsChanged);
_issuesDebounce?.cancel();
_taskRefreshTimer?.cancel();
@@ -121,15 +184,19 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {
}
Future<void> _loadAll() async {
+ final usersGeneration = _desktopUsersDirtyGeneration;
+ final librariesGeneration = _desktopLibrariesDirtyGeneration;
+ final overviewGeneration = _desktopOverviewDirtyGeneration;
final api = context.read<AuthProvider>().apiService;
if (api == null) return;
- setState(() => _loading = true);
+ if (!_loadedOnce) setState(() => _loading = true);
final taskRefresh = _refreshServerTasks();
final futures = await Future.wait([
api.getUsers(), api.getOnlineUsers(), api.getLibraries(), api.getBackups(), api.getAllSessions(limit: 10),
]);
await taskRefresh;
+ if (!mounted) return;
_users = futures[0];
_onlineUsers = futures[1];
_libraries = futures[2];
@@ -141,13 +208,30 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {
final id = lib['id'] as String? ?? '';
if (id.isNotEmpty) {
final stats = await api.getLibraryStats(id);
+ if (!mounted) return;
if (stats != null) _libraryStats[id] = stats;
_libraryIssues[id] = await api.getIssueItemCount(id);
+ if (!mounted) return;
}
}
_rmabBaseUrl = await ScopedPrefs.getString(kRmabBaseUrlKey);
+ if (!mounted) return;
_rmabApiToken = await ScopedPrefs.getString(kRmabApiTokenKey);
- if (mounted) setState(() => _loading = false);
+ if (!mounted) return;
+ if (_desktopUsersDirtyGeneration == usersGeneration) {
+ _desktopUsersDirty = false;
+ }
+ if (_desktopLibrariesDirtyGeneration == librariesGeneration) {
+ _desktopLibrariesDirty = false;
+ }
+ if (_desktopOverviewDirtyGeneration == overviewGeneration) {
+ _desktopOverviewDirty = false;
+ }
+ setState(() {
+ _loadedOnce = true;
+ _loading = false;
+ });
+ _leaveUnavailablePodcastSection();
}
bool get _hasRmab =>
@@ -167,6 +251,11 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {
final tt = Theme.of(context).textTheme;
final l = AppLocalizations.of(context)!;
+ final desktopPresentation = _desktopPresentation ?? false;
+ if (desktopPresentation) {
+ return _buildDesktopScaffold(context, l);
+ }
+
return Scaffold(
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
body: SafeArea(
@@ -175,11 +264,10 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {
: DesktopPageBody(
child: RefreshIndicator(
onRefresh: _loadAll,
- notificationPredicate: (n) =>
- !isDesktopWorkspace(context) && n.depth == 0,
+ notificationPredicate: (n) => !desktopPresentation && n.depth == 0,
child: ListView(
padding: EdgeInsets.only(
- bottom: isDesktopWorkspace(context) ? 24 : 80),
+ bottom: desktopPresentation ? 24 : 80),
children: [
// ── Header ──
Padding(
@@ -193,7 +281,7 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {
onPressed: () => showAdminTasksSheet(context, _taskTracker),
),
),
- if (isDesktopWorkspace(context))
+ if (desktopPresentation)
IconButton(
tooltip: l.refreshTooltip,
icon: Icon(Icons.refresh_rounded, color: cs.onSurfaceVariant),
@@ -369,6 +457,449 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {
// ─── Shared Widgets ─────────────────────────────────────────
+ Widget _buildDesktopScaffold(BuildContext context, AppLocalizations l) {
+ final outerNavigator = Navigator.of(context);
+ final destinations = <AdminSectionDestination>[
+ AdminSectionDestination(_overviewSection, Icons.dashboard_rounded, l.adminServer),
+ AdminSectionDestination('users', Icons.people_rounded, l.adminUsers),
+ AdminSectionDestination('upload', Icons.cloud_upload_rounded, l.adminUploadTitle),
+ if (_hasPodcastLibrary || _desktopSection == 'podcasts')
+ AdminSectionDestination('podcasts', Icons.podcasts_rounded, l.adminPodcasts),
+ AdminSectionDestination('email', Icons.email_rounded, l.adminEmail),
+ AdminSectionDestination('api-keys', Icons.vpn_key_rounded, l.adminApiKeys),
+ AdminSectionDestination('libraries', Icons.library_books_rounded, l.adminLibrariesManage),
+ AdminSectionDestination('server-settings', Icons.tune_rounded, l.adminServerSettings),
+ AdminSectionDestination('stats', Icons.bar_chart_rounded, l.adminStats),
+ AdminSectionDestination('sessions', Icons.history_rounded, l.adminAllSessions),
+ ];
+
+ return Scaffold(
+ backgroundColor: Theme.of(context).scaffoldBackgroundColor,
+ body: SafeArea(
+ child: _loading
+ ? const Center(child: CircularProgressIndicator(strokeWidth: 2))
+ : PopScope(
+ canPop: !_desktopNavigatorCanPop,
+ onPopInvokedWithResult: (didPop, result) {
+ if (didPop) return;
+ final navigator = _desktopNavigatorKey.currentState;
+ if (navigator != null) unawaited(navigator.maybePop(result));
+ },
+ child: AdminAdaptiveFrame(
+ desktopMode: true,
+ title: l.adminTitle,
+ selectedSection: _desktopSection,
+ destinations: destinations,
+ onSectionSelected: (section) => unawaited(_selectDesktopSection(section)),
+ child: Navigator(
+ key: _desktopNavigatorKey,
+ observers: [_desktopNavigatorObserver],
+ onDidRemovePage: (_) {},
+ pages: [
+ MaterialPage<void>(
+ key: const ValueKey('admin-overview-page'),
+ name: '/admin/overview',
+ child: Builder(
+ builder: (pageContext) => _buildDesktopOverview(
+ pageContext,
+ onClose: () => outerNavigator.pop(),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _buildDesktopOverview(BuildContext pageContext, {required VoidCallback onClose}) {
+ final cs = Theme.of(pageContext).colorScheme;
+ final tt = Theme.of(pageContext).textTheme;
+ final l = AppLocalizations.of(pageContext)!;
+
+ return DesktopPageBody(
+ maxWidth: 1040,
+ child: RefreshIndicator(
+ onRefresh: _loadAll,
+ notificationPredicate: (_) => false,
+ child: ListView(
+ padding: const EdgeInsets.only(bottom: 24),
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 12, 8, 0),
+ child: Row(children: [
+ Expanded(child: AbsorbPageHeader(title: l.adminTitle, padding: EdgeInsets.zero)),
+ ListenableBuilder(
+ listenable: _taskTracker,
+ builder: (_, __) => AdminTaskIndicator(
+ tasks: _taskTracker.visibleTasks,
+ onPressed: () => showAdminTasksSheet(pageContext, _taskTracker),
+ ),
+ ),
+ IconButton(
+ tooltip: l.refreshTooltip,
+ icon: Icon(Icons.refresh_rounded, color: cs.onSurfaceVariant),
+ onPressed: _loadAll,
+ ),
+ IconButton(
+ icon: Icon(Icons.close_rounded, color: cs.onSurfaceVariant),
+ onPressed: onClose,
+ ),
+ ]),
+ ),
+ const SizedBox(height: 20),
+ _section(cs, tt, l.adminServer),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Container(
+ padding: const EdgeInsets.all(16),
+ decoration: _cardDeco(cs),
+ child: Row(children: [
+ _stat(tt, cs, Icons.dns_rounded, _serverVersion ?? '–', l.adminVersion),
+ _stat(tt, cs, Icons.people_rounded, '${_users.length}', l.adminUsers),
+ _stat(tt, cs, Icons.wifi_rounded, '${_onlineUsers.length}', l.adminOnline),
+ _stat(tt, cs, Icons.backup_rounded, '${_backups.length}', l.adminBackupsLabel),
+ ]),
+ ),
+ ),
+ const SizedBox(height: 8),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Row(children: [
+ Expanded(child: _actionBtn(cs, tt, Icons.backup_rounded, l.adminBackup, _creatingBackup, _createBackup)),
+ const SizedBox(width: 10),
+ Expanded(child: _actionBtn(cs, tt, Icons.cleaning_services_rounded, l.adminPurgeCache, _purgingCache, _purgeCache)),
+ ]),
+ ),
+ const SizedBox(height: 28),
+ _section(cs, tt, l.adminRmab),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: _hasRmab ? _rmabTile(cs, tt) : _rmabAddRow(cs, tt),
+ ),
+ const SizedBox(height: 28),
+ if (_activeSessions.isNotEmpty) ...[
+ _section(cs, tt, l.adminListeningNow),
+ ..._activeSessions.map((session) => _sessionCard(cs, tt, session)),
+ const SizedBox(height: 18),
+ ],
+ _section(cs, tt, l.adminLibraries),
+ ListenableBuilder(
+ listenable: _taskTracker,
+ builder: (_, __) => Column(
+ children: _libraries.map((library) => _libraryCard(cs, tt, library)).toList(),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ void _onDesktopStackChanged() {
+ DesktopWorkspaceNavigator.notifyExitGuardChanged();
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted) return;
+ final canPop = _desktopNavigatorKey.currentState?.canPop() ?? false;
+ if (canPop != _desktopNavigatorCanPop) {
+ setState(() => _desktopNavigatorCanPop = canPop);
+ }
+ });
+ }
+
+ Future<void> _selectDesktopSection(String section) async {
+ final navigator = _desktopNavigatorKey.currentState;
+ if (navigator == null || _desktopNavigationChanging) return;
+ if (section == _desktopSection &&
+ (section != _overviewSection || !navigator.canPop())) return;
+
+ final previousSection = _desktopSection;
+ final previousSerial = _desktopNavigationSerial;
+ _desktopNavigationChanging = true;
+ final navigationSerial = ++_desktopNavigationSerial;
+
+ try {
+ if (!await _popDesktopNavigatorToOverview(navigator)) {
+ _desktopNavigationSerial = previousSerial;
+ return;
+ }
+ if (!mounted || _desktopNavigatorKey.currentState != navigator) return;
+ _markDesktopSectionDirty(previousSection);
+
+ if (section == _overviewSection) {
+ if (_desktopSection != _overviewSection || _desktopNavigatorCanPop) {
+ setState(() {
+ _desktopSection = _overviewSection;
+ _desktopNavigatorCanPop = false;
+ });
+ }
+ unawaited(_refreshDesktopOverviewIfNeeded());
+ return;
+ }
+
+ setState(() {
+ _desktopSection = section;
+ _desktopNavigatorCanPop = true;
+ });
+ final sectionPreparation = _prepareDesktopSectionInputs(section);
+ final route = MaterialPageRoute<void>(
+ settings: RouteSettings(name: '/admin/$section'),
+ builder: (routeContext) => _buildPreparedDesktopSectionPage(
+ routeContext,
+ section,
+ sectionPreparation,
+ ),
+ );
+ unawaited(navigator.push(route).then((_) {
+ if (!mounted || navigationSerial != _desktopNavigationSerial) return;
+ setState(() {
+ _desktopSection = _overviewSection;
+ _desktopNavigatorCanPop = false;
+ });
+ _markDesktopSectionDirty(section);
+ unawaited(_refreshDesktopOverviewIfNeeded());
+ }));
+ } finally {
+ _desktopNavigationChanging = false;
+ }
+ }
+
+ Future<bool> _prepareForDesktopPaneReset() async {
+ if (!mounted || _desktopPresentation != true) return true;
+ final navigator = _desktopNavigatorKey.currentState;
+ if (navigator == null || !navigator.canPop()) return true;
+ if (_desktopNavigationChanging) return false;
+
+ final previousSerial = _desktopNavigationSerial;
+ _desktopNavigationChanging = true;
+ _desktopNavigationSerial++;
+ try {
+ if (!await _popDesktopNavigatorToOverview(navigator)) {
+ _desktopNavigationSerial = previousSerial;
+ return false;
+ }
+ if (mounted) {
+ setState(() {
+ _desktopSection = _overviewSection;
+ _desktopNavigatorCanPop = false;
+ });
+ }
+ return true;
+ } finally {
+ _desktopNavigationChanging = false;
+ }
+ }
+
+ Future<bool> _popDesktopNavigatorToOverview(
+ NavigatorState navigator,
+ ) async {
+ while (navigator.canPop()) {
+ final routeDepth = _desktopNavigatorObserver.routeDepth;
+ await navigator.maybePop();
+ if (_desktopNavigatorObserver.routeDepth >= routeDepth) return false;
+ }
+ return true;
+ }
+
+ void _markDesktopSectionDirty(String section) {
+ if (section == 'users') {
+ _desktopUsersDirty = true;
+ _desktopUsersDirtyGeneration++;
+ _desktopOverviewDirty = true;
+ _desktopOverviewDirtyGeneration++;
+ } else if (section == 'libraries') {
+ _desktopLibrariesDirty = true;
+ _desktopLibrariesDirtyGeneration++;
+ _desktopOverviewDirty = true;
+ _desktopOverviewDirtyGeneration++;
+ } else if (section == 'sessions') {
+ _desktopOverviewDirty = true;
+ _desktopOverviewDirtyGeneration++;
+ }
+ }
+
+ Future<void> _refreshDesktopOverviewIfNeeded() async {
+ if (!_desktopOverviewDirty || _desktopOverviewRefreshActive) return;
+ _desktopOverviewRefreshActive = true;
+ try {
+ do {
+ await _loadAll();
+ } while (mounted && _desktopOverviewDirty);
+ } catch (error) {
+ debugPrint('[Admin] Could not refresh overview: $error');
+ } finally {
+ _desktopOverviewRefreshActive = false;
+ }
+ }
+
+ Future<void>? _prepareDesktopSectionInputs(String nextSection) {
+ if (_desktopUsersDirty &&
+ (nextSection == 'email' ||
+ nextSection == 'api-keys' ||
+ nextSection == 'sessions')) {
+ return _refreshDesktopUsers();
+ }
+ if (_desktopLibrariesDirty &&
+ (nextSection == 'users' ||
+ nextSection == 'upload' ||
+ nextSection == 'podcasts')) {
+ return _refreshDesktopLibraries();
+ }
+ return null;
+ }
+
+ Future<void> _refreshDesktopUsers() {
+ final activeRefresh = _desktopUsersRefresh;
+ if (activeRefresh != null) return activeRefresh;
+ final refresh = _runDesktopUsersRefresh();
+ _desktopUsersRefresh = refresh;
+ unawaited(refresh.whenComplete(() {
+ if (identical(_desktopUsersRefresh, refresh)) {
+ _desktopUsersRefresh = null;
+ }
+ }));
+ return refresh;
+ }
+
+ Future<void> _runDesktopUsersRefresh() async {
+ if (!mounted) return;
+ final api = context.read<AuthProvider>().apiService;
+ if (api == null) return;
+ try {
+ do {
+ final generation = _desktopUsersDirtyGeneration;
+ final results = await Future.wait([
+ api.getUsers(),
+ api.getOnlineUsers(),
+ ]);
+ if (!mounted) return;
+ setState(() {
+ _users = results[0];
+ _onlineUsers = results[1];
+ if (_desktopUsersDirtyGeneration == generation) {
+ _desktopUsersDirty = false;
+ }
+ });
+ } while (mounted && _desktopUsersDirty);
+ } catch (error) {
+ debugPrint('[Admin] Could not refresh users: $error');
+ }
+ }
+
+ Future<void> _refreshDesktopLibraries() {
+ final activeRefresh = _desktopLibrariesRefresh;
+ if (activeRefresh != null) return activeRefresh;
+ final refresh = _runDesktopLibrariesRefresh();
+ _desktopLibrariesRefresh = refresh;
+ unawaited(refresh.whenComplete(() {
+ if (identical(_desktopLibrariesRefresh, refresh)) {
+ _desktopLibrariesRefresh = null;
+ }
+ }));
+ return refresh;
+ }
+
+ Future<void> _runDesktopLibrariesRefresh() async {
+ if (!mounted) return;
+ final api = context.read<AuthProvider>().apiService;
+ if (api == null) return;
+ try {
+ do {
+ final generation = _desktopLibrariesDirtyGeneration;
+ final libraries = await api.getLibraries();
+ if (!mounted) return;
+ setState(() {
+ _libraries = libraries;
+ if (_desktopLibrariesDirtyGeneration == generation) {
+ _desktopLibrariesDirty = false;
+ }
+ });
+ } while (mounted && _desktopLibrariesDirty);
+ _leaveUnavailablePodcastSection();
+ } catch (error) {
+ debugPrint('[Admin] Could not refresh libraries: $error');
+ }
+ }
+
+ void _leaveUnavailablePodcastSection() {
+ if (_desktopPresentation != true ||
+ _desktopSection != 'podcasts' ||
+ _hasPodcastLibrary) {
+ return;
+ }
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted ||
+ _desktopSection != 'podcasts' ||
+ _hasPodcastLibrary) {
+ return;
+ }
+ unawaited(_selectDesktopSection(_overviewSection));
+ });
+ }
+
+ Widget _buildPreparedDesktopSectionPage(
+ BuildContext routeContext,
+ String section,
+ Future<void>? preparation,
+ ) {
+ if (preparation == null) {
+ return _buildDesktopSectionPage(routeContext, section);
+ }
+ return FutureBuilder<void>(
+ future: preparation,
+ builder: (context, snapshot) {
+ if (snapshot.connectionState != ConnectionState.done) {
+ return Scaffold(
+ backgroundColor: Theme.of(context).scaffoldBackgroundColor,
+ body: const Center(
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ),
+ );
+ }
+ return _buildDesktopSectionPage(context, section);
+ },
+ );
+ }
+
+ Widget _buildDesktopSectionPage(BuildContext routeContext, String section) {
+ switch (section) {
+ case 'users':
+ return AdminUsersScreen(users: _users, onlineUsers: _onlineUsers, libraries: _libraries);
+ case 'upload':
+ return AdminUploadScreen(
+ libraries: _libraries,
+ initialLibraryId: routeContext.read<AuthProvider>().defaultLibraryId,
+ apiService: routeContext.read<AuthProvider>().apiService,
+ onNavigationGuardChanged:
+ DesktopWorkspaceNavigator.notifyExitGuardChanged,
+ );
+ case 'podcasts':
+ final podcastLibrary = _libraries.firstWhere(
+ (library) => library['mediaType'] == 'podcast',
+ orElse: () => null,
+ );
+ return podcastLibrary == null
+ ? const SizedBox.shrink()
+ : AdminPodcastsScreen(library: podcastLibrary);
+ case 'email':
+ return AdminEmailScreen(users: _users);
+ case 'api-keys':
+ return AdminApiKeysScreen(users: _users);
+ case 'libraries':
+ return AdminLibrariesScreen(libraries: _libraries);
+ case 'server-settings':
+ return const AdminServerSettingsScreen();
+ case 'stats':
+ return const AdminStatsScreen();
+ case 'sessions':
+ return AdminSessionsScreen(users: _users);
+ default:
+ return const SizedBox.shrink();
+ }
+ }
+
Widget _section(ColorScheme cs, TextTheme tt, String t) => Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 10),
child: Text(t, style: tt.labelLarge?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.6), fontWeight: FontWeight.w600, letterSpacing: 0.5)));
@@ -520,7 +1051,8 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {
final l = AppLocalizations.of(context)!;
return GestureDetector(
onTap: () async {
- await Navigator.push(context, MaterialPageRoute(
+ final navigator = _desktopNavigatorKey.currentState ?? Navigator.of(context);
+ await navigator.push(MaterialPageRoute(
builder: (_) => AdminMissingItemsScreen(library: Map<String, dynamic>.from(lib as Map))));
_loadAll();
},
diff --git a/lib/screens/admin_upload_screen.dart b/lib/screens/admin_upload_screen.dart
index 6b488118..6d78d4eb 100644
--- a/lib/screens/admin_upload_screen.dart
+++ b/lib/screens/admin_upload_screen.dart
@@ -40,6 +40,7 @@ class AdminUploadScreen extends StatefulWidget {
final UploadPathChecker? pathChecker;
final MediaUploader? uploader;
final BookMetadataSearcher? metadataSearcher;
+ final VoidCallback? onNavigationGuardChanged;
const AdminUploadScreen({
super.key,
@@ -50,6 +51,7 @@ class AdminUploadScreen extends StatefulWidget {
this.pathChecker,
this.uploader,
this.metadataSearcher,
+ this.onNavigationGuardChanged,
});
@override
@@ -508,6 +510,7 @@ class _AdminUploadScreenState extends State<AdminUploadScreen> {
_uploading = true;
_progress = null;
});
+ widget.onNavigationGuardChanged?.call();
final pathResult = widget.pathChecker != null
? await widget.pathChecker!(request.directory, _folderPath)
@@ -518,11 +521,13 @@ class _AdminUploadScreenState extends State<AdminUploadScreen> {
if (!mounted) return;
if (!pathResult.success) {
setState(() => _uploading = false);
+ widget.onNavigationGuardChanged?.call();
_showError(l.adminUploadPathCheckFailed);
return;
}
if (pathResult.exists) {
setState(() => _uploading = false);
+ widget.onNavigationGuardChanged?.call();
final existingTitle = pathResult.libraryItemTitle;
_showError(
existingTitle == null || existingTitle.isEmpty
@@ -559,6 +564,7 @@ class _AdminUploadScreenState extends State<AdminUploadScreen> {
_files = [];
}
});
+ widget.onNavigationGuardChanged?.call();
if (result.success) {
showOverlayToast(
@@ -608,9 +614,11 @@ class _AdminUploadScreenState extends State<AdminUploadScreen> {
final tt = Theme.of(context).textTheme;
final l = AppLocalizations.of(context)!;
- return Scaffold(
- backgroundColor: Theme.of(context).scaffoldBackgroundColor,
- body: SafeArea(
+ return PopScope(
+ canPop: !_uploading,
+ child: Scaffold(
+ backgroundColor: Theme.of(context).scaffoldBackgroundColor,
+ body: SafeArea(
child: Column(
children: [
Padding(
@@ -711,6 +719,7 @@ class _AdminUploadScreenState extends State<AdminUploadScreen> {
),
],
),
+ ),
),
);
}
diff --git a/lib/screens/app_shell.dart b/lib/screens/app_shell.dart
index 3f8e479d..73416a77 100644
--- a/lib/screens/app_shell.dart
+++ b/lib/screens/app_shell.dart
@@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
+import 'package:shared_preferences/shared_preferences.dart';
import '../providers/auth_provider.dart';
import '../providers/library_provider.dart';
import '../services/audio_player_service.dart';
@@ -26,6 +27,7 @@ import '../services/android_auto_service.dart';
import '../services/carplay_service.dart';
import '../widgets/expanded_card.dart';
import '../widgets/desktop_account_button.dart';
+import '../widgets/desktop_collapsible_sidebar.dart';
import '../widgets/desktop_now_playing_bar.dart';
import 'absorbing_screen.dart';
import 'admin_screen.dart';
@@ -91,35 +93,7 @@ class AppShell extends StatefulWidget {
) {
final inst = _AppShellState._instance;
if (inst == null) return false;
- // If the full-screen expanded player is on top of the shell, pop it
- // first. Otherwise switching to the Library tab leaves the player
- // covering the filtered library underneath. Caller (e.g. the book
- // detail sheet) has already popped its own modal route at this point.
- if (inst._expandedIsOpen && inst.mounted) {
- Navigator.of(inst.context, rootNavigator: true).maybePop();
- }
- inst._navigateTo(1);
- // The retry budget has to survive the fade transition (~200ms by
- // default, see `_fadeController` and `_navigateTo`) plus the library
- // widget's own mount + first build. On cold start that easily takes
- // 300-500ms before `_libraryKey.currentState` becomes non-null. ~3s
- // worth of frames is generous enough to cover slow devices and stingy
- // enough to give up if something is genuinely broken.
- const maxAttempts = 180; // ~3s at 60fps
- var attempts = 0;
- void tryApply() {
- if (!inst.mounted) return;
- final state = inst._libraryKey.currentState;
- if (state != null) {
- apply(state);
- return;
- }
- if (++attempts < maxAttempts) {
- WidgetsBinding.instance.addPostFrameCallback((_) => tryApply());
- }
- }
-
- WidgetsBinding.instance.addPostFrameCallback((_) => tryApply());
+ unawaited(inst._applyLibraryFilterAfterPaneReset(apply));
return true;
}
@@ -140,6 +114,7 @@ class AppShell extends StatefulWidget {
class _AppShellState extends State<AppShell>
with WidgetsBindingObserver, TickerProviderStateMixin {
static _AppShellState? _instance;
+ static const _desktopSidebarPinnedKey = 'desktop_sidebar_pinned';
// Tabs: 0=Home, 1=Library, 2=Absorbing (default), 3=Stats, 4=Settings
int _currentIndex = 2; // overridden by user preference in initState
@@ -180,9 +155,41 @@ class _AppShellState extends State<AppShell>
// Desktop workspace content-pane navigator: full-page pushes land here so
// the sidebar and now-playing bar stay visible around them.
final _paneNavigatorKey = GlobalKey<NavigatorState>();
+ bool _adminRouteOpen = false;
+ bool _desktopWorkspaceWasActive = false;
+ bool _desktopCollapseAllowed = false;
+ bool _desktopCollapseCheckScheduled = false;
+ bool _desktopSidebarPinned = false;
+ int _desktopSidebarPreferenceGeneration = 0;
+
+ Future<void> _loadDesktopSidebarPreference() async {
+ final generation = _desktopSidebarPreferenceGeneration;
+ final prefs = await SharedPreferences.getInstance();
+ final pinned = prefs.getBool(_desktopSidebarPinnedKey) ?? false;
+ if (!mounted ||
+ generation != _desktopSidebarPreferenceGeneration ||
+ pinned == _desktopSidebarPinned) {
+ return;
+ }
+ setState(() => _desktopSidebarPinned = pinned);
+ }
- void _openSearch() {
- if (!mounted) return;
+ void _setDesktopSidebarPinned(bool pinned) {
+ _desktopSidebarPreferenceGeneration++;
+ if (pinned == _desktopSidebarPinned) return;
+ setState(() => _desktopSidebarPinned = pinned);
+ unawaited(_saveDesktopSidebarPreference(pinned));
+ }
+
+ Future<void> _saveDesktopSidebarPreference(bool pinned) async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setBool(_desktopSidebarPinnedKey, pinned);
+ }
+
+ void _openSearch() => unawaited(_openSearchAfterPaneReset());
+
+ Future<void> _openSearchAfterPaneReset() async {
+ if (!await _preparePaneForNavigation()) return;
// If the user triggered Search while a pushed route (Downloads, Bookmarks,
// Settings pages, etc.) is on top of the shell, pop back so the shell's
// Library tab actually becomes visible.
@@ -190,8 +197,10 @@ class _AppShellState extends State<AppShell>
if (nav != null && nav.canPop()) {
nav.popUntil((r) => r.isFirst);
}
- _paneNavigatorKey.currentState?.popUntil((r) => r.isFirst);
- _navigateTo(1);
+ final lib = context.read<LibraryProvider>();
+ final podcastsShown = _podcastsShown(lib);
+ if (podcastsShown) _syncTabLibrary(1, true);
+ _navigateToPrepared(1);
// Library tab may need a frame to mount its state before we can focus
// the search field. Retry up to a few frames to cover fade transitions.
int attempts = 0;
@@ -210,19 +219,36 @@ class _AppShellState extends State<AppShell>
WidgetsBinding.instance.addPostFrameCallback((_) => tryFocus());
}
- void _switchToAbsorbing() {
- if (mounted) {
- _navigateTo(2);
- // Scroll to the currently playing book after the tab switch
- WidgetsBinding.instance.addPostFrameCallback((_) {
- AbsorbingScreen.scrollToActive();
- });
- }
+ void _switchToAbsorbing() => unawaited(_switchToAbsorbingAfterPaneReset());
+
+ Future<void> _switchToAbsorbingAfterPaneReset() async {
+ if (!mounted || !await _navigateToAfterPaneReset(2)) return;
+ // Scroll to the currently playing book after the tab switch
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ AbsorbingScreen.scrollToActive();
+ });
}
- void _navigateTo(int index) {
+ void _navigateTo(int index) => unawaited(_navigateToAfterPaneReset(index));
+
+ Future<bool> _preparePaneForNavigation() async {
+ if (!mounted ||
+ !await DesktopWorkspaceNavigator.prepareForPaneReset() ||
+ !mounted) {
+ return false;
+ }
// A tab click while a pushed page fills the pane should reveal the tab.
_paneNavigatorKey.currentState?.popUntil((r) => r.isFirst);
+ return true;
+ }
+
+ Future<bool> _navigateToAfterPaneReset(int index) async {
+ if (!await _preparePaneForNavigation()) return false;
+ _navigateToPrepared(index);
+ return true;
+ }
+
+ void _navigateToPrepared(int index) {
if (index == _currentIndex) {
// Already on this tab — handle re-tap actions
if (index == 2) {
@@ -246,6 +272,42 @@ class _AppShellState extends State<AppShell>
}
}
+ Future<void> _applyLibraryFilterAfterPaneReset(
+ void Function(LibraryScreenState) apply,
+ ) async {
+ if (!await _preparePaneForNavigation()) return;
+ // If the full-screen expanded player is on top of the shell, pop it
+ // first. Otherwise switching to the Library tab leaves the player
+ // covering the filtered library underneath. Caller (e.g. the book
+ // detail sheet) has already popped its own modal route at this point.
+ if (_expandedIsOpen && mounted) {
+ await Navigator.of(context, rootNavigator: true).maybePop();
+ if (!mounted) return;
+ }
+ _navigateToPrepared(1);
+ // The retry budget has to survive the fade transition (~200ms by
+ // default, see `_fadeController` and `_navigateTo`) plus the library
+ // widget's own mount + first build. On cold start that easily takes
+ // 300-500ms before `_libraryKey.currentState` becomes non-null. ~3s
+ // worth of frames is generous enough to cover slow devices and stingy
+ // enough to give up if something is genuinely broken.
+ const maxAttempts = 180; // ~3s at 60fps
+ var attempts = 0;
+ void tryApply() {
+ if (!mounted) return;
+ final state = _libraryKey.currentState;
+ if (state != null) {
+ apply(state);
+ return;
+ }
+ if (++attempts < maxAttempts) {
+ WidgetsBinding.instance.addPostFrameCallback((_) => tryApply());
+ }
+ }
+
+ WidgetsBinding.instance.addPostFrameCallback((_) => tryApply());
+ }
+
/// Subscribe to the active screen's barsRevealNotifier when on Home or
/// Library tab, and ensure the nav bar is visible on all other tabs.
void _syncNavBarListener(int index) {
@@ -343,6 +405,10 @@ class _AppShellState extends State<AppShell>
super.initState();
_instance = this;
DesktopWorkspaceNavigator.register(() => _paneNavigatorKey.currentState);
+ DesktopWorkspaceNavigator.exitGuardChanges.addListener(
+ _onDesktopExitGuardChanged,
+ );
+ unawaited(_loadDesktopSidebarPreference());
if (AppPlatform.isWeb) {
_currentIndex = 0;
} else if (!widget.startOnAbsorbing) {
@@ -466,6 +532,9 @@ class _AppShellState extends State<AppShell>
try {
context.read<LibraryProvider>().removeListener(_onLibraryChanged);
} catch (_) {}
+ DesktopWorkspaceNavigator.exitGuardChanges.removeListener(
+ _onDesktopExitGuardChanged,
+ );
if (_instance == this) {
_instance = null;
DesktopWorkspaceNavigator.unregister();
@@ -706,6 +775,40 @@ class _AppShellState extends State<AppShell>
_libraryKey.currentState?.resetReveal();
}
+ void _onDesktopExitGuardChanged() {
+ if (!mounted || !_desktopWorkspaceWasActive || _desktopCollapseAllowed) {
+ return;
+ }
+ _scheduleDesktopWorkspaceCollapseCheck();
+ }
+
+ void _scheduleDesktopWorkspaceCollapseCheck() {
+ if (_desktopCollapseCheckScheduled) return;
+ _desktopCollapseCheckScheduled = true;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ unawaited(_checkDesktopWorkspaceCollapse());
+ });
+ }
+
+ Future<void> _checkDesktopWorkspaceCollapse() async {
+ if (!mounted) return;
+ final view = View.of(context);
+ final width = view.physicalSize.width / view.devicePixelRatio;
+ if (width >= kDesktopWorkspaceBreakpoint) {
+ _desktopCollapseCheckScheduled = false;
+ return;
+ }
+ final allowed = await DesktopWorkspaceNavigator.prepareForPaneReset();
+ if (!mounted) return;
+ _desktopCollapseCheckScheduled = false;
+ final currentView = View.of(context);
+ final currentWidth =
+ currentView.physicalSize.width / currentView.devicePixelRatio;
+ if (allowed && currentWidth < kDesktopWorkspaceBreakpoint) {
+ setState(() => _desktopCollapseAllowed = true);
+ }
+ }
+
DateTime? _lastRefresh;
static const _refreshCooldown = Duration(minutes: 1);
@@ -742,13 +845,27 @@ class _AppShellState extends State<AppShell>
final workspaceTier = AppPlatform.isWeb
? workspaceLayoutTierForWidth(constraints.maxWidth)
: WorkspaceLayoutTier.mobile;
- final useDesktopWorkspace =
- workspaceTier != WorkspaceLayoutTier.mobile;
+ final desktopRequested = workspaceTier != WorkspaceLayoutTier.mobile;
+ var useDesktopWorkspace = desktopRequested;
+ if (desktopRequested) {
+ _desktopWorkspaceWasActive = true;
+ _desktopCollapseAllowed = false;
+ } else if (_desktopWorkspaceWasActive && !_desktopCollapseAllowed) {
+ useDesktopWorkspace = true;
+ _scheduleDesktopWorkspaceCollapseCheck();
+ } else {
+ _desktopWorkspaceWasActive = false;
+ _desktopCollapseAllowed = false;
+ }
return PopScope(
canPop: false,
onPopInvokedWithResult: _handleBack,
child: useDesktopWorkspace
- ? _buildDesktopWorkspace(context, workspaceTier)
+ ? _buildDesktopWorkspace(
+ context,
+ allowPinnedSidebar: desktopRequested &&
+ usesExtendedDesktopSidebar(workspaceTier),
+ )
: Scaffold(
body: _buildPageStack(context),
bottomNavigationBar: _buildBottomNav(context),
@@ -761,22 +878,27 @@ class _AppShellState extends State<AppShell>
void _handleBack(bool didPop, Object? _) {
if (didPop) return;
- if (_currentIndex == 1 &&
- _libraryKey.currentState?.isSearchActive == true) {
- _libraryKey.currentState?.clearSearch();
- return;
- }
-
if (AppPlatform.isWeb) {
final pane = _paneNavigatorKey.currentState;
if (pane != null && pane.canPop()) {
- pane.pop();
+ unawaited(pane.maybePop());
+ return;
+ }
+ if (_currentIndex == 1 &&
+ _libraryKey.currentState?.isSearchActive == true) {
+ _libraryKey.currentState?.clearSearch();
return;
}
if (_currentIndex != 0) _navigateTo(0);
return;
}
+ if (_currentIndex == 1 &&
+ _libraryKey.currentState?.isSearchActive == true) {
+ _libraryKey.currentState?.clearSearch();
+ return;
+ }
+
if (_currentIndex == 2) {
final now = DateTime.now();
if (_lastBackPress != null &&
@@ -810,53 +932,47 @@ class _AppShellState extends State<AppShell>
}
Widget _buildDesktopWorkspace(
- BuildContext context,
- WorkspaceLayoutTier workspaceTier,
- ) {
+ BuildContext context, {
+ required bool allowPinnedSidebar,
+ }) {
final lib = context.watch<LibraryProvider>();
final podcastsShown = _podcastsShown(lib);
final destinations = _buildDestinations(context, podcastsShown);
+ final sidebarPinned = allowPinnedSidebar && _desktopSidebarPinned;
return Scaffold(
- body: Row(
- children: [
- _buildDesktopSidebar(
- context,
- lib: lib,
- podcastsShown: podcastsShown,
- destinations: destinations,
- workspaceTier: workspaceTier,
- ),
- VerticalDivider(
- width: 1,
- thickness: 1,
- color: Theme.of(
- context,
- ).colorScheme.outlineVariant.withValues(alpha: 0.45),
- ),
- Expanded(
- child: LayoutBuilder(
- // The MediaQuery override sits outside the pane Navigator so
- // pushed pages also lay out against the pane, not the window.
- // The tab stack is a declarative page so it keeps rebuilding
- // with this State; pushed routes stack on top imperatively.
- builder: (context, constraints) => MediaQuery(
- data: MediaQuery.of(context).copyWith(
- size: Size(constraints.maxWidth, constraints.maxHeight),
- ),
- child: ClipRect(
- child: Navigator(
- key: _paneNavigatorKey,
- onDidRemovePage: (page) {},
- pages: [
- MaterialPage(child: _buildPageStack(context)),
- ],
- ),
+ body: DesktopSidebarLayout(
+ pinned: sidebarPinned,
+ canPin: allowPinnedSidebar,
+ onPinnedChanged: _setDesktopSidebarPinned,
+ sidebarBuilder: (sidebarContext, extended) => _buildDesktopSidebar(
+ sidebarContext,
+ lib: lib,
+ podcastsShown: podcastsShown,
+ destinations: destinations,
+ extended: extended,
+ ),
+ child: LayoutBuilder(
+ // The MediaQuery override sits outside the pane Navigator so pushed
+ // pages also lay out against the pane, not the window. The tab stack
+ // is declarative so it keeps rebuilding below imperative routes.
+ builder: (context, constraints) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(
+ size: Size(constraints.maxWidth, constraints.maxHeight),
+ ),
+ child: DesktopWorkspaceScope(
+ child: ClipRect(
+ child: Navigator(
+ key: _paneNavigatorKey,
+ onDidRemovePage: (page) {},
+ pages: [
+ MaterialPage(child: _buildPageStack(context)),
+ ],
),
),
),
),
- ],
+ ),
),
bottomNavigationBar: shouldShowDesktopNowPlayingBar(_currentIndex)
? DesktopNowPlayingBar(
@@ -873,7 +989,7 @@ class _AppShellState extends State<AppShell>
required LibraryProvider lib,
required bool podcastsShown,
required List<NavigationDestination> destinations,
- required WorkspaceLayoutTier workspaceTier,
+ required bool extended,
}) {
final theme = Theme.of(context);
final cs = theme.colorScheme;
@@ -890,17 +1006,16 @@ class _AppShellState extends State<AppShell>
final serverLabel = parsedServer?.host.isNotEmpty == true
? parsedServer!.host
: serverUrl;
- final extended = usesExtendedDesktopSidebar(workspaceTier);
-
- void openSearch() {
- if (podcastsShown) _syncTabLibrary(1, true);
- _openSearch();
- }
+ void openSearch() => _openSearch();
void openAdmin() {
- _paneNavigatorKey.currentState?.push(
- MaterialPageRoute<void>(builder: (_) => const AdminScreen()),
- );
+ if (_adminRouteOpen) return;
+ final navigator = _paneNavigatorKey.currentState;
+ if (navigator == null) return;
+ _adminRouteOpen = true;
+ unawaited(navigator
+ .push(MaterialPageRoute<void>(builder: (_) => const AdminScreen()))
+ .whenComplete(() => _adminRouteOpen = false));
}
void openAccountMenu() {
@@ -932,13 +1047,15 @@ class _AppShellState extends State<AppShell>
return SafeArea(
child: SizedBox(
- width: desktopSidebarWidth(workspaceTier),
+ width: extended
+ ? DesktopCollapsibleSidebar.expandedWidth
+ : DesktopCollapsibleSidebar.collapsedWidth,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: extended
- ? const EdgeInsets.fromLTRB(20, 18, 16, 12)
+ ? const EdgeInsets.fromLTRB(20, 18, 60, 12)
: const EdgeInsets.fromLTRB(12, 18, 12, 12),
child: Row(
mainAxisAlignment: extended
@@ -1100,7 +1217,14 @@ class _AppShellState extends State<AppShell>
);
}
- void _selectDestination(int dest, bool podcastsShown) {
+ void _selectDestination(int dest, bool podcastsShown) =>
+ unawaited(_selectDestinationAfterPaneReset(dest, podcastsShown));
+
+ Future<void> _selectDestinationAfterPaneReset(
+ int dest,
+ bool podcastsShown,
+ ) async {
+ if (!await _preparePaneForNavigation()) return;
final lib = context.read<LibraryProvider>();
final page = _pageForDest(dest, podcastsShown);
if (page == 1 &&
@@ -1111,7 +1235,7 @@ class _AppShellState extends State<AppShell>
return;
}
_syncTabLibrary(dest, podcastsShown);
- _navigateTo(page);
+ _navigateToPrepared(page);
if (page >= 0 && page <= 3) _refreshDataForTab(page);
}
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 4c179961..c3803ad8 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -1300,6 +1300,7 @@ class AudioPlayerService extends ChangeNotifier {
StreamSubscription? _syncSub;
StreamSubscription? _completionSub;
StreamSubscription? _nativeAutoAdvanceSub;
+ StreamSubscription<Object>? _audioServiceErrorSub;
// ── Pre-buffer next book in queue (iOS background auto-advance fix) ──
// iOS denies background audio output to freshly-loaded AVPlayerItems.
@@ -2338,6 +2339,9 @@ class AudioPlayerService extends ChangeNotifier {
);
// Bind service so handler routes play/pause through service (for auto-rewind)
_handler!.bindService(_instance);
+ _instance._audioServiceErrorSub ??= AudioService.asyncError.listen(
+ (error) => debugPrint('[AudioService] Platform error: $error'),
+ );
// Wire the EQ service's skip-silence toggle through to just_audio.
// Android-only: just_audio's setSkipSilenceEnabled is a no-op on iOS.
if (AppPlatform.isAndroid) {
@@ -4310,14 +4314,16 @@ class AudioPlayerService extends ChangeNotifier {
// screen shows artwork even when the user is offline. Fall back to the
// remote HTTP URL when there's no local cover (streaming).
String? effectiveCoverUrl;
- if (AppPlatform.isIOS) {
+ if (AppPlatform.isWeb) {
+ effectiveCoverUrl = coverUrl;
+ } else if (AppPlatform.isIOS) {
final localCover = DownloadService().getInfo(itemId).localCoverPath;
if (localCover != null && localCover.isNotEmpty) {
effectiveCoverUrl = Uri.file(localCover).toString();
} else {
effectiveCoverUrl = coverUrl;
}
- } else {
+ } else if (AppPlatform.isAndroid) {
effectiveCoverUrl = 'content://$_coverAuthority/cover/$itemId';
if (coverCacheBust != null) effectiveCoverUrl += '?cb=$coverCacheBust';
// Streamed cover (no local file) won't be cached on first play - schedule
@@ -4328,6 +4334,8 @@ class AudioPlayerService extends ChangeNotifier {
_coverRepushItem = itemId;
_scheduleStreamedCoverRepush(itemId);
}
+ } else {
+ effectiveCoverUrl = coverUrl;
}
_updateNotificationMediaItem(
itemId,
@@ -6123,6 +6131,7 @@ class AudioPlayerService extends ChangeNotifier {
_stuckCheckTimer?.cancel();
_playVerifyTimer?.cancel();
_indexSub?.cancel();
+ _audioServiceErrorSub?.cancel();
_player?.dispose();
super.dispose();
}
diff --git a/lib/services/scoped_prefs.dart b/lib/services/scoped_prefs.dart
index 6a1026ad..1da0cac6 100644
--- a/lib/services/scoped_prefs.dart
+++ b/lib/services/scoped_prefs.dart
@@ -31,6 +31,7 @@ class ScopedPrefs {
'loggingEnabled', 'manual_offline_mode',
'custom_download_path', 'custom_download_uri', 'downloads',
'absorb_device_id',
+ 'desktop_sidebar_pinned',
'widget_item_id', 'widget_episode_id',
'cached_stats', 'cached_sessions',
'update_last_check', 'update_dismissed_version',
diff --git a/lib/utils/desktop_workspace.dart b/lib/utils/desktop_workspace.dart
index 20de8d52..04659dbc 100644
--- a/lib/utils/desktop_workspace.dart
+++ b/lib/utils/desktop_workspace.dart
@@ -1,3 +1,4 @@
+import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'app_platform.dart';
@@ -32,11 +33,50 @@ double desktopSidebarWidth(WorkspaceLayoutTier tier) =>
/// desktop and on the root navigator everywhere else.
abstract final class DesktopWorkspaceNavigator {
static NavigatorState? Function()? _resolver;
+ static Object? _exitGuardOwner;
+ static Future<bool> Function()? _exitGuard;
+ static final ValueNotifier<int> _exitGuardChanges = ValueNotifier<int>(0);
+
+ static ValueListenable<int> get exitGuardChanges => _exitGuardChanges;
static void register(NavigatorState? Function() resolver) =>
_resolver = resolver;
- static void unregister() => _resolver = null;
+ static void registerExitGuard(Object owner, Future<bool> Function() guard) {
+ _exitGuardOwner = owner;
+ _exitGuard = guard;
+ notifyExitGuardChanged();
+ }
+
+ static void unregisterExitGuard(Object owner) {
+ if (!identical(_exitGuardOwner, owner)) return;
+ _exitGuardOwner = null;
+ _exitGuard = null;
+ notifyExitGuardChanged();
+ }
+
+ static void notifyExitGuardChanged() => _exitGuardChanges.value++;
+
+ static Future<bool> prepareForPaneReset() =>
+ _exitGuard?.call() ?? Future.value(true);
+
+ static void unregister() {
+ _resolver = null;
+ _exitGuardOwner = null;
+ _exitGuard = null;
+ notifyExitGuardChanged();
+ }
+}
+
+class DesktopWorkspaceScope extends InheritedWidget {
+ const DesktopWorkspaceScope({super.key, required super.child});
+
+ static bool isActive(BuildContext context) =>
+ context.dependOnInheritedWidgetOfExactType<DesktopWorkspaceScope>() !=
+ null;
+
+ @override
+ bool updateShouldNotify(DesktopWorkspaceScope oldWidget) => false;
}
NavigatorState contentNavigator(BuildContext context) =>
@@ -49,6 +89,7 @@ NavigatorState contentNavigator(BuildContext context) =>
/// disagree with the shell's own breakpoint between 960 and ~1208px.
bool isDesktopWorkspace(BuildContext context) {
if (!AppPlatform.isWeb) return false;
+ if (DesktopWorkspaceScope.isActive(context)) return true;
// Subscribe to size changes so callers rebuild on window resize.
MediaQuery.sizeOf(context);
final view = View.of(context);
diff --git a/lib/widgets/absorbing_card.dart b/lib/widgets/absorbing_card.dart
index 281dbb90..181271ba 100644
--- a/lib/widgets/absorbing_card.dart
+++ b/lib/widgets/absorbing_card.dart
@@ -857,6 +857,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
builder: (context, cardConstraints) {
final textScale = MediaQuery.textScalerOf(context).scale(1.0).clamp(1.0, 1.5);
final compact = cardConstraints.maxHeight < 600 * textScale;
+ final spaciousDesktop = desktopPresentation && cardConstraints.maxWidth >= 1280;
// In landscape the card is wider than tall — switch to a two-pane
// layout with the cover on the left and everything else on the right.
final wide = cardConstraints.maxWidth > cardConstraints.maxHeight;
@@ -930,7 +931,9 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
listenable: Listenable.merge([ChromecastService(), widget.player]),
builder: (context, _) => LayoutBuilder(
builder: (context, constraints) {
- final maxW = constraints.maxWidth * 0.75;
+ final maxW = spaciousDesktop
+ ? (constraints.maxWidth * 0.9).clamp(0.0, 780.0).toDouble()
+ : constraints.maxWidth * 0.75;
final rawH = constraints.maxHeight.isFinite ? constraints.maxHeight : maxW;
final maxH = rawH - 24;
double coverW, coverH;
@@ -987,6 +990,9 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
}
} : null,
child: Container(
+ key: desktopPresentation
+ ? const ValueKey('desktop-player-cover')
+ : null,
width: coverW,
height: coverH,
decoration: BoxDecoration(
@@ -1136,7 +1142,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
builder: (context, buttonsConstraints) => FittedBox(
fit: BoxFit.scaleDown,
child: SizedBox(
- width: buttonsConstraints.maxWidth - 40,
+ width: buttonsConstraints.maxWidth,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
@@ -1225,7 +1231,8 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
child: ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: 640),
+ key: const ValueKey('desktop-player-details'),
+ constraints: BoxConstraints(maxWidth: spaciousDesktop ? 760 : 640),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -1234,7 +1241,8 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
primaryTitle,
maxLines: 3,
overflow: TextOverflow.ellipsis,
- style: tt.headlineSmall?.copyWith(fontWeight: FontWeight.w700, height: 1.12),
+ style: (spaciousDesktop ? tt.headlineMedium : tt.headlineSmall)
+ ?.copyWith(fontWeight: FontWeight.w700, height: 1.12),
),
if (contextLine.isNotEmpty) ...[
const SizedBox(height: 8),
@@ -1260,6 +1268,28 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
),
);
+ if (spaciousDesktop) {
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 32),
+ child: Center(
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 1680),
+ child: SizedBox(
+ width: double.infinity,
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Expanded(flex: 10, child: coverArea),
+ const SizedBox(width: 48),
+ Expanded(flex: 9, child: details),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
if (cardConstraints.maxWidth >= 760) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
diff --git a/lib/widgets/adaptive_modal.dart b/lib/widgets/adaptive_modal.dart
index a6a98f42..3ed7da28 100644
--- a/lib/widgets/adaptive_modal.dart
+++ b/lib/widgets/adaptive_modal.dart
@@ -305,28 +305,39 @@ class _DesktopDialogBodyState extends State<_DesktopDialogBody> {
child: Builder(builder: widget.builder),
);
if (!widget.closeButton) return content;
- return Stack(
- children: [
- content,
- Positioned(
- top: 8,
- right: 8,
- child: Material(
- color: cs.surfaceContainerHighest.withValues(alpha: 0.85),
- shape: const CircleBorder(),
- clipBehavior: Clip.antiAlias,
- child: IconButton(
- visualDensity: VisualDensity.compact,
- icon: Icon(
- Icons.close_rounded,
- size: 20,
- color: cs.onSurfaceVariant,
+ return ModalSurface(
+ desktop: true,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ SizedBox(
+ key: const ValueKey('desktop-dialog-chrome'),
+ height: 48,
+ child: Align(
+ alignment: Alignment.centerRight,
+ child: Padding(
+ padding: const EdgeInsets.only(right: 8),
+ child: Material(
+ color: cs.surfaceContainerHighest.withValues(alpha: 0.85),
+ shape: const CircleBorder(),
+ clipBehavior: Clip.antiAlias,
+ child: IconButton(
+ key: const ValueKey('desktop-dialog-close-button'),
+ visualDensity: VisualDensity.compact,
+ icon: Icon(
+ Icons.close_rounded,
+ size: 20,
+ color: cs.onSurfaceVariant,
+ ),
+ onPressed: () => Navigator.of(context).pop(),
+ ),
+ ),
),
- onPressed: () => Navigator.of(context).pop(),
),
),
- ),
- ],
+ Flexible(child: Builder(builder: widget.builder)),
+ ],
+ ),
);
}
}
diff --git a/lib/widgets/admin_adaptive_frame.dart b/lib/widgets/admin_adaptive_frame.dart
new file mode 100644
index 00000000..1be1aaab
--- /dev/null
+++ b/lib/widgets/admin_adaptive_frame.dart
@@ -0,0 +1,146 @@
+import 'package:flutter/material.dart';
+
+class AdminSectionDestination {
+ final String id;
+ final IconData icon;
+ final String label;
+
+ const AdminSectionDestination(this.id, this.icon, this.label);
+}
+
+class AdminAdaptiveFrame extends StatelessWidget {
+ final bool desktopMode;
+ final String title;
+ final String selectedSection;
+ final List<AdminSectionDestination> destinations;
+ final ValueChanged<String> onSectionSelected;
+ final Widget child;
+
+ const AdminAdaptiveFrame({
+ super.key,
+ required this.desktopMode,
+ required this.title,
+ required this.selectedSection,
+ required this.destinations,
+ required this.onSectionSelected,
+ required this.child,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ if (!desktopMode) return child;
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+
+ return LayoutBuilder(
+ builder: (context, constraints) {
+ // The desktop shell may stay mounted briefly below its breakpoint so
+ // an in-progress upload cannot be abandoned. Give the upload pane the
+ // full narrow width instead of squeezing it between two sidebars.
+ if (constraints.maxWidth < 720) return child;
+
+ return Row(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ SizedBox(
+ key: const Key('admin-desktop-sidebar'),
+ width: 224,
+ child: Material(
+ color: cs.surface.withValues(alpha: 0.38),
+ child: ListView(
+ padding: const EdgeInsets.fromLTRB(14, 20, 14, 20),
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
+ child: Text(
+ title,
+ style: tt.labelMedium?.copyWith(
+ color: cs.onSurfaceVariant,
+ fontWeight: FontWeight.w700,
+ letterSpacing: 0.8,
+ ),
+ ),
+ ),
+ for (final destination in destinations)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 4),
+ child: Material(
+ color: selectedSection == destination.id
+ ? cs.primary.withValues(alpha: 0.14)
+ : Colors.transparent,
+ borderRadius: BorderRadius.circular(11),
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ key: ValueKey(
+ 'admin-destination-${destination.id}',
+ ),
+ onTap: () => onSectionSelected(destination.id),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 12,
+ vertical: 11,
+ ),
+ child: Row(
+ children: [
+ Icon(
+ destination.icon,
+ size: 19,
+ color: selectedSection == destination.id
+ ? cs.primary
+ : cs.onSurfaceVariant,
+ ),
+ const SizedBox(width: 11),
+ Expanded(
+ child: Text(
+ destination.label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.bodyMedium?.copyWith(
+ color: selectedSection == destination.id
+ ? cs.onSurface
+ : cs.onSurfaceVariant,
+ fontWeight:
+ selectedSection == destination.id
+ ? FontWeight.w700
+ : FontWeight.w500,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ VerticalDivider(
+ width: 1,
+ thickness: 1,
+ color: cs.outlineVariant.withValues(alpha: 0.35),
+ ),
+ Expanded(
+ key: const Key('admin-desktop-content'),
+ child: Align(
+ alignment: Alignment.topCenter,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 1040),
+ child: LayoutBuilder(
+ builder: (context, constraints) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(
+ size: Size(constraints.maxWidth, constraints.maxHeight),
+ ),
+ child: ClipRect(child: SizedBox.expand(child: child)),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ );
+ },
+ );
+ }
+}
diff --git a/lib/widgets/desktop_collapsible_sidebar.dart b/lib/widgets/desktop_collapsible_sidebar.dart
new file mode 100644
index 00000000..8bbd8e81
--- /dev/null
+++ b/lib/widgets/desktop_collapsible_sidebar.dart
@@ -0,0 +1,204 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+typedef DesktopSidebarBuilder =
+ Widget Function(BuildContext context, bool extended);
+
+class DesktopSidebarLayout extends StatelessWidget {
+ const DesktopSidebarLayout({
+ super.key,
+ required this.pinned,
+ required this.canPin,
+ required this.onPinnedChanged,
+ required this.sidebarBuilder,
+ required this.child,
+ });
+
+ static const reservedSpaceKey = ValueKey<String>(
+ 'desktop-sidebar-reserved-space',
+ );
+
+ final bool pinned;
+ final bool canPin;
+ final ValueChanged<bool> onPinnedChanged;
+ final DesktopSidebarBuilder sidebarBuilder;
+ final Widget child;
+
+ @override
+ Widget build(BuildContext context) {
+ final reservedWidth = pinned
+ ? DesktopCollapsibleSidebar.expandedWidth
+ : DesktopCollapsibleSidebar.collapsedWidth;
+
+ return Stack(
+ children: [
+ Row(
+ children: [
+ AnimatedContainer(
+ key: reservedSpaceKey,
+ width: reservedWidth,
+ duration: const Duration(milliseconds: 160),
+ curve: Curves.easeOutCubic,
+ ),
+ Expanded(child: child),
+ ],
+ ),
+ Positioned(
+ left: 0,
+ top: 0,
+ bottom: 0,
+ child: DesktopCollapsibleSidebar(
+ pinned: pinned,
+ canPin: canPin,
+ onPinnedChanged: onPinnedChanged,
+ builder: sidebarBuilder,
+ ),
+ ),
+ ],
+ );
+ }
+}
+
+class DesktopCollapsibleSidebar extends StatefulWidget {
+ const DesktopCollapsibleSidebar({
+ super.key,
+ required this.pinned,
+ required this.onPinnedChanged,
+ required this.builder,
+ this.canPin = true,
+ this.pinTooltip = 'Keep sidebar expanded',
+ this.unpinTooltip = 'Unpin sidebar',
+ });
+
+ static const panelKey = ValueKey<String>('desktop-collapsible-sidebar');
+ static const pinButtonKey = ValueKey<String>('desktop-sidebar-pin-button');
+ static const double collapsedWidth = 72;
+ static const double expandedWidth = 248;
+
+ final bool pinned;
+ final ValueChanged<bool> onPinnedChanged;
+ final DesktopSidebarBuilder builder;
+ final bool canPin;
+ final String pinTooltip;
+ final String unpinTooltip;
+
+ @override
+ State<DesktopCollapsibleSidebar> createState() =>
+ _DesktopCollapsibleSidebarState();
+}
+
+class _DesktopCollapsibleSidebarState extends State<DesktopCollapsibleSidebar> {
+ bool _hovering = false;
+ bool _focusWithin = false;
+ Timer? _collapseTimer;
+
+ void _showForPointer() {
+ _collapseTimer?.cancel();
+ if (!_hovering) setState(() => _hovering = true);
+ }
+
+ void _schedulePointerCollapse() {
+ _collapseTimer?.cancel();
+ _collapseTimer = Timer(const Duration(milliseconds: 120), () {
+ if (mounted && _hovering) setState(() => _hovering = false);
+ });
+ }
+
+ @override
+ void dispose() {
+ _collapseTimer?.cancel();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ final cs = theme.colorScheme;
+ final extended = widget.pinned || _hovering || _focusWithin;
+ final width = extended
+ ? DesktopCollapsibleSidebar.expandedWidth
+ : DesktopCollapsibleSidebar.collapsedWidth;
+
+ return Focus(
+ canRequestFocus: false,
+ onFocusChange: (focused) {
+ if (focused != _focusWithin) setState(() => _focusWithin = focused);
+ },
+ onKeyEvent: (_, event) {
+ if (!widget.pinned &&
+ event is KeyDownEvent &&
+ event.logicalKey == LogicalKeyboardKey.escape) {
+ FocusManager.instance.primaryFocus?.unfocus();
+ if (_focusWithin) setState(() => _focusWithin = false);
+ return KeyEventResult.handled;
+ }
+ return KeyEventResult.ignored;
+ },
+ child: MouseRegion(
+ onEnter: (_) => _showForPointer(),
+ onExit: (_) => _schedulePointerCollapse(),
+ child: AnimatedContainer(
+ key: DesktopCollapsibleSidebar.panelKey,
+ width: width,
+ duration: const Duration(milliseconds: 160),
+ curve: Curves.easeOutCubic,
+ clipBehavior: Clip.hardEdge,
+ decoration: BoxDecoration(
+ color: theme.scaffoldBackgroundColor,
+ border: Border(
+ right: BorderSide(
+ color: cs.outlineVariant.withValues(alpha: 0.45),
+ ),
+ ),
+ boxShadow: extended && !widget.pinned
+ ? [
+ BoxShadow(
+ color: Colors.black.withValues(alpha: 0.18),
+ blurRadius: 18,
+ offset: const Offset(6, 0),
+ ),
+ ]
+ : null,
+ ),
+ child: OverflowBox(
+ alignment: Alignment.topLeft,
+ minWidth: width,
+ maxWidth: width,
+ child: SizedBox(
+ width: width,
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ widget.builder(context, extended),
+ if (extended && widget.canPin)
+ Positioned(
+ top: 14,
+ right: 8,
+ child: Tooltip(
+ message: widget.pinned
+ ? widget.unpinTooltip
+ : widget.pinTooltip,
+ child: IconButton(
+ key: DesktopCollapsibleSidebar.pinButtonKey,
+ onPressed: () =>
+ widget.onPinnedChanged(!widget.pinned),
+ icon: Icon(
+ widget.pinned
+ ? Icons.keyboard_double_arrow_left_rounded
+ : Icons.push_pin_outlined,
+ size: 20,
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/packages/audio_service_web/LICENSE b/packages/audio_service_web/LICENSE
new file mode 100644
index 00000000..465ef6d6
--- /dev/null
+++ b/packages/audio_service_web/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2021 Keagan Hilliard and the audio_service_web contributors.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/packages/audio_service_web/lib/audio_service_web.dart b/packages/audio_service_web/lib/audio_service_web.dart
new file mode 100644
index 00000000..417ef889
--- /dev/null
+++ b/packages/audio_service_web/lib/audio_service_web.dart
@@ -0,0 +1,222 @@
+import 'dart:async';
+import 'dart:js_interop' as js;
+import 'dart:js_interop_unsafe';
+
+import 'package:audio_service_platform_interface/audio_service_platform_interface.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter_web_plugins/flutter_web_plugins.dart';
+import 'package:web/web.dart' as web;
+
+import 'js/media_session_web.dart';
+
+class AudioServiceWeb extends AudioServicePlatform {
+ static void registerWith(Registrar registrar) {
+ AudioServicePlatform.instance = AudioServiceWeb();
+ }
+
+ web.MediaSession get _mediaSession => web.window.navigator.mediaSession;
+
+ final _mediaSessionSupported = _SupportChecker(
+ () => js.globalContext.hasProperty('MediaSession'.toJS).toDart,
+ 'MediaSession is not supported in this browser, so the plugin is a no-op',
+ );
+ final _setPositionStateSupported = _SupportChecker(
+ () => web.window.navigator.mediaSession
+ .hasProperty('setPositionState'.toJS)
+ .toDart,
+ 'MediaSession.setPositionState is not supported in this browser',
+ );
+ final Set<String> _unsupportedActions = {};
+
+ AudioHandlerCallbacks? handlerCallbacks;
+ MediaItemMessage? mediaItem;
+
+ @override
+ Future<void> configure(ConfigureRequest request) async {
+ _mediaSessionSupported.check();
+ }
+
+ @override
+ Future<void> setState(SetStateRequest request) async {
+ if (!_mediaSessionSupported.check()) return;
+
+ final state = request.state;
+ _mediaSession.playbackState = switch (state.processingState) {
+ AudioProcessingStateMessage.idle => MediaSessionPlaybackState.none,
+ _ when state.playing => MediaSessionPlaybackState.playing,
+ _ => MediaSessionPlaybackState.paused,
+ };
+
+ _installCoreHandlers();
+ for (final control in state.controls) {
+ switch (control.action) {
+ case MediaActionMessage.rewind:
+ _setActionHandler(MediaSessionActions.seekbackward, (_) {
+ unawaited(handlerCallbacks?.rewind(const RewindRequest()));
+ });
+ case MediaActionMessage.fastForward:
+ _setActionHandler(MediaSessionActions.seekforward, (_) {
+ unawaited(
+ handlerCallbacks?.fastForward(const FastForwardRequest()),
+ );
+ });
+ case MediaActionMessage.skipToPrevious:
+ _setActionHandler(MediaSessionActions.previoustrack, (_) {
+ unawaited(
+ handlerCallbacks?.skipToPrevious(const SkipToPreviousRequest()),
+ );
+ });
+ case MediaActionMessage.skipToNext:
+ _setActionHandler(MediaSessionActions.nexttrack, (_) {
+ unawaited(
+ handlerCallbacks?.skipToNext(const SkipToNextRequest()),
+ );
+ });
+ case MediaActionMessage.stop:
+ _setActionHandler(MediaSessionActions.stop, (_) {
+ unawaited(handlerCallbacks?.stop(const StopRequest()));
+ });
+ case MediaActionMessage.play:
+ case MediaActionMessage.pause:
+ default:
+ break;
+ }
+ }
+
+ if (state.systemActions.contains(MediaActionMessage.seek)) {
+ _setActionHandler(MediaSessionActions.seekto, (details) {
+ final seekTime = details.seekTime;
+ if (seekTime == null || !seekTime.isFinite) return;
+ unawaited(
+ handlerCallbacks?.seek(
+ SeekRequest(
+ position: Duration(
+ milliseconds: (seekTime * 1000).round(),
+ ),
+ ),
+ ),
+ );
+ });
+ }
+
+ _updatePositionState(state);
+ }
+
+ void _installCoreHandlers() {
+ _setActionHandler(MediaSessionActions.play, (_) {
+ unawaited(handlerCallbacks?.play(const PlayRequest()));
+ });
+ _setActionHandler(MediaSessionActions.pause, (_) {
+ unawaited(handlerCallbacks?.pause(const PauseRequest()));
+ });
+ }
+
+ void _setActionHandler(
+ String action,
+ void Function(MediaSessionActionDetails) handler,
+ ) {
+ try {
+ _mediaSession.setActionHandler(action, handler.toJS);
+ } catch (error) {
+ if (_unsupportedActions.add(action)) {
+ debugPrint(
+ '[AudioServiceWeb] Media action "$action" is unavailable: $error',
+ );
+ }
+ }
+ }
+
+ void _updatePositionState(PlaybackStateMessage state) {
+ if (!_setPositionStateSupported.check()) return;
+
+ final durationSeconds =
+ (mediaItem?.duration ?? Duration.zero).inMilliseconds / 1000;
+ final rate = state.speed;
+ if (!durationSeconds.isFinite ||
+ durationSeconds <= 0 ||
+ !rate.isFinite ||
+ rate <= 0) {
+ try {
+ _mediaSession.setPositionState();
+ } catch (_) {}
+ return;
+ }
+
+ final rawPosition = state.updatePosition.inMilliseconds / 1000;
+ final position = rawPosition.isFinite
+ ? rawPosition.clamp(0.0, durationSeconds).toDouble()
+ : 0.0;
+ try {
+ _mediaSession.setPositionState(
+ web.MediaPositionState(
+ duration: durationSeconds,
+ playbackRate: rate,
+ position: position,
+ ),
+ );
+ } catch (error) {
+ debugPrint('[AudioServiceWeb] Could not update media position: $error');
+ }
+ }
+
+ @override
+ Future<void> setQueue(SetQueueRequest request) async {}
+
+ @override
+ Future<void> setMediaItem(SetMediaItemRequest request) async {
+ if (!_mediaSessionSupported.check()) return;
+
+ mediaItem = request.mediaItem;
+ final item = request.mediaItem;
+ final artUri = item.artUri;
+ final artwork = artUri != null && _isBrowserArtworkUri(artUri)
+ ? [web.MediaImage(src: artUri.toString(), sizes: '512x512')]
+ : <web.MediaImage>[];
+
+ _mediaSession.metadata = web.MediaMetadata(
+ web.MediaMetadataInit(
+ title: item.title,
+ artist: item.artist ?? '',
+ album: item.album ?? '',
+ artwork: artwork.toJS,
+ ),
+ );
+ }
+
+ bool _isBrowserArtworkUri(Uri uri) =>
+ uri.scheme == 'http' ||
+ uri.scheme == 'https' ||
+ uri.scheme == 'data' ||
+ uri.scheme == 'blob';
+
+ @override
+ Future<void> stopService(StopServiceRequest request) async {
+ if (!_mediaSessionSupported.check()) return;
+ _mediaSession.playbackState = MediaSessionPlaybackState.none;
+ _mediaSession.metadata = null;
+ mediaItem = null;
+ }
+
+ @override
+ void setHandlerCallbacks(AudioHandlerCallbacks callbacks) {
+ handlerCallbacks = callbacks;
+ if (_mediaSessionSupported.check()) _installCoreHandlers();
+ }
+}
+
+class _SupportChecker {
+ _SupportChecker(this._checkCallback, this._warningMessage);
+
+ final ValueGetter<bool> _checkCallback;
+ final String _warningMessage;
+ bool _logged = false;
+
+ bool check() {
+ final supported = _checkCallback();
+ if (!_logged && !supported) {
+ _logged = true;
+ debugPrint('[AudioServiceWeb] $_warningMessage');
+ }
+ return supported;
+ }
+}
diff --git a/packages/audio_service_web/lib/js/media_session_web.dart b/packages/audio_service_web/lib/js/media_session_web.dart
new file mode 100644
index 00000000..dbc8c0d1
--- /dev/null
+++ b/packages/audio_service_web/lib/js/media_session_web.dart
@@ -0,0 +1,30 @@
+@JS()
+library;
+
+import 'dart:js_interop';
+
+abstract final class MediaSessionPlaybackState {
+ static const none = 'none';
+ static const paused = 'paused';
+ static const playing = 'playing';
+}
+
+abstract final class MediaSessionActions {
+ static const play = 'play';
+ static const pause = 'pause';
+ static const seekbackward = 'seekbackward';
+ static const seekforward = 'seekforward';
+ static const previoustrack = 'previoustrack';
+ static const nexttrack = 'nexttrack';
+ static const stop = 'stop';
+ static const seekto = 'seekto';
+}
+
+@JS()
+@anonymous
+extension type MediaSessionActionDetails._(JSObject _) implements JSObject {
+ external String get action;
+ external bool? get fastSeek;
+ external double? get seekOffset;
+ external double? get seekTime;
+}
diff --git a/packages/audio_service_web/pubspec.yaml b/packages/audio_service_web/pubspec.yaml
new file mode 100644
index 00000000..3e76de7e
--- /dev/null
+++ b/packages/audio_service_web/pubspec.yaml
@@ -0,0 +1,28 @@
+name: audio_service_web
+description: Web platform implementation of audio_service, vendored for Absorb.
+version: 0.1.4+absorb.1
+publish_to: none
+
+environment:
+ sdk: ">=3.3.0 <4.0.0"
+ flutter: ">=3.0.0"
+
+dependencies:
+ audio_service_platform_interface: ^0.1.3
+ web: ">=0.5.1 <2.0.0"
+ flutter:
+ sdk: flutter
+ flutter_web_plugins:
+ sdk: flutter
+
+dev_dependencies:
+ flutter_test:
+ sdk: flutter
+ flutter_lints: ^3.0.1
+
+flutter:
+ plugin:
+ platforms:
+ web:
+ pluginClass: AudioServiceWeb
+ fileName: audio_service_web.dart
diff --git a/pubspec.lock b/pubspec.lock
index dee53550..40c4185b 100644
--- a/pubspec.lock
+++ b/pubspec.lock
@@ -81,13 +81,12 @@ packages:
source: hosted
version: "0.1.3"
audio_service_web:
- dependency: transitive
+ dependency: "direct overridden"
description:
- name: audio_service_web
- sha256: b8ea9243201ee53383157fbccf13d5d2a866b5dda922ec19d866d1d5d70424df
- url: "https://pub.dev"
- source: hosted
- version: "0.1.4"
+ path: "packages/audio_service_web"
+ relative: true
+ source: path
+ version: "0.1.4+absorb.1"
audio_session:
dependency: "direct main"
description:
diff --git a/pubspec.yaml b/pubspec.yaml
index 979a0f3f..b6f7fa64 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -118,6 +118,10 @@ dev_dependencies:
rename_app: ^1.6.5
mocktail: ^1.0.4
+dependency_overrides:
+ audio_service_web:
+ path: packages/audio_service_web
+
flutter:
generate: true
uses-material-design: true