feat: Android TV support (#503)

Co-authored-by: PartyDonut <PartyDonut@users.noreply.github.com>
This commit is contained in:
PartyDonut 2025-09-28 21:07:49 +02:00 committed by GitHub
parent 7ab8c015b9
commit c299492d6d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
168 changed files with 12019 additions and 3073 deletions

View file

@ -0,0 +1,42 @@
import 'package:flutter/material.dart';
class MediaQueryScaler extends StatelessWidget {
final Widget child;
final bool enable;
final double scale;
const MediaQueryScaler({
required this.child,
required this.enable,
this.scale = 1.35,
super.key,
});
@override
Widget build(BuildContext context) {
if (!enable) return child;
final mediaQuery = MediaQuery.of(context);
final screenSize = MediaQuery.sizeOf(context) * scale;
final scaledMedia = mediaQuery.copyWith(
navigationMode: NavigationMode.directional,
size: screenSize,
padding: mediaQuery.padding * scale,
viewInsets: mediaQuery.viewInsets * scale,
viewPadding: mediaQuery.viewPadding * scale,
devicePixelRatio: mediaQuery.devicePixelRatio * scale,
);
return FittedBox(
alignment: Alignment.center,
child: SizedBox(
width: screenSize.width,
height: screenSize.height,
child: MediaQuery(
data: scaledMedia,
child: child,
),
),
);
}
}

View file

@ -32,8 +32,11 @@ class AdaptiveFab {
padding: const EdgeInsets.symmetric(horizontal: 6),
child: FilledButton.tonal(
onPressed: onPressed,
style: FilledButton.styleFrom(
padding: const EdgeInsets.all(16),
),
child: Row(
spacing: 24,
spacing: 16,
children: [
child,
Flexible(child: Text(title)),

View file

@ -31,7 +31,7 @@ class _BackgroundImageState extends ConsumerState<BackgroundImage> {
@override
void didUpdateWidget(covariant BackgroundImage oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.items.length != widget.items.length || oldWidget.images.length != widget.images.length) {
if (!oldWidget.items.equals(widget.items)) {
updateItems();
}
}

View file

@ -81,10 +81,12 @@ class DestinationModel {
);
}
NavigationButton toNavigationButton(bool selected, bool horizontal, bool expanded, {Widget? customIcon}) {
NavigationButton toNavigationButton(bool selected, bool horizontal, bool expanded,
{bool navFocusNode = false, Widget? customIcon}) {
return NavigationButton(
label: label,
selected: selected,
navFocusNode: navFocusNode,
onPressed: action,
horizontal: horizontal,
expanded: expanded,

View file

@ -25,6 +25,7 @@ double floatingPlayerHeight(BuildContext context) => switch (AdaptiveLayout.view
ViewSize.phone => 75,
ViewSize.tablet => 85,
ViewSize.desktop => 95,
ViewSize.television => 105,
};
class FloatingPlayerBar extends ConsumerStatefulWidget {

View file

@ -64,25 +64,28 @@ class _NavigationBodyState extends ConsumerState<NavigationBody> {
child: widget.child,
);
return switch (AdaptiveLayout.layoutOf(context)) {
ViewSize.phone => paddedChild(),
ViewSize.tablet => hasOverlay
? SideNavigationBar(
currentIndex: widget.currentIndex,
destinations: widget.destinations,
currentLocation: widget.currentLocation,
child: paddedChild(),
scaffoldKey: widget.drawerKey,
)
: paddedChild(),
ViewSize.desktop => SideNavigationBar(
currentIndex: widget.currentIndex,
destinations: widget.destinations,
currentLocation: widget.currentLocation,
child: paddedChild(),
scaffoldKey: widget.drawerKey,
)
};
return FocusTraversalGroup(
policy: GlobalFallbackTraversalPolicy(fallbackNode: navBarNode),
child: switch (AdaptiveLayout.layoutOf(context)) {
ViewSize.phone => paddedChild(),
ViewSize.tablet => hasOverlay
? SideNavigationBar(
currentIndex: widget.currentIndex,
destinations: widget.destinations,
currentLocation: widget.currentLocation,
child: paddedChild(),
scaffoldKey: widget.drawerKey,
)
: paddedChild(),
ViewSize.desktop || ViewSize.television => SideNavigationBar(
currentIndex: widget.currentIndex,
destinations: widget.destinations,
currentLocation: widget.currentLocation,
child: paddedChild(),
scaffoldKey: widget.drawerKey,
)
},
);
}
MediaQueryData semiNestedPadding(BuildContext context, bool hasOverlay) {
@ -92,3 +95,28 @@ class _NavigationBodyState extends ConsumerState<NavigationBody> {
);
}
}
FocusNode? lastMainFocus;
class GlobalFallbackTraversalPolicy extends ReadingOrderTraversalPolicy {
final FocusNode fallbackNode;
GlobalFallbackTraversalPolicy({required this.fallbackNode}) : super();
@override
bool inDirection(FocusNode currentNode, TraversalDirection direction) {
lastMainFocus = null;
final handled = super.inDirection(currentNode, direction);
if (!handled && direction == TraversalDirection.left) {
lastMainFocus = currentNode;
if (fallbackNode.canRequestFocus && fallbackNode.context?.mounted == true) {
final cb = FocusTraversalPolicy.defaultTraversalRequestFocusCallback;
cb(fallbackNode);
return true;
}
}
return handled;
}
}

View file

@ -3,12 +3,14 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:fladder/util/localization_helper.dart';
import 'package:fladder/widgets/navigation_scaffold/components/side_navigation_bar.dart';
import 'package:fladder/widgets/shared/item_actions.dart';
class NavigationButton extends ConsumerStatefulWidget {
final String? label;
final Widget selectedIcon;
final Widget icon;
final bool navFocusNode;
final bool horizontal;
final bool expanded;
final Function()? onPressed;
@ -21,6 +23,7 @@ class NavigationButton extends ConsumerStatefulWidget {
required this.label,
required this.selectedIcon,
required this.icon,
this.navFocusNode = false,
this.horizontal = false,
this.expanded = false,
this.onPressed,
@ -48,6 +51,7 @@ class _NavigationButtonState extends ConsumerState<NavigationButton> {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 6),
child: ElevatedButton(
focusNode: widget.navFocusNode ? navBarNode : null,
onHover: (value) => setState(() => showPopupButton = value),
style: ButtonStyle(
elevation: const WidgetStatePropertyAll(0),
@ -64,95 +68,97 @@ class _NavigationButtonState extends ConsumerState<NavigationButton> {
})),
onPressed: widget.onPressed,
onLongPress: widget.onLongPress,
child: widget.horizontal
? Padding(
padding: widget.customIcon != null
? EdgeInsetsGeometry.zero
: const EdgeInsets.symmetric(vertical: 6, horizontal: 8),
child: SizedBox(
height: widget.customIcon != null ? 60 : 35,
child: Row(
spacing: 4,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
AnimatedContainer(
duration: const Duration(milliseconds: 250),
height: widget.selected ? 16 : 0,
margin: const EdgeInsets.only(top: 1.5),
width: 6,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: Theme.of(context)
.colorScheme
.primary
.withValues(alpha: widget.selected && !widget.expanded ? 1 : 0),
),
),
widget.customIcon ??
AnimatedSwitcher(
duration: widget.duration,
child: widget.selected ? widget.selectedIcon : widget.icon,
),
const SizedBox(width: 6),
if (widget.horizontal && widget.expanded) ...[
if (widget.label != null)
Expanded(
child: ConstrainedBox(
constraints: const BoxConstraints(minWidth: 80),
child: Text(
widget.label!,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
),
if (widget.trailing.isNotEmpty)
AnimatedOpacity(
duration: const Duration(milliseconds: 125),
opacity: showPopupButton ? 1 : 0,
child: PopupMenuButton(
tooltip: context.localized.options,
iconColor: foreGroundColor,
iconSize: 18,
itemBuilder: (context) => widget.trailing.popupMenuItems(useIcons: true),
),
)
],
],
),
),
)
: Padding(
padding: widget.customIcon != null ? EdgeInsetsGeometry.zero : const EdgeInsets.all(8),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
spacing: 8,
child: ExcludeFocusTraversal(
child: widget.horizontal
? Padding(
padding: widget.customIcon != null
? EdgeInsetsGeometry.zero
: const EdgeInsets.symmetric(vertical: 6, horizontal: 8),
child: SizedBox(
height: widget.customIcon != null ? 60 : 35,
child: Row(
spacing: 4,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
AnimatedContainer(
duration: const Duration(milliseconds: 250),
height: widget.selected ? 16 : 0,
margin: const EdgeInsets.only(top: 1.5),
width: 6,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: Theme.of(context)
.colorScheme
.primary
.withValues(alpha: widget.selected && !widget.expanded ? 1 : 0),
),
),
widget.customIcon ??
AnimatedSwitcher(
duration: widget.duration,
child: widget.selected ? widget.selectedIcon : widget.icon,
),
if (widget.label != null && widget.horizontal && widget.expanded)
Flexible(child: Text(widget.label!))
const SizedBox(width: 6),
if (widget.horizontal && widget.expanded) ...[
if (widget.label != null)
Expanded(
child: ConstrainedBox(
constraints: const BoxConstraints(minWidth: 80),
child: Text(
widget.label!,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
),
if (widget.trailing.isNotEmpty)
AnimatedOpacity(
duration: const Duration(milliseconds: 125),
opacity: showPopupButton ? 1 : 0,
child: PopupMenuButton(
tooltip: context.localized.options,
iconColor: foreGroundColor,
iconSize: 18,
itemBuilder: (context) => widget.trailing.popupMenuItems(useIcons: true),
),
)
],
],
),
AnimatedContainer(
duration: const Duration(milliseconds: 250),
margin: EdgeInsets.only(top: widget.selected ? 4 : 0),
height: widget.selected ? 6 : 0,
width: widget.selected ? 14 : 0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: Theme.of(context).colorScheme.primary.withValues(alpha: widget.selected ? 1 : 0),
),
)
: Padding(
padding: widget.customIcon != null ? EdgeInsetsGeometry.zero : const EdgeInsets.all(8),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
spacing: 8,
children: [
widget.customIcon ??
AnimatedSwitcher(
duration: widget.duration,
child: widget.selected ? widget.selectedIcon : widget.icon,
),
if (widget.label != null && widget.horizontal && widget.expanded)
Flexible(child: Text(widget.label!))
],
),
),
],
AnimatedContainer(
duration: const Duration(milliseconds: 250),
margin: EdgeInsets.only(top: widget.selected ? 4 : 0),
height: widget.selected ? 6 : 0,
width: widget.selected ? 14 : 0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: Theme.of(context).colorScheme.primary.withValues(alpha: widget.selected ? 1 : 0),
),
),
],
),
),
),
),
),
);
}

View file

@ -20,12 +20,15 @@ import 'package:fladder/util/fladder_image.dart';
import 'package:fladder/util/localization_helper.dart';
import 'package:fladder/widgets/navigation_scaffold/components/adaptive_fab.dart';
import 'package:fladder/widgets/navigation_scaffold/components/destination_model.dart';
import 'package:fladder/widgets/navigation_scaffold/components/navigation_body.dart';
import 'package:fladder/widgets/navigation_scaffold/components/navigation_button.dart';
import 'package:fladder/widgets/navigation_scaffold/components/settings_user_icon.dart';
import 'package:fladder/widgets/shared/custom_tooltip.dart';
import 'package:fladder/widgets/shared/item_actions.dart';
import 'package:fladder/widgets/shared/modal_bottom_sheet.dart';
final navBarNode = FocusNode();
class SideNavigationBar extends ConsumerStatefulWidget {
final int currentIndex;
final List<DestinationModel> destinations;
@ -53,7 +56,7 @@ class _SideNavigationBarState extends ConsumerState<SideNavigationBar> {
final views = ref.watch(viewsProvider.select((value) => value.views));
final usePostersForLibrary = ref.watch(clientSettingsProvider.select((value) => value.usePosterForLibrary));
final expandedWidth = 250.0;
final expandedWidth = 200.0;
final padding = MediaQuery.paddingOf(context);
final collapsedWidth = 90 + padding.left;
@ -64,6 +67,9 @@ class _SideNavigationBarState extends ConsumerState<SideNavigationBar> {
final fullScreenChildRoute = fullScreenRoutes.contains(context.router.current.name);
final hasOverlay = AdaptiveLayout.layoutModeOf(context) == LayoutMode.dual ||
homeRoutes.any((element) => element.name.contains(context.router.current.name));
return Stack(
children: [
AdaptiveLayoutBuilder(
@ -73,15 +79,16 @@ class _SideNavigationBarState extends ConsumerState<SideNavigationBar> {
),
child: (context) => widget.child,
),
IgnorePointer(
ignoring: fullScreenChildRoute,
child: AnimatedOpacity(
duration: const Duration(milliseconds: 250),
opacity: !fullScreenChildRoute ? 1 : 0,
child: Container(
color: Theme.of(context).colorScheme.surface.withValues(alpha: shouldExpand ? 0.95 : 0.85),
width: shouldExpand ? expandedWidth : collapsedWidth,
child: MouseRegion(
FocusTraversalGroup(
policy: _RailTraversalPolicy(),
child: IgnorePointer(
ignoring: !hasOverlay || fullScreenChildRoute,
child: AnimatedOpacity(
duration: const Duration(milliseconds: 250),
opacity: !fullScreenChildRoute ? 1 : 0,
child: Container(
color: Theme.of(context).colorScheme.surface.withValues(alpha: shouldExpand ? 0.95 : 0.85),
width: shouldExpand ? expandedWidth : collapsedWidth,
child: Padding(
key: const Key('navigation_rail'),
padding: padding.copyWith(right: 0, top: isDesktop ? padding.top : null),
@ -111,9 +118,12 @@ class _SideNavigationBarState extends ConsumerState<SideNavigationBar> {
),
),
if (largeBar) ...[
AnimatedFadeSize(
duration: const Duration(milliseconds: 250),
child: shouldExpand ? actionButton(context).extended : actionButton(context).normal,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 4).copyWith(bottom: expandedSideBar ? 10 : 0),
child: AnimatedFadeSize(
duration: const Duration(milliseconds: 250),
child: shouldExpand ? actionButton(context).extended : actionButton(context).normal,
),
),
],
Expanded(
@ -137,6 +147,7 @@ class _SideNavigationBarState extends ConsumerState<SideNavigationBar> {
child: destination.toNavigationButton(
widget.currentIndex == index,
true,
navFocusNode: index == 0,
shouldExpand,
),
),
@ -204,6 +215,7 @@ class _SideNavigationBarState extends ConsumerState<SideNavigationBar> {
: view.collectionType.iconOutlined,
),
),
decodeHeight: 64,
),
),
)
@ -273,6 +285,7 @@ class _SideNavigationBarState extends ConsumerState<SideNavigationBar> {
e.collectionType.iconOutlined,
),
),
decodeHeight: 64,
),
),
),
@ -299,7 +312,7 @@ class _SideNavigationBarState extends ConsumerState<SideNavigationBar> {
selectedIcon: const Icon(IconsaxPlusBold.setting_3),
horizontal: true,
expanded: shouldExpand,
icon: const SettingsUserIcon(),
icon: const ExcludeFocusTraversal(child: SettingsUserIcon()),
onPressed: () {
if (AdaptiveLayout.layoutModeOf(context) == LayoutMode.single) {
context.router.push(const SettingsRoute());
@ -332,3 +345,64 @@ class _SideNavigationBarState extends ConsumerState<SideNavigationBar> {
);
}
}
class _RailTraversalPolicy extends ReadingOrderTraversalPolicy {
_RailTraversalPolicy();
@override
bool inDirection(FocusNode currentNode, TraversalDirection direction) {
if (direction == TraversalDirection.left) {
return false;
}
if (direction == TraversalDirection.right) {
if (lastMainFocus != null && _isLaidOut(lastMainFocus!)) {
lastMainFocus!.requestFocus();
return true;
} else {
return super.inDirection(currentNode, direction);
}
}
if (direction == TraversalDirection.up || direction == TraversalDirection.down) {
final scope = currentNode.enclosingScope;
if (scope == null) {
return false;
}
final candidates = scope.traversalDescendants
.where((n) => n.canRequestFocus && FocusTraversalGroup.maybeOfNode(n) == this && _isLaidOut(n))
.toList();
if (candidates.isEmpty) return false;
final sorted = sortDescendants(candidates, currentNode).toList();
var index = sorted.indexOf(currentNode);
if (index == -1) {
index = direction == TraversalDirection.down ? -1 : sorted.length;
}
final nextIndex = direction == TraversalDirection.down ? index + 1 : index - 1;
if (nextIndex < 0 || nextIndex >= sorted.length) {
return true;
}
requestFocusCallback(sorted[nextIndex]);
return true;
}
return super.inDirection(currentNode, direction);
}
}
bool _isLaidOut(FocusNode node) {
final ro = node.context?.findRenderObject();
return ro is RenderBox && ro.hasSize;
}
bool isNodeInCurrentRoute(FocusNode node) {
if (!node.canRequestFocus) return false;
if (node.context == null) return false;
final nearestScope = FocusScope.of(node.context!);
return nearestScope.hasFocus || nearestScope.isFirstFocus;
}

View file

@ -0,0 +1,16 @@
import 'package:flutter/material.dart';
extension EnsureVisibleHelper on BuildContext {
Future<void> ensureVisible({
Duration duration = const Duration(milliseconds: 300),
double? alignment,
Curve curve = Curves.fastOutSlowIn,
}) {
return Scrollable.ensureVisible(
this,
duration: duration,
alignment: alignment ?? 0.5,
curve: curve,
);
}
}

View file

@ -1,12 +1,14 @@
import 'package:flutter/material.dart';
import 'package:fladder/screens/shared/flat_button.dart';
import 'package:fladder/util/adaptive_layout/adaptive_layout.dart';
import 'package:fladder/util/focus_provider.dart';
import 'package:fladder/widgets/shared/ensure_visible.dart';
import 'package:fladder/widgets/shared/item_actions.dart';
import 'package:fladder/widgets/shared/modal_bottom_sheet.dart';
class EnumBox<T> extends StatelessWidget {
final String current;
final List<PopupMenuEntry<T>> Function(BuildContext context) itemBuilder;
final List<ItemAction> Function(BuildContext context) itemBuilder;
const EnumBox({required this.current, required this.itemBuilder, super.key});
@ -15,7 +17,7 @@ class EnumBox<T> extends StatelessWidget {
final textStyle = Theme.of(context).textTheme.titleMedium;
const padding = EdgeInsets.symmetric(horizontal: 12, vertical: 6);
final itemList = itemBuilder(context);
final useBottomSheet = AdaptiveLayout.viewSizeOf(context) <= ViewSize.phone;
final useBottomSheet = AdaptiveLayout.inputDeviceOf(context) != InputDevice.pointer;
final labelWidget = Padding(
padding: padding,
@ -46,29 +48,39 @@ class EnumBox<T> extends StatelessWidget {
),
);
return Card(
color: Theme.of(context).colorScheme.primaryContainer,
color: itemList.length > 1 ? Theme.of(context).colorScheme.primaryContainer : Colors.transparent,
shadowColor: Colors.transparent,
elevation: 0,
child: useBottomSheet
? FlatButton(
? FocusButton(
child: labelWidget,
onTap: () => showBottomSheetPill(
context: context,
content: (context, scrollController) => ListView(
shrinkWrap: true,
controller: scrollController,
children: [
const SizedBox(height: 6),
...itemBuilder(context),
],
),
),
darkOverlay: false,
onFocusChanged: (value) {
if (value) {
context.ensureVisible();
}
},
onTap: itemList.length > 1
? () => showBottomSheetPill(
context: context,
content: (context, scrollController) => ListView(
shrinkWrap: true,
controller: scrollController,
children: [
const SizedBox(height: 6),
...itemList.map(
(e) => e.toListItem(context),
),
],
),
)
: null,
)
: PopupMenuButton(
tooltip: '',
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
enabled: itemList.length > 1,
itemBuilder: itemBuilder,
itemBuilder: (context) => itemList.map((e) => e.toPopupMenuItem()).toList(),
padding: padding,
child: labelWidget,
),
@ -79,7 +91,7 @@ class EnumBox<T> extends StatelessWidget {
class EnumSelection<T> extends StatelessWidget {
final Text label;
final String current;
final List<PopupMenuEntry<T>> Function(BuildContext context) itemBuilder;
final List<ItemAction> Function(BuildContext context) itemBuilder;
const EnumSelection({
super.key,
required this.label,

View file

@ -0,0 +1,186 @@
import 'package:flutter/material.dart';
import 'package:collection/collection.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:fladder/util/focus_provider.dart';
import 'package:fladder/widgets/navigation_scaffold/components/side_navigation_bar.dart';
class GridFocusTraveler extends ConsumerStatefulWidget {
final int currentIndex;
final int itemCount;
final int crossAxisCount;
final Function(BuildContext context, int selectedIndex, int index) itemBuilder;
final SliverGridDelegate gridDelegate;
const GridFocusTraveler({
this.currentIndex = 0,
required this.itemCount,
required this.crossAxisCount,
required this.itemBuilder,
required this.gridDelegate,
super.key,
});
@override
ConsumerState<GridFocusTraveler> createState() => _GridFocusTravelerState();
}
class _GridFocusTravelerState extends ConsumerState<GridFocusTraveler> {
late int selectedIndex = widget.currentIndex;
late final List<FocusNode> _focusNodes;
@override
void initState() {
super.initState();
_focusNodes = List.generate(widget.itemCount, (index) => FocusNode());
_focusNodes.mapIndexed(
(index, element) {
element.addListener(() {
if (element.hasFocus) {
setState(() {
selectedIndex = index;
});
}
});
},
);
if (!FocusProvider.autoFocusOf(context)) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_focusNodes.firstOrNull?.requestFocus();
});
}
}
@override
void didUpdateWidget(GridFocusTraveler oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.itemCount != oldWidget.itemCount) {
for (var node in _focusNodes) {
node.dispose();
}
_focusNodes = List.generate(widget.itemCount, (index) => FocusNode());
if (selectedIndex >= widget.itemCount) {
selectedIndex = widget.itemCount - 1;
if (selectedIndex >= 0) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_focusNodes[selectedIndex].requestFocus();
});
}
}
}
}
@override
void dispose() {
for (var node in _focusNodes) {
node.dispose();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
return FocusTraversalGroup(
policy: GridFocusTravelerPolicy(
navBarNode: navBarNode,
nodes: _focusNodes,
crossAxisCount: widget.crossAxisCount,
onChanged: (value) {
selectedIndex = value;
_focusNodes[value].requestFocus();
},
),
child: SliverGrid.builder(
gridDelegate: widget.gridDelegate,
itemCount: widget.itemCount,
itemBuilder: (context, index) {
return FocusProvider(
focusNode: _focusNodes[index],
child: Builder(
builder: (context) => widget.itemBuilder(context, selectedIndex, index),
),
);
},
),
);
}
}
class GridFocusTravelerPolicy extends ReadingOrderTraversalPolicy {
/// The complete list of FocusNodes for the grid.
final List<FocusNode> nodes;
/// The number of items in each row.
final int crossAxisCount;
/// Callback to notify the parent which node index should be focused next.
final Function(int value) onChanged;
/// The navigation bar node to focus when navigating left from the first column.
final FocusNode navBarNode;
GridFocusTravelerPolicy({
required this.nodes,
required this.crossAxisCount,
required this.onChanged,
required this.navBarNode,
});
@override
bool inDirection(FocusNode currentNode, TraversalDirection direction) {
final int current = nodes.indexOf(currentNode);
if (current == -1) {
return super.inDirection(currentNode, direction);
}
final int itemCount = nodes.length;
final int row = current ~/ crossAxisCount;
final int col = current % crossAxisCount;
final int rowCount = (itemCount / crossAxisCount).ceil();
int? next;
switch (direction) {
case TraversalDirection.left:
if (col > 0) {
next = current - 1;
}
break;
case TraversalDirection.right:
if (col < crossAxisCount - 1 && current + 1 < itemCount) {
next = current + 1;
}
break;
case TraversalDirection.up:
if (row > 0) {
next = current - crossAxisCount;
}
break;
case TraversalDirection.down:
if (row < rowCount - 1) {
final int candidate = current + crossAxisCount;
if (candidate < itemCount) {
next = candidate;
}
}
break;
}
if (next != null) {
onChanged(next);
return true;
}
if (direction == TraversalDirection.left && col == 0) {
navBarNode.requestFocus();
return true;
}
return super.inDirection(currentNode, direction);
}
}

View file

@ -1,4 +1,4 @@
import 'dart:math';
import 'dart:math' as math;
import 'package:flutter/material.dart';
@ -7,26 +7,32 @@ import 'package:iconsax_plus/iconsax_plus.dart';
import 'package:fladder/providers/settings/client_settings_provider.dart';
import 'package:fladder/util/adaptive_layout/adaptive_layout.dart';
import 'package:fladder/util/disable_keypad_focus.dart';
import 'package:fladder/util/focus_provider.dart';
import 'package:fladder/util/list_padding.dart';
import 'package:fladder/util/sticky_header_text.dart';
import 'package:fladder/widgets/navigation_scaffold/components/side_navigation_bar.dart';
import 'package:fladder/widgets/shared/ensure_visible.dart';
class HorizontalList<T> extends ConsumerStatefulWidget {
final bool autoFocus;
final String? label;
final List<Widget> titleActions;
final Function()? onLabelClick;
final String? subtext;
final List<T> items;
final int? startIndex;
final Widget Function(BuildContext context, int index) itemBuilder;
final Widget Function(BuildContext context, int index, int selected) itemBuilder;
final Function(int index)? onFocused;
final bool scrollToEnd;
final EdgeInsets contentPadding;
final double? dominantRatio;
final double? height;
final bool shrinkWrap;
const HorizontalList({
this.autoFocus = false,
required this.items,
required this.itemBuilder,
this.onFocused,
this.startIndex,
this.height,
this.label,
@ -45,44 +51,100 @@ class HorizontalList<T> extends ConsumerStatefulWidget {
}
class _HorizontalListState extends ConsumerState<HorizontalList> {
final FocusNode parentNode = FocusNode();
late int currentIndex = 0;
final GlobalKey _firstItemKey = GlobalKey();
final ScrollController _scrollController = ScrollController();
final contentPadding = 8.0;
double? contentWidth;
double? _firstItemWidth;
bool hasFocus = false;
late List<FocusNode> _focusNodes;
@override
void initState() {
super.initState();
_measureFirstItem(scrollTo: true);
_initFocusNodes();
_measureFirstItem();
}
@override
void dispose() {
super.dispose();
}
void _measureFirstItem({bool scrollTo = false}) {
void _measureFirstItem() {
if (_firstItemWidth != null) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (widget.startIndex != null) {
final context = _firstItemKey.currentContext;
if (context != null) {
final box = context.findRenderObject() as RenderBox;
_firstItemWidth = box.size.width;
if (scrollTo) {
_scrollToPosition(widget.startIndex!);
}
}
final context = _firstItemKey.currentContext;
if (context != null) {
final box = context.findRenderObject() as RenderBox;
_firstItemWidth = box.size.width;
_scrollToPosition(widget.startIndex ?? 0);
}
});
}
void _scrollToPosition(int index) {
final offset = index * _firstItemWidth! + index * contentPadding;
_scrollController.animateTo(
offset,
void _initFocusNodes() {
_focusNodes = List.generate(widget.items.length, (i) {
final node = FocusNode();
node.addListener(() {
if (node.hasFocus) {
_scrollToPosition(i);
if (widget.onFocused != null) {
widget.onFocused?.call(i);
} else {
context.ensureVisible();
}
}
});
return node;
});
WidgetsBinding.instance.addPostFrameCallback((_) {
if (widget.autoFocus) {
_focusNodes[currentIndex].requestFocus();
context.ensureVisible();
}
});
}
@override
void dispose() {
for (var node in _focusNodes) {
node.dispose();
}
parentNode.dispose();
super.dispose();
}
@override
void didUpdateWidget(HorizontalList oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.items.length != oldWidget.items.length) {
for (var node in _focusNodes) {
node.dispose();
}
_initFocusNodes();
if (currentIndex >= widget.items.length) {
currentIndex = widget.items.isEmpty ? 0 : widget.items.length - 1;
}
if (widget.items.isNotEmpty && parentNode.hasFocus) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_focusNodes[currentIndex].requestFocus();
});
}
}
}
Future<void> _scrollToPosition(int index) async {
if (_firstItemWidth == null) return;
final offset = index * (_firstItemWidth! + contentPadding);
final clamped = math.min(offset, _scrollController.position.maxScrollExtent);
await _scrollController.animateTo(
clamped,
duration: const Duration(milliseconds: 250),
curve: Curves.easeInOut,
curve: Curves.fastOutSlowIn,
);
}
@ -90,34 +152,35 @@ class _HorizontalListState extends ConsumerState<HorizontalList> {
_scrollController.animateTo(
0,
duration: const Duration(milliseconds: 250),
curve: Curves.easeInOut,
curve: Curves.fastOutSlowIn,
);
}
void _scrollToEnd() {
Future<void> _scrollToEnd() async {
final offset = (_firstItemWidth ?? 200) * widget.items.length + 200;
_scrollController.animateTo(
(_firstItemWidth ?? 200) * widget.items.length + 200,
math.min(offset, _scrollController.position.maxScrollExtent),
duration: const Duration(milliseconds: 250),
curve: Curves.easeInOut,
curve: Curves.fastOutSlowIn,
);
}
int getFirstVisibleIndex() {
if (widget.startIndex == null) return 0;
if (!_scrollController.hasClients || _firstItemWidth == null) return 0;
return (_scrollController.offset / _firstItemWidth!).floor().clamp(0, widget.items.length - 1);
}
@override
Widget build(BuildContext context) {
final hasPointer = AdaptiveLayout.of(context).inputDevice == InputDevice.pointer;
final content = Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
DisableFocus(
child: Padding(
return Focus(
focusNode: parentNode,
onFocusChange: (value) {
if (value) {
_focusNodes[currentIndex].requestFocus();
}
},
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: widget.contentPadding,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
@ -128,18 +191,22 @@ class _HorizontalListState extends ConsumerState<HorizontalList> {
children: [
if (widget.label != null)
Flexible(
child: StickyHeaderText(
label: widget.label ?? "",
onClick: widget.onLabelClick,
child: ExcludeFocus(
child: StickyHeaderText(
label: widget.label ?? "",
onClick: widget.onLabelClick,
),
),
),
if (widget.subtext != null)
Flexible(
child: Opacity(
opacity: 0.5,
child: Text(
widget.subtext!,
style: Theme.of(context).textTheme.titleMedium,
child: ExcludeFocus(
child: Opacity(
opacity: 0.5,
child: Text(
widget.subtext!,
style: Theme.of(context).textTheme.titleMedium,
),
),
),
),
@ -148,89 +215,135 @@ class _HorizontalListState extends ConsumerState<HorizontalList> {
),
),
if (widget.items.length > 1)
Card(
elevation: 5,
color: Theme.of(context).colorScheme.surface,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
if (hasPointer)
GestureDetector(
onLongPress: () => _scrollToStart(),
child: IconButton(
ExcludeFocus(
child: Card(
elevation: 5,
color: Theme.of(context).colorScheme.surface,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
if (hasPointer)
GestureDetector(
onLongPress: () => _scrollToStart(),
child: IconButton(
onPressed: () {
_scrollController.animateTo(
_scrollController.offset + -(MediaQuery.of(context).size.width / 1.75),
duration: const Duration(milliseconds: 250),
curve: Curves.easeInOut);
},
icon: const Icon(
IconsaxPlusLinear.arrow_left_1,
size: 20,
)),
),
if (widget.startIndex != null)
IconButton(
tooltip: "Scroll to current",
onPressed: () {
_scrollController.animateTo(
_scrollController.offset + -(MediaQuery.of(context).size.width / 1.75),
duration: const Duration(milliseconds: 250),
curve: Curves.easeInOut);
},
icon: const Icon(
IconsaxPlusLinear.arrow_left_1,
size: 20,
)),
),
if (widget.startIndex != null)
IconButton(
tooltip: "Scroll to current",
onPressed: () {
if (_firstItemWidth != null && widget.startIndex != null) {
_scrollToPosition(widget.startIndex!);
}
},
icon: const Icon(
Icons.circle,
size: 16,
)),
if (hasPointer)
GestureDetector(
onLongPress: () => _scrollToEnd(),
child: IconButton(
onPressed: () {
_scrollController.animateTo(
_scrollController.offset + (MediaQuery.of(context).size.width / 1.75),
duration: const Duration(milliseconds: 250),
curve: Curves.easeInOut);
},
icon: const Icon(
IconsaxPlusLinear.arrow_right_3,
size: 20,
Icons.circle,
size: 16,
)),
),
],
if (hasPointer)
GestureDetector(
onLongPress: () => _scrollToEnd(),
child: IconButton(
onPressed: () {
_scrollController.animateTo(
_scrollController.offset + (MediaQuery.of(context).size.width / 1.75),
duration: const Duration(milliseconds: 250),
curve: Curves.easeInOut);
},
icon: const Icon(
IconsaxPlusLinear.arrow_right_3,
size: 20,
)),
),
],
),
),
),
].addPadding(const EdgeInsets.symmetric(horizontal: 6)),
),
),
),
const SizedBox(height: 8),
SizedBox(
height: widget.height ??
((AdaptiveLayout.poster(context).size *
ref.watch(clientSettingsProvider.select((value) => value.posterSize))) /
pow((widget.dominantRatio ?? 1.0), 0.55)) *
0.72,
child: ListView.separated(
controller: _scrollController,
scrollDirection: Axis.horizontal,
padding: widget.contentPadding,
itemBuilder: (context, index) => index == getFirstVisibleIndex()
? Container(
key: _firstItemKey,
child: widget.itemBuilder(context, index),
)
: widget.itemBuilder(context, index),
separatorBuilder: (context, index) => SizedBox(width: contentPadding),
itemCount: widget.items.length,
const SizedBox(height: 8),
SizedBox(
height: widget.height ??
((AdaptiveLayout.poster(context).size *
ref.watch(clientSettingsProvider.select((value) => value.posterSize))) /
math.pow((widget.dominantRatio ?? 1.0), 0.55)) *
0.72,
child: FocusTraversalGroup(
policy: HorizontalRailFocus(
parentNode: parentNode,
nodes: _focusNodes,
onChanged: (value) {
currentIndex = value;
_focusNodes[value].requestFocus();
}),
child: ExcludeFocusTraversal(
child: ListView.separated(
controller: _scrollController,
scrollDirection: Axis.horizontal,
padding: widget.contentPadding,
itemBuilder: (context, index) {
return FocusProvider(
focusNode: _focusNodes[index],
hasFocus: hasFocus && index == currentIndex,
key: index == 0 ? _firstItemKey : null,
child: widget.itemBuilder(context, index, hasFocus ? currentIndex : -1),
);
},
separatorBuilder: (context, index) => SizedBox(width: contentPadding),
itemCount: widget.items.length,
),
),
),
),
),
],
],
),
);
return widget.startIndex == null
? content
: LayoutBuilder(builder: (context, constraints) {
_measureFirstItem();
return content;
});
}
}
class HorizontalRailFocus extends WidgetOrderTraversalPolicy {
final FocusNode parentNode;
final List<FocusNode> nodes;
final Function(int value) onChanged;
HorizontalRailFocus({
required this.parentNode,
required this.nodes,
required this.onChanged,
});
@override
bool inDirection(FocusNode currentNode, TraversalDirection direction) {
// Find the index of the currently focused node
final int current = nodes.indexWhere((node) => node.hasFocus);
// If nothing is focused, default to 0
final int currentIndex = current == -1 ? 0 : current;
if (direction == TraversalDirection.left) {
if (currentIndex <= 0) {
navBarNode.requestFocus();
return true;
} else {
onChanged(math.max(currentIndex - 1, 0));
return true;
}
} else if (direction == TraversalDirection.right) {
if (currentIndex >= nodes.length - 1) {
// Corrected boundary check
return super.inDirection(parentNode, direction);
} else {
onChanged(math.min(currentIndex + 1, nodes.length - 1));
return true;
}
}
parentNode.requestFocus();
return super.inDirection(parentNode, direction);
}
}

View file

@ -33,21 +33,25 @@ class ItemActionDivider extends ItemAction {
}
class ItemActionButton extends ItemAction {
final bool selected;
final Widget? icon;
final Widget? label;
final FutureOr<void> Function()? action;
ItemActionButton({
this.selected = false,
this.icon,
this.label,
this.action,
});
ItemActionButton copyWith({
bool? selected,
Widget? icon,
Widget? label,
Future<void> Function()? action,
}) {
return ItemActionButton(
selected: selected ?? this.selected,
icon: icon ?? this.icon,
label: label ?? this.label,
action: action ?? this.action,
@ -93,14 +97,19 @@ class ItemActionButton extends ItemAction {
@override
Widget toListItem(BuildContext context, {bool useIcons = false, bool shouldPop = true}) {
final foregroundColor =
selected ? Theme.of(context).colorScheme.onPrimaryContainer : Theme.of(context).colorScheme.onSurface;
return ElevatedButton(
autofocus: selected,
style: ButtonStyle(
backgroundColor: const WidgetStatePropertyAll(Colors.transparent),
backgroundColor: WidgetStatePropertyAll(
selected ? Theme.of(context).colorScheme.primaryContainer : Colors.transparent,
),
padding: const WidgetStatePropertyAll(EdgeInsets.symmetric(horizontal: 12)),
minimumSize: const WidgetStatePropertyAll(Size(50, 50)),
elevation: const WidgetStatePropertyAll(0),
foregroundColor: WidgetStatePropertyAll(Theme.of(context).colorScheme.onSurface),
iconColor: WidgetStatePropertyAll(Theme.of(context).colorScheme.onSurface),
foregroundColor: WidgetStatePropertyAll(foregroundColor),
iconColor: WidgetStatePropertyAll(foregroundColor),
),
onPressed: () {
if (shouldPop) {
@ -113,7 +122,7 @@ class ItemActionButton extends ItemAction {
builder: (context) {
return Theme(
data: ThemeData(
iconTheme: IconThemeData(color: Theme.of(context).colorScheme.onSurface),
iconTheme: IconThemeData(color: foregroundColor),
),
child: Row(
children: [
@ -134,10 +143,13 @@ extension ItemActionExtension on List<ItemAction> {
List<PopupMenuEntry> popupMenuItems({bool useIcons = false}) => map((e) => e.toPopupMenuItem(useIcons: useIcons))
.whereNotIndexed((index, element) => (index == 0 && element is PopupMenuDivider))
.toList();
List<Widget> menuItemButtonItems() =>
map((e) => e.toMenuItemButton()).whereNotIndexed((index, element) => (index == 0 && element is Divider)).toList();
List<Widget> listTileItems(BuildContext context, {bool useIcons = false, bool shouldPop = true}) =>
map((e) => e.toListItem(context, useIcons: useIcons, shouldPop: shouldPop))
.whereNotIndexed((index, element) => (index == 0 && element is Divider))
.toList();
List<Widget> listTileItems(BuildContext context, {bool useIcons = false, bool shouldPop = true}) {
return map((e) => e.toListItem(context, useIcons: useIcons, shouldPop: shouldPop))
.whereNotIndexed((index, element) => (index == 0 && element is Divider))
.toList();
}
}

View file

@ -7,6 +7,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:fladder/screens/shared/animated_fade_size.dart';
import 'package:fladder/util/refresh_state.dart';
import 'package:fladder/widgets/shared/ensure_visible.dart';
class SelectableIconButton extends ConsumerStatefulWidget {
final FutureOr<dynamic> Function() onPressed;
@ -33,6 +34,7 @@ class SelectableIconButton extends ConsumerStatefulWidget {
class _SelectableIconButtonState extends ConsumerState<SelectableIconButton> {
bool loading = false;
bool focused = false;
@override
Widget build(BuildContext context) {
const duration = Duration(milliseconds: 250);
@ -51,6 +53,16 @@ class _SelectableIconButtonState extends ConsumerState<SelectableIconButton> {
widget.iconColor ?? (widget.selected ? Theme.of(context).colorScheme.onPrimary : null)),
padding: const WidgetStatePropertyAll(EdgeInsets.zero),
),
onFocusChange: (value) {
setState(() {
focused = value;
});
if (value) {
context.ensureVisible(
alignment: 1.0,
);
}
},
onPressed: loading
? null
: () async {