Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Show server tasks across the web app and fix desktop scrolling, playback, and gradients

Barnabas61d717879cad
diff --git a/lib/screens/absorbing_screen.dart b/lib/screens/absorbing_screen.dart
index 2402a1c1..833e7545 100644
--- a/lib/screens/absorbing_screen.dart
+++ b/lib/screens/absorbing_screen.dart
@@ -24,14 +24,29 @@ import '../l10n/app_localizations.dart';
import '../services/wording.dart';
import '../utils/desktop_workspace.dart';
-const double kAbsorbingSidePanelOpenBreakpoint = 1180;
-
-bool shouldOpenAbsorbingSidePanelByDefault(double paneWidth) =>
- paneWidth >= kAbsorbingSidePanelOpenBreakpoint;
+const double _kAbsorbingDesktopPanelRailWidth = 48;
+const double _kAbsorbingDesktopPanelDividerWidth = 1;
+const double _kAbsorbingDesktopPlayerHorizontalPadding = 24;
double absorbingQueuePaneWidth(double paneWidth) =>
(paneWidth * 0.32).clamp(340.0, 400.0).toDouble();
+double absorbingDesktopPlayerLayoutWidth(double paneWidth) =>
+ (paneWidth -
+ absorbingQueuePaneWidth(paneWidth) -
+ _kAbsorbingDesktopPanelRailWidth -
+ _kAbsorbingDesktopPanelDividerWidth -
+ _kAbsorbingDesktopPlayerHorizontalPadding)
+ .clamp(0.0, double.infinity)
+ .toDouble();
+
+bool shouldOverlayAbsorbingSidePanel(double paneWidth) =>
+ absorbingDesktopPlayerLayoutWidth(paneWidth) <
+ kAbsorbingDesktopRowLayoutWidth;
+
+bool shouldOpenAbsorbingSidePanelByDefault(double paneWidth) =>
+ !shouldOverlayAbsorbingSidePanel(paneWidth);
+
enum DesktopAbsorbingPanelTab { chapters, queue }
class AbsorbingScreen extends StatefulWidget {
@@ -662,22 +677,32 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
return Scaffold(
backgroundColor: scaffoldBg,
- body: Container(
- decoration: flatNotifier.value ? null : BoxDecoration(
- gradient: LinearGradient(
- begin: Alignment.topCenter,
- end: Alignment.bottomCenter,
- stops: const [0.0, 0.22, 0.72, 1.0],
- colors: [
- cs.primary.withValues(alpha: gradientIntensityNotifier.value),
- cs.surface,
- lowerFade,
- scaffoldBg,
- ],
- ),
- ),
- child: SafeArea(
- child: Builder(builder: (context) {
+ body: Stack(
+ children: [
+ if (!flatNotifier.value)
+ Positioned.fill(
+ child: RepaintBoundary(
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.topCenter,
+ end: Alignment.bottomCenter,
+ stops: const [0.0, 0.22, 0.72, 1.0],
+ colors: [
+ cs.primary.withValues(
+ alpha: gradientIntensityNotifier.value,
+ ),
+ cs.surface,
+ lowerFade,
+ scaffoldBg,
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ SafeArea(
+ child: Builder(builder: (context) {
final desktopWorkspace = isDesktopWorkspace(context);
final offlineIcon = OfflineStatusIcon(
onTapWhenOnline: () {
@@ -836,89 +861,132 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
final panelOpen = _desktopPanelOpen ??=
shouldOpenAbsorbingSidePanelByDefault(constraints.maxWidth);
final panelWidth = absorbingQueuePaneWidth(constraints.maxWidth);
+ final playerLayoutWidth =
+ absorbingDesktopPlayerLayoutWidth(constraints.maxWidth);
+ final overlayPanel = shouldOverlayAbsorbingSidePanel(
+ constraints.maxWidth,
+ );
final chapterData = _desktopChapterData?.itemKey == currentKey
? _desktopChapterData
: null;
- return Row(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Expanded(
- child: Padding(
- padding: const EdgeInsets.fromLTRB(12, 8, 12, 16),
- child: RepaintBoundary(
- child: AbsorbingCard(
- key: _cardKey(currentKey),
- item: books[0],
- player: _player,
- presentation: AbsorbingCardPresentation.desktop,
- onChapterDataChanged: _handleDesktopChapterData,
- ),
- ),
- ),
+ final playerPane = Expanded(
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(
+ _kAbsorbingDesktopPlayerHorizontalPadding / 2,
+ 8,
+ _kAbsorbingDesktopPlayerHorizontalPadding / 2,
+ 16,
),
- VerticalDivider(
- width: 1,
- thickness: 1,
- color: cs.outlineVariant.withValues(alpha: 0.45),
+ child: AbsorbingCard(
+ key: _cardKey(currentKey),
+ item: books[0],
+ player: _player,
+ presentation: AbsorbingCardPresentation.desktop,
+ spaciousDesktopLayout: playerLayoutWidth >=
+ kAbsorbingSpaciousDesktopLayoutWidth,
+ onChapterDataChanged: _handleDesktopChapterData,
),
- SizedBox(
- width: 48,
- child: Align(
- alignment: Alignment.topCenter,
- child: Padding(
- padding: const EdgeInsets.only(top: 8),
- child: IconButton(
- key: const ValueKey('desktop-absorbing-panel-toggle'),
- tooltip: panelOpen
- ? MaterialLocalizations.of(context).closeButtonTooltip
- : l.absorbingManageQueue,
- onPressed: () => setState(
- () => _desktopPanelOpen = !panelOpen,
- ),
- icon: Icon(
- panelOpen
- ? Icons.chevron_right_rounded
- : Icons.chevron_left_rounded,
- ),
- ),
+ ),
+ );
+ final panelRail = SizedBox(
+ width: _kAbsorbingDesktopPanelRailWidth,
+ child: Align(
+ alignment: Alignment.topCenter,
+ child: Padding(
+ padding: const EdgeInsets.only(top: 8),
+ child: IconButton(
+ key: const ValueKey(
+ 'desktop-absorbing-panel-toggle',
+ ),
+ tooltip: panelOpen
+ ? MaterialLocalizations.of(context)
+ .closeButtonTooltip
+ : l.absorbingManageQueue,
+ onPressed: () => setState(
+ () => _desktopPanelOpen = !panelOpen,
+ ),
+ icon: Icon(
+ panelOpen
+ ? Icons.chevron_right_rounded
+ : Icons.chevron_left_rounded,
),
),
),
- TweenAnimationBuilder<double>(
- tween: Tween(end: panelOpen ? 1 : 0),
- duration: const Duration(milliseconds: 220),
- curve: Curves.easeOutCubic,
- builder: (context, widthFactor, child) => ClipRect(
- child: Align(
- alignment: Alignment.centerRight,
- widthFactor: widthFactor,
- child: child,
+ ),
+ );
+ return TweenAnimationBuilder<double>(
+ tween: Tween(end: panelOpen ? panelWidth : 0),
+ duration: const Duration(milliseconds: 220),
+ curve: Curves.easeOutCubic,
+ builder: (context, animatedWidth, child) {
+ final devicePixelRatio =
+ MediaQuery.devicePixelRatioOf(context);
+ final visibleWidth =
+ (animatedWidth * devicePixelRatio).round() /
+ devicePixelRatio;
+ final playerRow = Row(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ playerPane,
+ if (!overlayPanel)
+ SizedBox(width: visibleWidth),
+ VerticalDivider(
+ width:
+ _kAbsorbingDesktopPanelDividerWidth,
+ thickness: 1,
+ color: cs.outlineVariant
+ .withValues(alpha: 0.45),
),
- ),
- child: SizedBox(
- width: panelWidth,
- child: _buildDesktopSidePanel(
- context,
- chapterData: chapterData,
- queuePanel: _AbsorbingQueuePanel(
- embedded: true,
- showHeader: false,
- keys: books.map(_absorbingKey).toList(),
- books: books,
- lib: lib,
- scrollController: _desktopQueueScrollController,
- absorbingKeyFn: _absorbingKey,
- queueMode: _queueMode,
- isMerged: _mergeLibraries,
- isPodcast: lib.isPodcastLibrary,
- currentItemId: _currentPlayerKey,
- onQueueModeChanged: (mode) =>
- _handleQueueModeChanged(lib, mode),
+ panelRail,
+ ],
+ );
+ return Stack(
+ fit: StackFit.expand,
+ children: [
+ playerRow,
+ Positioned(
+ top: 0,
+ bottom: 0,
+ right: _kAbsorbingDesktopPanelRailWidth +
+ _kAbsorbingDesktopPanelDividerWidth,
+ child: Offstage(
+ offstage: visibleWidth == 0,
+ child: SizedBox(
+ width: visibleWidth,
+ child: ClipRect(
+ child: OverflowBox(
+ minWidth: panelWidth,
+ maxWidth: panelWidth,
+ alignment: Alignment.centerRight,
+ child: child,
+ ),
+ ),
+ ),
),
),
- ),
+ ],
+ );
+ },
+ child: _buildDesktopSidePanel(
+ context,
+ opaque: overlayPanel,
+ chapterData: chapterData,
+ queuePanel: _AbsorbingQueuePanel(
+ embedded: true,
+ showHeader: false,
+ keys: books.map(_absorbingKey).toList(),
+ books: books,
+ lib: lib,
+ scrollController: _desktopQueueScrollController,
+ absorbingKeyFn: _absorbingKey,
+ queueMode: _queueMode,
+ isMerged: _mergeLibraries,
+ isPodcast: lib.isPodcastLibrary,
+ currentItemId: _currentPlayerKey,
+ onQueueModeChanged: (mode) =>
+ _handleQueueModeChanged(lib, mode),
),
- ],
+ ),
);
}),
),
@@ -1041,8 +1109,9 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
),
],
);
- }),
- ),
+ }),
+ ),
+ ],
),
);
}
@@ -1109,6 +1178,7 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
Widget _buildDesktopSidePanel(
BuildContext context, {
+ required bool opaque,
required AbsorbingChapterData? chapterData,
required Widget queuePanel,
}) {
@@ -1143,7 +1213,7 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
);
return ColoredBox(
- color: cs.surface.withValues(alpha: 0.72),
+ color: opaque ? cs.surface : cs.surface.withValues(alpha: 0.72),
child: Column(children: [
Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 12, 8),
diff --git a/lib/screens/admin_screen.dart b/lib/screens/admin_screen.dart
index db500f25..6477e570 100644
--- a/lib/screens/admin_screen.dart
+++ b/lib/screens/admin_screen.dart
@@ -59,7 +59,9 @@ class _AdminNavigatorObserver extends NavigatorObserver {
}
class AdminScreen extends StatefulWidget {
- const AdminScreen({super.key});
+ final ServerTaskTracker? taskTracker;
+
+ const AdminScreen({super.key, this.taskTracker});
@override State<AdminScreen> createState() => _AdminScreenState();
}
@@ -84,6 +86,7 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {
bool _creatingBackup = false;
bool _purgingCache = false;
late final ServerTaskTracker _taskTracker;
+ late final bool _ownsTaskTracker;
Timer? _issuesDebounce;
Timer? _taskRefreshTimer;
@@ -111,8 +114,9 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {
WidgetsBinding.instance.addObserver(this);
_desktopNavigatorObserver = _AdminNavigatorObserver(_onDesktopStackChanged);
DesktopWorkspaceNavigator.registerExitGuard(this, _prepareForDesktopPaneReset);
- _taskTracker = ServerTaskTracker();
- _startTaskRefreshTimer();
+ _ownsTaskTracker = widget.taskTracker == null;
+ _taskTracker = widget.taskTracker ?? ServerTaskTracker();
+ if (_ownsTaskTracker) _startTaskRefreshTimer();
_loadAll();
SocketService().addItemsChangedListener(_onItemsChanged);
}
@@ -130,12 +134,13 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {
SocketService().removeItemsChangedListener(_onItemsChanged);
_issuesDebounce?.cancel();
_taskRefreshTimer?.cancel();
- _taskTracker.dispose();
+ if (_ownsTaskTracker) _taskTracker.dispose();
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
+ if (!_ownsTaskTracker) return;
if (state == AppLifecycleState.resumed) {
_startTaskRefreshTimer();
unawaited(_refreshServerTasks());
@@ -531,13 +536,6 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {
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),
diff --git a/lib/screens/app_shell.dart b/lib/screens/app_shell.dart
index 73416a77..65fe29d6 100644
--- a/lib/screens/app_shell.dart
+++ b/lib/screens/app_shell.dart
@@ -10,6 +10,7 @@ import '../providers/library_provider.dart';
import '../services/audio_player_service.dart';
import '../services/chromecast_service.dart';
import '../services/home_widget_service.dart';
+import '../services/server_task_tracker.dart';
import '../services/sleep_timer_service.dart';
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
@@ -29,6 +30,7 @@ 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 '../widgets/admin_task_indicator.dart';
import 'absorbing_screen.dart';
import 'admin_screen.dart';
import 'home_screen.dart';
@@ -66,6 +68,9 @@ class AppShell extends StatefulWidget {
_AppShellState._instance?._expandedIsOpen = open;
}
+ static ServerTaskTracker? serverTaskTrackerOf(BuildContext context) =>
+ context.findAncestorStateOfType<_AppShellState>()?._serverTaskTracker;
+
/// Switch to the Library tab and focus the search bar. Used by the
/// app-icon "Search" shortcut. Returns false when the shell isn't mounted
/// yet so callers can retry during cold start.
@@ -111,6 +116,36 @@ class AppShell extends StatefulWidget {
State<AppShell> createState() => _AppShellState();
}
+class _PaneNavigatorObserver extends NavigatorObserver {
+ _PaneNavigatorObserver(this.onStackChanged);
+
+ final VoidCallback onStackChanged;
+
+ @override
+ void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
+ super.didPush(route, previousRoute);
+ onStackChanged();
+ }
+
+ @override
+ void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
+ super.didPop(route, previousRoute);
+ onStackChanged();
+ }
+
+ @override
+ void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
+ super.didRemove(route, previousRoute);
+ onStackChanged();
+ }
+
+ @override
+ void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
+ super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
+ onStackChanged();
+ }
+}
+
class _AppShellState extends State<AppShell>
with WidgetsBindingObserver, TickerProviderStateMixin {
static _AppShellState? _instance;
@@ -155,12 +190,20 @@ 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>();
+ late final _PaneNavigatorObserver _paneNavigatorObserver;
+ bool _paneRouteOpen = false;
bool _adminRouteOpen = false;
bool _desktopWorkspaceWasActive = false;
bool _desktopCollapseAllowed = false;
bool _desktopCollapseCheckScheduled = false;
bool _desktopSidebarPinned = false;
int _desktopSidebarPreferenceGeneration = 0;
+ ServerTaskTracker? _serverTaskTracker;
+ Timer? _serverTaskRefreshTimer;
+ bool _refreshingServerTasks = false;
+ Object? _serverTaskPollingApi;
+ bool _serverTaskPollingEnabled = false;
+ bool _serverTaskPollingSyncScheduled = false;
Future<void> _loadDesktopSidebarPreference() async {
final generation = _desktopSidebarPreferenceGeneration;
@@ -186,6 +229,58 @@ class _AppShellState extends State<AppShell>
await prefs.setBool(_desktopSidebarPinnedKey, pinned);
}
+ void _startServerTaskRefreshTimer() {
+ _serverTaskRefreshTimer?.cancel();
+ _serverTaskRefreshTimer = null;
+ if (!mounted || !AppPlatform.isWeb) return;
+ final auth = context.read<AuthProvider>();
+ if (!auth.isAdmin || auth.apiService == null || _serverTaskTracker == null) {
+ return;
+ }
+ unawaited(_refreshServerTasks());
+ _serverTaskRefreshTimer = Timer.periodic(const Duration(seconds: 3), (_) {
+ unawaited(_refreshServerTasks());
+ });
+ }
+
+ void _syncServerTaskPolling({
+ required bool isAdmin,
+ required Object? api,
+ }) {
+ final enabled = isAdmin && api != null && _serverTaskTracker != null;
+ if (enabled == _serverTaskPollingEnabled &&
+ identical(api, _serverTaskPollingApi)) {
+ return;
+ }
+ _serverTaskPollingEnabled = enabled;
+ _serverTaskPollingApi = api;
+ if (_serverTaskPollingSyncScheduled) return;
+ _serverTaskPollingSyncScheduled = true;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ _serverTaskPollingSyncScheduled = false;
+ if (!mounted) return;
+ if (_serverTaskPollingEnabled && !_lifecycleBackgrounded) {
+ _startServerTaskRefreshTimer();
+ } else {
+ _serverTaskRefreshTimer?.cancel();
+ _serverTaskRefreshTimer = null;
+ }
+ });
+ }
+
+ Future<void> _refreshServerTasks() async {
+ if (!mounted || _refreshingServerTasks) return;
+ final tracker = _serverTaskTracker;
+ final api = context.read<AuthProvider>().apiService;
+ if (tracker == null || api == null) return;
+ _refreshingServerTasks = true;
+ try {
+ await tracker.refresh(api);
+ } finally {
+ _refreshingServerTasks = false;
+ }
+ }
+
void _openSearch() => unawaited(_openSearchAfterPaneReset());
Future<void> _openSearchAfterPaneReset() async {
@@ -404,6 +499,10 @@ class _AppShellState extends State<AppShell>
void initState() {
super.initState();
_instance = this;
+ if (AppPlatform.isWeb) {
+ _serverTaskTracker = ServerTaskTracker();
+ }
+ _paneNavigatorObserver = _PaneNavigatorObserver(_syncPaneRouteState);
DesktopWorkspaceNavigator.register(() => _paneNavigatorKey.currentState);
DesktopWorkspaceNavigator.exitGuardChanges.addListener(
_onDesktopExitGuardChanged,
@@ -528,6 +627,8 @@ class _AppShellState extends State<AppShell>
_navBarAnimController.dispose();
_player.removeListener(_onPlayerChanged);
_cast.removeListener(_onCastChanged);
+ _serverTaskRefreshTimer?.cancel();
+ _serverTaskTracker?.dispose();
PlayerSettings.settingsChanged.removeListener(_loadPodcastTabPrefs);
try {
context.read<LibraryProvider>().removeListener(_onLibraryChanged);
@@ -734,6 +835,7 @@ class _AppShellState extends State<AppShell>
void _handleAppForegrounded() {
if (!_lifecycleBackgrounded) return;
_lifecycleBackgrounded = false;
+ _startServerTaskRefreshTimer();
// The rotation lock lives on the Activity, and Android can recreate the
// activity over the still-running cached engine (swipe away from recents
// while playback keeps the service alive). main() doesn't re-run then, so
@@ -760,6 +862,8 @@ class _AppShellState extends State<AppShell>
void _handleAppBackgrounded() {
if (_lifecycleBackgrounded) return;
_lifecycleBackgrounded = true;
+ _serverTaskRefreshTimer?.cancel();
+ _serverTaskRefreshTimer = null;
context.read<LibraryProvider>().onAppBackgrounded();
SleepTimerService().onAppBackgrounded();
AudioPlayerService.onAppBackgrounded();
@@ -782,6 +886,16 @@ class _AppShellState extends State<AppShell>
_scheduleDesktopWorkspaceCollapseCheck();
}
+ void _syncPaneRouteState() {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted) return;
+ final paneRouteOpen = _paneNavigatorKey.currentState?.canPop() ?? false;
+ if (paneRouteOpen != _paneRouteOpen) {
+ setState(() => _paneRouteOpen = paneRouteOpen);
+ }
+ });
+ }
+
void _scheduleDesktopWorkspaceCollapseCheck() {
if (_desktopCollapseCheckScheduled) return;
_desktopCollapseCheckScheduled = true;
@@ -840,6 +954,12 @@ class _AppShellState extends State<AppShell>
@override
Widget build(BuildContext context) {
+ if (AppPlatform.isWeb) {
+ final taskAccess = context.select<AuthProvider, (bool, Object?)>(
+ (auth) => (auth.isAdmin, auth.apiService),
+ );
+ _syncServerTaskPolling(isAdmin: taskAccess.$1, api: taskAccess.$2);
+ }
return LayoutBuilder(
builder: (context, constraints) {
final workspaceTier = AppPlatform.isWeb
@@ -964,6 +1084,7 @@ class _AppShellState extends State<AppShell>
child: ClipRect(
child: Navigator(
key: _paneNavigatorKey,
+ observers: [_paneNavigatorObserver],
onDidRemovePage: (page) {},
pages: [
MaterialPage(child: _buildPageStack(context)),
@@ -974,7 +1095,10 @@ class _AppShellState extends State<AppShell>
),
),
),
- bottomNavigationBar: shouldShowDesktopNowPlayingBar(_currentIndex)
+ bottomNavigationBar: shouldShowDesktopNowPlayingBar(
+ _currentIndex,
+ paneRouteOpen: _paneRouteOpen,
+ )
? DesktopNowPlayingBar(
player: _player,
library: lib,
@@ -1006,15 +1130,66 @@ class _AppShellState extends State<AppShell>
final serverLabel = parsedServer?.host.isNotEmpty == true
? parsedServer!.host
: serverUrl;
+ final taskTracker = _serverTaskTracker;
void openSearch() => _openSearch();
+ Widget buildBranding(List<ServerTask> tasks) {
+ final showTasks = auth.isAdmin && tasks.isNotEmpty && taskTracker != null;
+ return Row(
+ mainAxisAlignment: extended
+ ? MainAxisAlignment.start
+ : MainAxisAlignment.center,
+ children: [
+ if (!extended && showTasks)
+ AdminTaskIndicator(
+ tasks: tasks,
+ onPressed: () => showAdminTasksSheet(context, taskTracker),
+ )
+ else
+ Container(
+ width: 38,
+ height: 38,
+ decoration: BoxDecoration(
+ color: cs.primaryContainer,
+ borderRadius: BorderRadius.circular(12),
+ ),
+ child: Icon(
+ Icons.graphic_eq_rounded,
+ color: cs.onPrimaryContainer,
+ ),
+ ),
+ if (extended) ...[
+ const SizedBox(width: 12),
+ Expanded(
+ child: Text(
+ l.appTitle,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: theme.textTheme.titleMedium?.copyWith(
+ fontWeight: FontWeight.w800,
+ letterSpacing: 1.4,
+ ),
+ ),
+ ),
+ if (showTasks)
+ AdminTaskIndicator(
+ tasks: tasks,
+ onPressed: () => showAdminTasksSheet(context, taskTracker),
+ ),
+ ],
+ ],
+ );
+ }
+
void openAdmin() {
if (_adminRouteOpen) return;
final navigator = _paneNavigatorKey.currentState;
if (navigator == null) return;
_adminRouteOpen = true;
unawaited(navigator
- .push(MaterialPageRoute<void>(builder: (_) => const AdminScreen()))
+ .push(MaterialPageRoute<void>(
+ builder: (_) => AdminScreen(taskTracker: _serverTaskTracker),
+ ))
.whenComplete(() => _adminRouteOpen = false));
}
@@ -1057,35 +1232,14 @@ class _AppShellState extends State<AppShell>
padding: extended
? const EdgeInsets.fromLTRB(20, 18, 60, 12)
: const EdgeInsets.fromLTRB(12, 18, 12, 12),
- child: Row(
- mainAxisAlignment: extended
- ? MainAxisAlignment.start
- : MainAxisAlignment.center,
- children: [
- Container(
- width: 38,
- height: 38,
- decoration: BoxDecoration(
- color: cs.primaryContainer,
- borderRadius: BorderRadius.circular(12),
- ),
- child: Icon(
- Icons.graphic_eq_rounded,
- color: cs.onPrimaryContainer,
- ),
- ),
- if (extended) ...[
- const SizedBox(width: 12),
- Text(
- l.appTitle,
- style: theme.textTheme.titleMedium?.copyWith(
- fontWeight: FontWeight.w800,
- letterSpacing: 1.4,
+ child: auth.isAdmin && taskTracker != null
+ ? ListenableBuilder(
+ listenable: taskTracker,
+ builder: (_, __) => buildBranding(
+ taskTracker.visibleTasks,
),
- ),
- ],
- ],
- ),
+ )
+ : buildBranding(const []),
),
Padding(
padding: const EdgeInsets.fromLTRB(12, 4, 12, 10),
diff --git a/lib/screens/app_shell_navigation_policy.dart b/lib/screens/app_shell_navigation_policy.dart
index 7b0c64a5..d485bb26 100644
--- a/lib/screens/app_shell_navigation_policy.dart
+++ b/lib/screens/app_shell_navigation_policy.dart
@@ -10,4 +10,7 @@ bool shouldRestoreBookLibrary({
selectedLibraryId == podcastLibraryId;
}
-bool shouldShowDesktopNowPlayingBar(int pageIndex) => pageIndex != 2;
+bool shouldShowDesktopNowPlayingBar(
+ int pageIndex, {
+ bool paneRouteOpen = false,
+}) => pageIndex != 2 || paneRouteOpen;
diff --git a/lib/screens/library_screen.dart b/lib/screens/library_screen.dart
index 64bb3027..5170acb1 100644
--- a/lib/screens/library_screen.dart
+++ b/lib/screens/library_screen.dart
@@ -43,6 +43,65 @@ import '../utils/desktop_workspace.dart';
const double kDesktopLibraryTileMaxExtent = 220;
+LinearGradient _libraryBackgroundGradient(
+ ColorScheme colorScheme,
+ Color scaffoldBackground,
+) {
+ final lowerFade =
+ Color.lerp(colorScheme.surface, scaffoldBackground, 0.55) ??
+ scaffoldBackground;
+ return LinearGradient(
+ begin: Alignment.topCenter,
+ end: Alignment.bottomCenter,
+ stops: const [0.0, 0.22, 0.72, 1.0],
+ colors: [
+ colorScheme.primary.withValues(
+ alpha: gradientIntensityNotifier.value,
+ ),
+ colorScheme.surface,
+ lowerFade,
+ scaffoldBackground,
+ ],
+ );
+}
+
+class _LibraryHeaderGradientPainter extends CustomPainter {
+ const _LibraryHeaderGradientPainter({
+ required this.backgroundColor,
+ required this.gradient,
+ required this.topInset,
+ required this.screenHeight,
+ });
+
+ final Color backgroundColor;
+ final LinearGradient gradient;
+ final double topInset;
+ final double screenHeight;
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ final paintBounds = Offset.zero & size;
+ canvas.drawRect(paintBounds, Paint()..color = backgroundColor);
+ final shaderBounds = Rect.fromLTWH(
+ 0,
+ -topInset,
+ size.width,
+ screenHeight,
+ );
+ canvas.drawRect(
+ paintBounds,
+ Paint()..shader = gradient.createShader(shaderBounds),
+ );
+ }
+
+ @override
+ bool shouldRepaint(_LibraryHeaderGradientPainter oldDelegate) =>
+ backgroundColor != oldDelegate.backgroundColor ||
+ gradient != oldDelegate.gradient ||
+ topInset != oldDelegate.topInset ||
+ screenHeight != oldDelegate.screenHeight;
+}
+
SliverGridDelegate libraryGridDelegateForWidth(
double width, {
required bool desktopWorkspace,
@@ -2392,7 +2451,6 @@ class LibraryScreenState extends State<LibraryScreen>
final desktopWorkspace = isDesktopWorkspace(context);
_revealDriver.setEnabled(!desktopWorkspace);
final scaffoldBg = Theme.of(context).scaffoldBackgroundColor;
- final lowerFade = Color.lerp(cs.surface, scaffoldBg, 0.55) ?? scaffoldBg;
// Watch LibraryProvider so this screen rebuilds when the active library
// or its data changes; the actual lib object is consumed inside
// _buildHeaderSliver via context.watch.
@@ -2419,27 +2477,11 @@ class LibraryScreenState extends State<LibraryScreen>
body: Stack(
children: [
if (!flatNotifier.value)
- OverflowBox(
- maxHeight: MediaQuery.of(context).size.height,
- alignment: Alignment.topCenter,
- child: SizedBox(
- height: MediaQuery.of(context).size.height,
- width: double.infinity,
+ Positioned.fill(
+ child: RepaintBoundary(
child: DecoratedBox(
decoration: BoxDecoration(
- gradient: LinearGradient(
- begin: Alignment.topCenter,
- end: Alignment.bottomCenter,
- stops: const [0.0, 0.22, 0.72, 1.0],
- colors: [
- cs.primary.withValues(
- alpha: gradientIntensityNotifier.value,
- ),
- cs.surface,
- lowerFade,
- scaffoldBg,
- ],
- ),
+ gradient: _libraryBackgroundGradient(cs, scaffoldBg),
),
),
),
@@ -2571,7 +2613,6 @@ class LibraryScreenState extends State<LibraryScreen>
final tt = Theme.of(context).textTheme;
final l = AppLocalizations.of(context)!;
final scaffoldBg = Theme.of(context).scaffoldBackgroundColor;
- final lowerFade = Color.lerp(cs.surface, scaffoldBg, 0.55) ?? scaffoldBg;
final lib = context.watch<LibraryProvider>();
final allLibraries = lib.libraries;
final hasMultipleLibraries = allLibraries.length > 1;
@@ -2581,36 +2622,12 @@ class LibraryScreenState extends State<LibraryScreen>
final screenH = MediaQuery.of(context).size.height;
final headerBackground = flatNotifier.value
? ColoredBox(color: scaffoldBg)
- : ClipRect(
- child: OverflowBox(
- maxHeight: screenH,
- minHeight: 0,
- alignment: Alignment.topCenter,
- child: Transform.translate(
- offset: Offset(0, -topInset),
- child: SizedBox(
- height: screenH,
- width: double.infinity,
- child: DecoratedBox(
- decoration: BoxDecoration(
- color: scaffoldBg,
- gradient: LinearGradient(
- begin: Alignment.topCenter,
- end: Alignment.bottomCenter,
- stops: const [0.0, 0.22, 0.72, 1.0],
- colors: [
- cs.primary.withValues(
- alpha: gradientIntensityNotifier.value,
- ),
- cs.surface,
- lowerFade,
- scaffoldBg,
- ],
- ),
- ),
- ),
- ),
- ),
+ : CustomPaint(
+ painter: _LibraryHeaderGradientPainter(
+ backgroundColor: scaffoldBg,
+ gradient: _libraryBackgroundGradient(cs, scaffoldBg),
+ topInset: topInset,
+ screenHeight: screenH,
),
);
final desktop = isDesktopWorkspace(context);
@@ -2629,7 +2646,7 @@ class LibraryScreenState extends State<LibraryScreen>
_seriesFilter != SeriesFilter.none)
? 196
: 184),
- backgroundColor: scaffoldBg,
+ backgroundColor: Colors.transparent,
surfaceTintColor: Colors.transparent,
elevation: 0,
scrolledUnderElevation: 0,
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index 01421d19..fa9528b6 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -49,6 +49,7 @@ import '../widgets/adaptive_modal.dart';
import '../widgets/rmab_config_sheet.dart';
import '../widgets/server_connection_editor.dart';
import '../widgets/server_admin_status_badges.dart';
+import '../widgets/desktop_wheel_scroll_region.dart';
import '../l10n/app_localizations.dart';
class _SettingsSectionDestination {
@@ -85,6 +86,7 @@ class _SettingsAdaptiveFrame extends StatelessWidget {
final String? selectedSection;
final List<_SettingsSectionDestination> destinations;
final ValueChanged<String> onSectionSelected;
+ final ScrollController scrollController;
final Widget child;
const _SettingsAdaptiveFrame({
@@ -92,6 +94,7 @@ class _SettingsAdaptiveFrame extends StatelessWidget {
required this.selectedSection,
required this.destinations,
required this.onSectionSelected,
+ required this.scrollController,
required this.child,
});
@@ -178,10 +181,12 @@ class _SettingsAdaptiveFrame extends StatelessWidget {
thickness: 1,
color: cs.outlineVariant.withValues(alpha: 0.35),
),
- Expanded(child: Align(
+ Expanded(child: DesktopWheelScrollRegion(
+ controller: scrollController,
+ child: Align(
alignment: Alignment.topCenter, child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 880),
- child: SizedBox.expand(child: child),
+ child: SizedBox.expand(child: child),),
),
),),
],
@@ -1587,8 +1592,10 @@ class SettingsScreenState extends State<SettingsScreen> {
child: InkWell(
borderRadius: BorderRadius.circular(14),
onTap: () async {
+ final taskTracker =
+ AppShell.serverTaskTrackerOf(context);
await Navigator.push(context, MaterialPageRoute(
- builder: (_) => const AdminScreen(),
+ builder: (_) => AdminScreen(taskTracker: taskTracker),
),);
_loadAdminIssueCount();
},
@@ -2113,7 +2120,7 @@ class SettingsScreenState extends State<SettingsScreen> {
PlayerSettings.setFullScreenPlayer(v);
} : null,
),
- const Divider(height: 1, indent: 16, endIndent: 16),
+ const Divider(height: 1, indent: 16, endIndent: 16,),
],
SwitchListTile(
title: Text(l.coverPlayPause),
@@ -2158,7 +2165,7 @@ class SettingsScreenState extends State<SettingsScreen> {
),),
],),
),
- const Divider(height: 1, indent: 16, endIndent: 16),
+ const Divider(height: 1, indent: 16, endIndent: 16,),
],
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 14,),
@@ -2224,11 +2231,11 @@ class SettingsScreenState extends State<SettingsScreen> {
),
value: _notifChapterProgress,
onChanged: _loaded ? (v) {
- setState(() => _notifChapterProgress = v);
- PlayerSettings.setNotificationChapterProgress(v);
+ setState(() => _notifChapterProgress = v,);
+ PlayerSettings.setNotificationChapterProgress(v,);
} : null,
),
- const Divider(height: 1, indent: 16, endIndent: 16),
+ const Divider(height: 1, indent: 16, endIndent: 16,),
],
ValueListenableBuilder<bool>(
valueListenable: classicWordingNotifier,
@@ -2255,7 +2262,7 @@ class SettingsScreenState extends State<SettingsScreen> {
onChanged: (_loaded && !_podcastTabEnabled) ? (v) async {
setState(() => _mergeAbsorbingLibraries = v,);
await PlayerSettings.setMergeAbsorbingLibraries(v,);
- unawaited(lib.syncQueueAutoDownloads());
+ unawaited(lib.syncQueueAutoDownloads(),);
} : null,
);
},
@@ -2398,7 +2405,7 @@ class SettingsScreenState extends State<SettingsScreen> {
onChanged: _loaded ? (v) async {
setState(() => _queueAutoDownload = v,);
await PlayerSettings.setQueueAutoDownload(v,);
- unawaited(lib.syncQueueAutoDownloads());
+ unawaited(lib.syncQueueAutoDownloads(),);
} : null,
dense: true,
contentPadding: EdgeInsets.zero,
@@ -2870,11 +2877,11 @@ class SettingsScreenState extends State<SettingsScreen> {
),),
value: _notifChapterProgress,
onChanged: _loaded ? (v) {
- setState(() => _notifChapterProgress = v);
+ setState(() => _notifChapterProgress = v,);
PlayerSettings.setNotificationChapterProgress(v,);
} : null,
),
- const Divider(height: 1, indent: 16, endIndent: 16),
+ const Divider(height: 1, indent: 16, endIndent: 16,),
// Cross-platform: drops the seek action so the scrubber in the
// notification / lockscreen / car can't be dragged.
SwitchListTile(
@@ -2918,7 +2925,7 @@ class SettingsScreenState extends State<SettingsScreen> {
),),
value: _notifSpeedBookmark,
onChanged: _loaded ? (v) {
- setState(() => _notifSpeedBookmark = v);
+ setState(() => _notifSpeedBookmark = v,);
PlayerSettings.setMediaControlsSpeedBookmark(v,);
} : null,
),
@@ -3401,7 +3408,7 @@ class SettingsScreenState extends State<SettingsScreen> {
setState(() => _rollingDownloadCount = v.first,);
await PlayerSettings.setRollingDownloadCount(v.first,);
if (_queueAutoDownload) {
- unawaited(lib.syncQueueAutoDownloads());
+ unawaited(lib.syncQueueAutoDownloads(),);
}
},
),),
@@ -4026,14 +4033,14 @@ class SettingsScreenState extends State<SettingsScreen> {
const Divider(height: 1, indent: 16, endIndent: 16,),
ListTile(
leading: Icon(Icons.check_circle_rounded, color: Colors.greenAccent.shade400,),
- title: Text(l.localServerOnConnectedSubtitle),
+ title: Text(l.localServerOnConnectedSubtitle,),
subtitle: Text(_localServerUrl,
style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant,
),),
),
],
],
- const Divider(height: 1, indent: 16, endIndent: 16),
+ const Divider(height: 1, indent: 16, endIndent: 16,),
],
if (!AppPlatform.isWeb)
SwitchListTile(
@@ -4096,7 +4103,7 @@ class SettingsScreenState extends State<SettingsScreen> {
),
],
if (!AppPlatform.isWeb || _isGithubBuild)
- const Divider(height: 1, indent: 16, endIndent: 16),
+ const Divider(height: 1, indent: 16, endIndent: 16,),
ListTile(
leading: Icon(Icons.menu_book_rounded, color: cs.primary,),
title: Text(l.adminRmab),
@@ -4288,6 +4295,7 @@ class SettingsScreenState extends State<SettingsScreen> {
desktopMode: isDesktopSettings,
selectedSection: expandedSection,
destinations: destinations,
+ scrollController: _settingsScrollController,
onSectionSelected: (section) {
setState(() => _expandedSection = section);
WidgetsBinding.instance.addPostFrameCallback((_) {
diff --git a/lib/services/server_task_tracker.dart b/lib/services/server_task_tracker.dart
index 0f54bc9b..23d78365 100644
--- a/lib/services/server_task_tracker.dart
+++ b/lib/services/server_task_tracker.dart
@@ -109,6 +109,8 @@ class ServerTaskTracker extends ChangeNotifier {
final Set<String> _finishedTaskIds = {};
var _eventRevision = 0;
var _disposed = false;
+ Future<void>? _refreshInFlight;
+ ApiService? _refreshApi;
ServerTaskTracker({SocketService? socketService})
: _socketService = socketService ?? SocketService() {
@@ -142,6 +144,26 @@ class ServerTaskTracker extends ChangeNotifier {
}
Future<void> refresh(ApiService api) async {
+ final activeRefresh = _refreshInFlight;
+ if (activeRefresh != null) {
+ if (identical(api, _refreshApi)) return activeRefresh;
+ await activeRefresh;
+ return refresh(api);
+ }
+
+ late final Future<void> operation;
+ operation = _performRefresh(api).whenComplete(() {
+ if (identical(_refreshInFlight, operation)) {
+ _refreshInFlight = null;
+ _refreshApi = null;
+ }
+ });
+ _refreshApi = api;
+ _refreshInFlight = operation;
+ return operation;
+ }
+
+ Future<void> _performRefresh(ApiService api) async {
if (_disposed) return;
final revisionBeforeRequest = _eventRevision;
final rawTasks = await api.getServerTasks();
diff --git a/lib/widgets/absorbing_card.dart b/lib/widgets/absorbing_card.dart
index 181271ba..4285edf6 100644
--- a/lib/widgets/absorbing_card.dart
+++ b/lib/widgets/absorbing_card.dart
@@ -26,6 +26,9 @@ import 'stable_cached_network_image.dart';
enum AbsorbingCardPresentation { card, desktop }
+const double kAbsorbingDesktopRowLayoutWidth = 760;
+const double kAbsorbingSpaciousDesktopLayoutWidth = 1280;
+
@immutable
class AbsorbingChapterData {
final String itemKey;
@@ -55,12 +58,14 @@ class AbsorbingCard extends StatefulWidget {
final Map<String, dynamic> item;
final AudioPlayerService player;
final AbsorbingCardPresentation presentation;
+ final bool? spaciousDesktopLayout;
final ValueChanged<AbsorbingChapterData>? onChapterDataChanged;
const AbsorbingCard({
super.key,
required this.item,
required this.player,
this.presentation = AbsorbingCardPresentation.card,
+ this.spaciousDesktopLayout,
this.onChapterDataChanged,
});
@@ -857,7 +862,10 @@ 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;
+ final spaciousDesktop = desktopPresentation &&
+ (widget.spaciousDesktopLayout ??
+ cardConstraints.maxWidth >=
+ kAbsorbingSpaciousDesktopLayoutWidth);
// 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;
@@ -1290,7 +1298,8 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
);
}
- if (cardConstraints.maxWidth >= 760) {
+ if (cardConstraints.maxWidth >=
+ kAbsorbingDesktopRowLayoutWidth) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Row(
diff --git a/lib/widgets/adaptive_modal.dart b/lib/widgets/adaptive_modal.dart
index 3ed7da28..ee1723f4 100644
--- a/lib/widgets/adaptive_modal.dart
+++ b/lib/widgets/adaptive_modal.dart
@@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import '../utils/desktop_workspace.dart';
+import 'desktop_wheel_scroll_region.dart';
enum DialogWidthClass {
action(480),
@@ -212,28 +213,41 @@ Future<T?> showDesktopModalDialog<T>({
context: context,
useRootNavigator: true,
barrierDismissible: isDismissible,
- builder: (dialogContext) => Dialog(
- backgroundColor: bg,
- clipBehavior: Clip.antiAlias,
- insetPadding: const EdgeInsets.all(24),
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(20),
- side: BorderSide(color: cs.outlineVariant.withValues(alpha: 0.4)),
- ),
- child: ConstrainedBox(
- constraints: BoxConstraints(
- maxHeight:
- MediaQuery.sizeOf(dialogContext).height * maxHeightFraction,
- ),
- child: SizedBox(
- width: maxWidth,
- child: _DesktopDialogBody(
- builder: builder,
- closeButton: closeButton,
- onRouteCaptured: onRouteCaptured,
- onRouteDisposed: onRouteDisposed,
+ builder: (dialogContext) => DesktopWheelScrollRegion(
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: isDismissible
+ ? () => Navigator.of(dialogContext).maybePop()
+ : null,
),
- ),
+ Dialog(
+ backgroundColor: bg,
+ clipBehavior: Clip.antiAlias,
+ insetPadding: const EdgeInsets.all(24),
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(20),
+ side: BorderSide(color: cs.outlineVariant.withValues(alpha: 0.4)),
+ ),
+ child: ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight:
+ MediaQuery.sizeOf(dialogContext).height * maxHeightFraction,
+ ),
+ child: SizedBox(
+ width: maxWidth,
+ child: _DesktopDialogBody(
+ builder: builder,
+ closeButton: closeButton,
+ onRouteCaptured: onRouteCaptured,
+ onRouteDisposed: onRouteDisposed,
+ ),
+ ),
+ ),
+ ),
+ ],
),
),
);
diff --git a/lib/widgets/admin_adaptive_frame.dart b/lib/widgets/admin_adaptive_frame.dart
index 1be1aaab..dc3c8bd6 100644
--- a/lib/widgets/admin_adaptive_frame.dart
+++ b/lib/widgets/admin_adaptive_frame.dart
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
+import 'desktop_wheel_scroll_region.dart';
class AdminSectionDestination {
final String id;
@@ -123,16 +124,21 @@ class AdminAdaptiveFrame extends StatelessWidget {
),
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: DesktopWheelScrollRegion(
+ 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)),
),
- child: ClipRect(child: SizedBox.expand(child: child)),
),
),
),
diff --git a/lib/widgets/desktop_page_body.dart b/lib/widgets/desktop_page_body.dart
index 9597393b..ace9ebf3 100644
--- a/lib/widgets/desktop_page_body.dart
+++ b/lib/widgets/desktop_page_body.dart
@@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import '../utils/desktop_workspace.dart';
+import 'desktop_wheel_scroll_region.dart';
/// Centers a pushed page's content in a readable column on the desktop
/// workspace; returns the child untouched everywhere else.
@@ -12,10 +13,12 @@ class DesktopPageBody extends StatelessWidget {
@override
Widget build(BuildContext context) {
if (!isDesktopWorkspace(context)) return child;
- return Center(
- child: ConstrainedBox(
- constraints: BoxConstraints(maxWidth: maxWidth),
- child: child,
+ return DesktopWheelScrollRegion(
+ child: Center(
+ child: ConstrainedBox(
+ constraints: BoxConstraints(maxWidth: maxWidth),
+ child: child,
+ ),
),
);
}
diff --git a/lib/widgets/desktop_wheel_scroll_region.dart b/lib/widgets/desktop_wheel_scroll_region.dart
new file mode 100644
index 00000000..bc294afc
--- /dev/null
+++ b/lib/widgets/desktop_wheel_scroll_region.dart
@@ -0,0 +1,173 @@
+import 'package:flutter/gestures.dart';
+import 'package:flutter/material.dart';
+
+/// Lets a desktop pane's empty gutters scroll its primary content.
+class DesktopWheelScrollRegion extends StatefulWidget {
+ const DesktopWheelScrollRegion({
+ super.key,
+ required this.child,
+ this.controller,
+ });
+
+ final Widget child;
+ final ScrollController? controller;
+
+ @override
+ State<DesktopWheelScrollRegion> createState() =>
+ _DesktopWheelScrollRegionState();
+}
+
+class _DesktopWheelScrollRegionState extends State<DesktopWheelScrollRegion> {
+ final List<_DiscoveredScrollable> _discoveredScrollables = [];
+
+ _WheelTarget? _targetFor(PointerScrollEvent event) {
+ final controller = widget.controller;
+ if (controller != null) {
+ if (!controller.hasClients || controller.positions.length != 1) {
+ return null;
+ }
+ return _targetForPosition(controller.position, event);
+ }
+
+ _discoveredScrollables.removeWhere(
+ (candidate) => !candidate.scrollable.mounted,
+ );
+ _WheelTarget? bestTarget;
+ var bestDepth = 1 << 20;
+ var bestVisibleArea = -1.0;
+ final preferredAxis =
+ event.scrollDelta.dy.abs() >= event.scrollDelta.dx.abs()
+ ? Axis.vertical
+ : Axis.horizontal;
+ for (final candidate in _discoveredScrollables) {
+ final scrollable = candidate.scrollable;
+ if (!_isActive(scrollable)) continue;
+ final position = scrollable.position;
+ if (axisDirectionToAxis(position.axisDirection) != preferredAxis) {
+ continue;
+ }
+ final target = _targetForPosition(position, event);
+ if (target == null) continue;
+ final visibleArea = _visibleArea(scrollable);
+ if (visibleArea <= 0) continue;
+ if (candidate.depth < bestDepth ||
+ (candidate.depth == bestDepth && visibleArea > bestVisibleArea)) {
+ bestTarget = target;
+ bestDepth = candidate.depth;
+ bestVisibleArea = visibleArea;
+ }
+ }
+ return bestTarget;
+ }
+
+ double _visibleArea(ScrollableState scrollable) {
+ final regionObject = context.findRenderObject();
+ final scrollObject = scrollable.context.findRenderObject();
+ if (regionObject is! RenderBox ||
+ scrollObject is! RenderBox ||
+ !regionObject.attached ||
+ !scrollObject.attached) {
+ return 0;
+ }
+ final scrollBounds = MatrixUtils.transformRect(
+ scrollObject.getTransformTo(regionObject),
+ scrollObject.paintBounds,
+ );
+ final visibleBounds = scrollBounds.intersect(
+ Offset.zero & regionObject.size,
+ );
+ if (visibleBounds.isEmpty) return 0;
+ return visibleBounds.width * visibleBounds.height;
+ }
+
+ _WheelTarget? _targetForPosition(
+ ScrollPosition position,
+ PointerScrollEvent event,
+ ) {
+ if (!position.hasContentDimensions ||
+ !position.physics.shouldAcceptUserOffset(position)) {
+ return null;
+ }
+ final axis = axisDirectionToAxis(position.axisDirection);
+ var delta = axis == Axis.vertical
+ ? event.scrollDelta.dy
+ : event.scrollDelta.dx;
+ if (axisDirectionIsReversed(position.axisDirection)) delta = -delta;
+ final target = (position.pixels + delta).clamp(
+ position.minScrollExtent,
+ position.maxScrollExtent,
+ );
+ if (delta == 0 || target == position.pixels) return null;
+ return _WheelTarget(position, delta);
+ }
+
+ bool _isActive(ScrollableState scrollable) {
+ final renderObject = scrollable.context.findRenderObject();
+ if (!(renderObject?.attached ?? false)) return false;
+ final route = ModalRoute.of(scrollable.context);
+ return (route == null || route.isCurrent) &&
+ TickerMode.of(scrollable.context);
+ }
+
+ void _rememberPosition(BuildContext? notificationContext, int depth) {
+ if (notificationContext == null) return;
+ final scrollable = Scrollable.maybeOf(notificationContext);
+ if (scrollable == null) return;
+ _discoveredScrollables
+ ..removeWhere((candidate) => candidate.scrollable == scrollable)
+ ..insert(0, _DiscoveredScrollable(scrollable, depth));
+ }
+
+ bool _handleMetricsNotification(ScrollMetricsNotification notification) {
+ _rememberPosition(notification.context, notification.depth);
+ return false;
+ }
+
+ bool _handleScrollNotification(ScrollNotification notification) {
+ _rememberPosition(notification.context, notification.depth);
+ return false;
+ }
+
+ void _handlePointerSignal(PointerSignalEvent event) {
+ if (event is! PointerScrollEvent) return;
+ final target = _targetFor(event);
+ if (target == null) return;
+
+ GestureBinding.instance.pointerSignalResolver.register(event, (
+ resolvedEvent,
+ ) {
+ if (resolvedEvent is! PointerScrollEvent) return;
+ target.position.pointerScroll(target.delta);
+ resolvedEvent.respond(allowPlatformDefault: false);
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return Listener(
+ behavior: HitTestBehavior.opaque,
+ onPointerSignal: _handlePointerSignal,
+ child: NotificationListener<ScrollMetricsNotification>(
+ onNotification: _handleMetricsNotification,
+ child: NotificationListener<ScrollNotification>(
+ onNotification: _handleScrollNotification,
+ child: widget.child,
+ ),
+ ),
+ );
+ }
+}
+
+class _DiscoveredScrollable {
+ const _DiscoveredScrollable(this.scrollable, this.depth);
+
+ final ScrollableState scrollable;
+ final int depth;
+}
+
+class _WheelTarget {
+ const _WheelTarget(this.position, this.delta);
+
+ final ScrollPosition position;
+ final double delta;
+}