import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../icons/app_icons.dart'; import '../theme/app_theme.dart'; import '../theme/menu_metrics.dart'; import 'native_context_menu.dart'; import 'app_combobox.dart'; import 'menu_trigger_focus.dart'; part 'app_menu.freezed.dart'; void _focusMenu(GlobalKey entryKey) { WidgetsBinding.instance.addPostFrameCallback((_) { final context = entryKey.currentContext; if (context == null) return; final scope = FocusScope.of(context); final policy = FocusTraversalGroup.of(context); policy.findFirstFocus(scope, ignoreCurrentFocus: true)?.requestFocus(); }); } abstract final class AppMenuStyle { static MenuStyle panel(BuildContext context, {double minWidth = 160}) { final colors = Theme.of(context).colorScheme; return MenuStyle( backgroundColor: WidgetStatePropertyAll( AppTheme.popoverBackground(context), ), surfaceTintColor: const WidgetStatePropertyAll(Colors.transparent), elevation: const WidgetStatePropertyAll(4), shadowColor: WidgetStatePropertyAll(colors.shadow.withValues(alpha: .2)), minimumSize: WidgetStatePropertyAll(Size(minWidth, 0)), padding: const WidgetStatePropertyAll( EdgeInsets.all(AppMenuMetrics.gutter), ), side: WidgetStatePropertyAll( BorderSide( color: colors.outlineVariant, width: AppMenuMetrics.borderWidth, ), ), shape: const WidgetStatePropertyAll( RoundedRectangleBorder( borderRadius: BorderRadius.all( Radius.circular(AppMenuMetrics.radius), ), ), ), ); } static MenuStyle selectPanel( BuildContext context, { required double minWidth, }) => panel(context, minWidth: minWidth); static ButtonStyle selectItem(BuildContext context) => item(context); static ButtonStyle descriptionItem( BuildContext context, { bool destructive = false, }) => item(context, destructive: destructive).copyWith( minimumSize: const WidgetStatePropertyAll( Size(0, AppMenuMetrics.descriptionRowHeight), ), padding: const WidgetStatePropertyAll( EdgeInsets.symmetric( horizontal: AppMenuMetrics.iconGap, vertical: AppMenuMetrics.descriptionVerticalPadding, ), ), textStyle: WidgetStatePropertyAll( Theme.of(context).textTheme.bodyMedium?.copyWith( fontSize: AppMenuMetrics.titleFontSize, height: AppMenuMetrics.titleLineHeight / AppMenuMetrics.titleFontSize, ), ), ); static ButtonStyle item(BuildContext context, {bool destructive = false}) { final theme = Theme.of(context); final colors = theme.colorScheme; final foreground = destructive ? colors.error : colors.onSurface; return ButtonStyle( textStyle: WidgetStatePropertyAll( theme.textTheme.bodyMedium?.copyWith( fontSize: AppMenuMetrics.fontSize, height: AppMenuMetrics.lineHeight / AppMenuMetrics.fontSize, ), ), iconSize: const WidgetStatePropertyAll(AppMenuMetrics.iconSize), minimumSize: const WidgetStatePropertyAll( Size(0, AppMenuMetrics.rowHeight), ), padding: const WidgetStatePropertyAll( EdgeInsets.symmetric(horizontal: AppMenuMetrics.iconGap, vertical: 5), ), tapTargetSize: MaterialTapTargetSize.shrinkWrap, visualDensity: VisualDensity.standard, shape: const WidgetStatePropertyAll( RoundedRectangleBorder( borderRadius: BorderRadius.all( Radius.circular(AppMenuMetrics.itemRadius), ), ), ), foregroundColor: WidgetStateProperty.resolveWith( (states) => states.contains(WidgetState.disabled) ? foreground.withValues(alpha: .5) : foreground, ), iconColor: WidgetStateProperty.resolveWith( (states) => states.contains(WidgetState.disabled) ? foreground.withValues(alpha: .5) : foreground, ), backgroundColor: WidgetStateProperty.resolveWith( (states) => states.any( { WidgetState.hovered, WidgetState.focused, WidgetState.pressed, }.contains, ) ? (destructive ? colors.errorContainer : AppSidebarColors.of(context).hover) : Colors.transparent, ), overlayColor: const WidgetStatePropertyAll(Colors.transparent), ); } } class AppMenuItem extends StatefulWidget { const AppMenuItem({ super.key, required this.label, this.description, this.onPressed, this.icon, this.selected, this.destructive = false, this.selectOption = false, this.requestFocusOnHover = true, }); final String label; final String? description; final VoidCallback? onPressed; final IconData? icon; final bool? selected; final bool destructive; final bool selectOption; final bool requestFocusOnHover; @override State createState() => _AppMenuItemState(); } class _AppMenuItemState extends State { final _focus = FocusNode(); bool _focusFromHover = false; @override void dispose() { _focus.dispose(); super.dispose(); } @override Widget build(BuildContext context) => Semantics( selected: widget.selected, child: Focus( canRequestFocus: false, onKeyEvent: (_, event) { if (event is KeyDownEvent) _focusFromHover = false; return KeyEventResult.ignored; }, child: MenuItemButton( focusNode: _focus, requestFocusOnHover: widget.requestFocusOnHover, onHover: (hovered) { // Material moves focus on pointer hover, but retains it on exit. // Release only mouse-acquired focus when scrolling moves this item // away; keep keyboard focus and the normal highlight transition. if (!hovered && _focusFromHover && _focus.hasFocus) { _focus.unfocus(); } _focusFromHover = hovered; }, onPressed: widget.onPressed, style: widget.description != null ? AppMenuStyle.descriptionItem( context, destructive: widget.destructive, ) : widget.selectOption ? AppMenuStyle.selectItem(context) : AppMenuStyle.item(context, destructive: widget.destructive), leadingIcon: widget.icon == null ? null : Icon(widget.icon), trailingIcon: widget.selectOption || widget.selected == null ? null : SizedBox.square( dimension: AppMenuMetrics.iconSize, child: widget.selected! ? const Icon(AppIcons.check) : null, ), child: widget.selectOption ? Row( children: [ Expanded( child: Text( widget.label, maxLines: 1, overflow: TextOverflow.ellipsis, ), ), const SizedBox(width: AppSpacing.small), SizedBox.square( dimension: 16, child: widget.selected == true ? const Icon(AppIcons.check, size: 16) : null, ), ], ) : widget.description == null ? Text(widget.label, maxLines: 1, overflow: TextOverflow.ellipsis) : Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( widget.label, maxLines: 1, overflow: TextOverflow.ellipsis, ), Text( widget.description!, maxLines: 1, overflow: TextOverflow.ellipsis, style: Theme.of(context).textTheme.bodySmall?.copyWith( fontSize: AppMenuMetrics.descriptionFontSize, height: AppMenuMetrics.descriptionLineHeight / AppMenuMetrics.descriptionFontSize, ), ), ], ), ), ), ); } class AppMenuSeparator extends StatelessWidget { const AppMenuSeparator({super.key}); @override Widget build(BuildContext context) => const Padding( padding: EdgeInsets.symmetric( horizontal: AppMenuMetrics.iconGap, vertical: AppMenuMetrics.separatorVerticalPadding, ), child: Divider(height: 1), ); } class AppMenuLabel extends StatelessWidget { const AppMenuLabel(this.label, {super.key}); final String label; @override Widget build(BuildContext context) => Padding( padding: const EdgeInsets.symmetric( horizontal: AppSpacing.gap, vertical: AppSpacing.tiny, ), child: Text( label, style: Theme.of(context).textTheme.labelMedium ?.copyWith(color: Theme.of(context).colorScheme.onSurfaceVariant), ), ); } class AppSubmenu extends StatelessWidget { const AppSubmenu({ super.key, required this.label, required this.items, this.icon, }); final String label; final List items; final IconData? icon; @override Widget build(BuildContext context) => SubmenuButton( style: AppMenuStyle.item(context), menuStyle: AppMenuStyle.panel(context), leadingIcon: icon == null ? null : Icon(icon), menuChildren: items, child: Text(label), ); } typedef AppMenuTriggerBuilder = Widget Function( BuildContext context, VoidCallback? toggle, FocusNode focusNode, ); class AppDropdownMenu extends StatefulWidget { const AppDropdownMenu({ super.key, required this.items, required this.builder, this.enabled = true, this.minWidth = 160, this.maxHeight, this.onClose, this.menuStyle, this.crossAxisUnconstrained = false, this.alignmentOffset = const Offset(0, 4), }); final List items; final AppMenuTriggerBuilder builder; final bool enabled; final double minWidth; final double? maxHeight; final VoidCallback? onClose; final MenuStyle? menuStyle; final bool crossAxisUnconstrained; final Offset alignmentOffset; @override State createState() => _AppDropdownMenuState(); } class _AppDropdownMenuState extends State { final _controller = MenuController(); late final _triggerFocus = MenuTriggerFocus(controller: _controller); FocusNode get _focus => _triggerFocus.node; final _entryKey = GlobalKey(); // MenuAnchor owns a scroll view. Do not let its offset read or overwrite // an enclosing inspector's expansion state or scroll position. final _menuStorage = PageStorageBucket(); @override void dispose() { _triggerFocus.dispose(); super.dispose(); } @override Widget build(BuildContext context) => PageStorage( bucket: _menuStorage, child: MenuAnchor( controller: _controller, childFocusNode: _focus, // Close on outside clicks without swallowing the target control's action. consumeOutsideTap: false, crossAxisUnconstrained: widget.crossAxisUnconstrained, alignmentOffset: widget.alignmentOffset, style: (widget.menuStyle ?? AppMenuStyle.panel(context, minWidth: widget.minWidth)) .copyWith( maximumSize: widget.maxHeight == null ? null : WidgetStatePropertyAll( Size(double.infinity, widget.maxHeight!), ), ), onClose: () { _triggerFocus.onClose(); widget.onClose?.call(); }, onOpen: () { _triggerFocus.onOpen(); _focusMenu(_entryKey); }, menuChildren: [ for (var i = 0; i < widget.items.length; i++) if (i == 0) Builder(key: _entryKey, builder: (_) => widget.items[i]) else widget.items[i], ], builder: (context, controller, _) => Shortcuts( shortcuts: const { SingleActivator(LogicalKeyboardKey.arrowDown): ActivateIntent(), }, child: widget.builder( context, !widget.enabled ? null : () { controller.isOpen ? controller.close() : controller.open(); }, _focus, ), ), ), ); } @freezed abstract class AppSelectOption with _$AppSelectOption { const factory AppSelectOption( T value, String label, { @Default(true) bool enabled, @Default([]) List searchTerms, }) = _AppSelectOption; } /// Shared shadcn-style select; searchable for long option lists. class AppSelect extends StatelessWidget { const AppSelect({ super.key, required this.value, required this.options, required this.onChanged, required this.label, required this.emptyLabel, this.searchHint, this.outlined = true, this.searchable = false, this.controlHeight, this.textStyle, }) : assert(!searchable || searchHint != null); final T value; final List> options; final ValueChanged? onChanged; final String label; final String emptyLabel; final String? searchHint; final bool outlined; final bool searchable; final double? controlHeight; final TextStyle? textStyle; @override Widget build(BuildContext context) => searchable ? AppCombobox( value: value, options: options, onChanged: onChanged, label: label, emptyLabel: emptyLabel, searchHint: searchHint!, ) : LayoutBuilder( builder: (context, constraints) { final theme = Theme.of(context); final colors = theme.colorScheme; final current = options .where((option) => option.value == value) .firstOrNull; final bounded = constraints.hasBoundedWidth; return AppDropdownMenu( enabled: onChanged != null, minWidth: outlined && bounded ? constraints.maxWidth : 160, maxHeight: 320, menuStyle: AppMenuStyle.selectPanel( context, minWidth: outlined && bounded ? constraints.maxWidth : 128, ), items: [ if (options.isEmpty) AppMenuLabel(emptyLabel), for (final option in options) AppMenuItem( label: option.label, selected: option.value == value, selectOption: true, onPressed: onChanged == null || !option.enabled ? null : () => onChanged!(option.value), ), ], builder: (context, toggle, focus) => Semantics( label: label, child: Opacity( opacity: onChanged == null ? .5 : 1, child: AnimatedContainer( duration: const Duration(milliseconds: 100), decoration: BoxDecoration( borderRadius: BorderRadius.circular(AppRadius.large), boxShadow: outlined ? [ BoxShadow( color: colors.shadow.withValues(alpha: .05), offset: const Offset(0, 1), blurRadius: 2, ), ] : null, ), child: TextButton( focusNode: focus, onPressed: toggle, style: TextButton.styleFrom( textStyle: textStyle ?? theme.textTheme.bodyMedium, foregroundColor: colors.onSurface, disabledForegroundColor: colors.onSurface, overlayColor: Colors.transparent, backgroundColor: outlined ? theme.inputDecorationTheme.fillColor : Colors.transparent, fixedSize: controlHeight == null ? null : Size.fromHeight(controlHeight!), minimumSize: Size( 0, controlHeight ?? (AppTheme.isDesktop(context) ? outlined ? theme .inputDecorationTheme .constraints ?.minHeight ?? AppDesktopMetrics.input : AppDesktopMetrics.iconButton : outlined ? AppControlSize.input : AppControlSize.small), ), tapTargetSize: MaterialTapTargetSize.shrinkWrap, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(AppRadius.large), ), side: outlined ? theme .inputDecorationTheme .enabledBorder ?.borderSide ?? BorderSide(color: colors.outlineVariant) : null, padding: EdgeInsets.symmetric( horizontal: outlined ? 12 : AppSpacing.tiny, vertical: outlined ? AppSpacing.inputVertical : 0, ), ), child: Row( mainAxisSize: MainAxisSize.min, children: [ Flexible( fit: outlined && bounded ? FlexFit.tight : FlexFit.loose, child: Text( current?.label ?? label, maxLines: 1, overflow: TextOverflow.ellipsis, ), ), const SizedBox(width: AppSpacing.small), Icon( AppIcons.expandMore, size: 16, color: colors.onSurfaceVariant.withValues( alpha: .5, ), ), ], ), ), ), ), ), ); }, ); } class AppContextMenu extends StatefulWidget { const AppContextMenu({ super.key, required this.itemsBuilder, required this.child, }); final List Function(BuildContext) itemsBuilder; final Widget child; @override State createState() => _AppContextMenuState(); } class _AppContextMenuState extends State { final _controller = MenuController(); final _focus = FocusNode(); final _entryKey = GlobalKey(); final _menuStorage = PageStorageBucket(); Offset _anchorPosition = Offset.zero; bool _focusFirstItem = false; bool _opening = false; @override void dispose() { _focus.dispose(); super.dispose(); } Future _open(Offset position, {required bool focusFirstItem}) async { if (_opening) return; _opening = true; try { _focus.requestFocus(); final box = context.findRenderObject() as RenderBox; if (await showNativeContextMenu( widget.itemsBuilder(context), box.localToGlobal(position), () => mounted, )) { return; } if (!mounted) return; _openFlutter(position, focusFirstItem: focusFirstItem); } finally { _opening = false; } } void _openFlutter(Offset position, {required bool focusFirstItem}) { _focus.requestFocus(); if (_controller.isOpen) _controller.close(); setState(() { _anchorPosition = position; _focusFirstItem = focusFirstItem; }); WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted) _controller.open(); }); } @override Widget build(BuildContext context) => Focus( focusNode: _focus, onKeyEvent: (node, event) { if (event is! KeyDownEvent) return KeyEventResult.ignored; if (event.logicalKey == LogicalKeyboardKey.contextMenu || (event.logicalKey == LogicalKeyboardKey.f10 && HardwareKeyboard.instance.isShiftPressed)) { _open(Offset.zero, focusFirstItem: true); return KeyEventResult.handled; } if (_controller.isOpen && !_focusFirstItem && event.logicalKey == LogicalKeyboardKey.arrowDown) { _focusFirstItem = true; _focusMenu(_entryKey); return KeyEventResult.handled; } return KeyEventResult.ignored; }, child: Stack( fit: StackFit.passthrough, children: [ GestureDetector( behavior: HitTestBehavior.translucent, // Let Flutter finish the pointer sequence before AppKit takes over // event tracking, otherwise NSMenu can consume the right-button up. onSecondaryTapUp: (details) => _open(details.localPosition, focusFirstItem: false), onLongPressStart: (details) => _open(details.localPosition, focusFirstItem: false), child: widget.child, ), Positioned( left: _anchorPosition.dx, top: _anchorPosition.dy, child: PageStorage( bucket: _menuStorage, child: MenuAnchor( controller: _controller, childFocusNode: _focus, // Nested anchors share their parent's open state. Consuming an // outside tap here would also block clicks outside that parent. consumeOutsideTap: false, crossAxisUnconstrained: false, style: AppMenuStyle.panel(context), onOpen: () { if (_focusFirstItem) _focusMenu(_entryKey); }, menuChildren: _items(context), child: const IgnorePointer(child: SizedBox.square(dimension: 1)), ), ), ), ], ), ); List _items(BuildContext context) { final items = widget.itemsBuilder(context); return [ for (var i = 0; i < items.length; i++) if (i == 0) Builder(key: _entryKey, builder: (_) => items[i]) else items[i], ]; } }