Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/+overlay-keyboard-contract.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Every dialog now takes keyboard focus when it opens, keeps Tab inside, closes on Esc and returns focus to where it was opened; the task dialog no longer leaves typing going into the ETB field behind it, and Enter on a remove confirmation cancels instead of confirming (#538).
233 changes: 233 additions & 0 deletions src/LageBuch.App.Shared/Behaviors/Overlay.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,233 @@
using System.Runtime.CompilerServices;
using System.Windows.Input;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Threading;
using Avalonia.VisualTree;

namespace LageBuch.App.Shared.Behaviors;

/// <summary>
/// The keyboard contract every overlay keeps (#538, contract 1 of #545), set on the overlay's
/// root: focus goes inside once it is shown, Tab cycles inside it, Esc runs
/// <see cref="CancelCommandProperty"/>, Enter runs <see cref="PrimaryCommandProperty"/> (never
/// inside multi-line text), and focus goes back to the control that opened it.
///
/// A destructive confirm sets no primary command: Enter then activates the focused button, which
/// starts out as ABBRECHEN, so a reflex Enter cancels.
/// </summary>
public static class Overlay
{
public static readonly AttachedProperty<ICommand?> CancelCommandProperty =
AvaloniaProperty.RegisterAttached<Control, ICommand?>("CancelCommand", typeof(Overlay));

public static readonly AttachedProperty<ICommand?> PrimaryCommandProperty =
AvaloniaProperty.RegisterAttached<Control, ICommand?>("PrimaryCommand", typeof(Overlay));

/// <summary>Where focus goes when the overlay opens; the first tab stop when unset.</summary>
public static readonly AttachedProperty<Control?> InitialFocusProperty =
AvaloniaProperty.RegisterAttached<Control, Control?>("InitialFocus", typeof(Overlay));

// The control that had focus when the overlay was shown: the one focus goes back to.
private static readonly ConditionalWeakTable<Control, IInputElement> Openers = new();

static Overlay()
{
CancelCommandProperty.Changed.AddClassHandler<Control>((root, e) =>
{
Detach(root);
if (e.NewValue is ICommand)
{
Attach(root);
}
});
}

public static void SetCancelCommand(Control target, ICommand? value)
{
ArgumentNullException.ThrowIfNull(target);
target.SetValue(CancelCommandProperty, value);
}

public static ICommand? GetCancelCommand(Control target)
{
ArgumentNullException.ThrowIfNull(target);
return target.GetValue(CancelCommandProperty);
}

public static void SetPrimaryCommand(Control target, ICommand? value)
{
ArgumentNullException.ThrowIfNull(target);
target.SetValue(PrimaryCommandProperty, value);
}

public static ICommand? GetPrimaryCommand(Control target)
{
ArgumentNullException.ThrowIfNull(target);
return target.GetValue(PrimaryCommandProperty);
}

public static void SetInitialFocus(Control target, Control? value)
{
ArgumentNullException.ThrowIfNull(target);
target.SetValue(InitialFocusProperty, value);
}

public static Control? GetInitialFocus(Control target)
{
ArgumentNullException.ThrowIfNull(target);
return target.GetValue(InitialFocusProperty);
}

private static void Attach(Control root)
{
// Focusable so focus can rest on the overlay itself when the focused control inside is
// disabled (a busy form), but no tab stop of its own.
root.Focusable = true;
KeyboardNavigation.SetIsTabStop(root, false);
KeyboardNavigation.SetTabNavigation(root, KeyboardNavigationMode.Cycle);
root.AttachedToVisualTree += OnAttached;
root.DetachedFromVisualTree += OnDetached;
root.AddHandler(InputElement.KeyDownEvent, OnKeyDown);
root.AddHandler(InputElement.LostFocusEvent, OnLostFocus);
if (root.IsAttachedToVisualTree())
{
Opened(root);
}
}

private static void Detach(Control root)
{
root.AttachedToVisualTree -= OnAttached;
root.DetachedFromVisualTree -= OnDetached;
root.RemoveHandler(InputElement.KeyDownEvent, OnKeyDown);
root.RemoveHandler(InputElement.LostFocusEvent, OnLostFocus);
}

private static void OnAttached(object? sender, VisualTreeAttachmentEventArgs e)
{
if (sender is Control root)
{
Opened(root);
}
}

private static void Opened(Control root)
{
Openers.Remove(root);
if (TopLevel.GetTopLevel(root)?.FocusManager?.GetFocusedElement() is { } opener && !IsWithin(root, opener))
{
Openers.Add(root, opener);
}

// Posted, at a lower priority than a view's own posted focus: the overlay is not laid out
// yet at attach time, so a synchronous Focus() is dropped, and a view that places focus
// itself (OperatorPrompt, by stage) keeps that placement.
Dispatcher.UIThread.Post(() => FocusInitial(root), DispatcherPriority.Background);
}

private static void FocusInitial(Control root)
{
var focusManager = TopLevel.GetTopLevel(root)?.FocusManager;
if (focusManager is null || IsWithin(root, focusManager.GetFocusedElement()))
{
return;
}

var target = GetInitialFocus(root) ?? FirstTabStop(root);
if (target is null)
{
root.Focus();
return;
}

target.Focus(NavigationMethod.Tab);
if (target is TextBox box)
{
box.SelectAll();
}
}

private static InputElement? FirstTabStop(Control root) =>
root.GetVisualDescendants().OfType<InputElement>()
.FirstOrDefault(e => e.Focusable && e.IsEffectivelyVisible && e.IsEffectivelyEnabled && KeyboardNavigation.GetIsTabStop(e));

private static void OnDetached(object? sender, VisualTreeAttachmentEventArgs e)
{
if (sender is not Control root || !Openers.TryGetValue(root, out var opener))
{
return;
}

Openers.Remove(root);
var topLevel = TopLevel.GetTopLevel(e.RootVisual);
Dispatcher.UIThread.Post(() =>
{
// Another overlay may have opened in the same breath (a confirm chaining into the PDF
// options); focus stays with it.
if (topLevel?.FocusManager?.GetFocusedElement() is Visual focused && IsInOverlay(focused))
{
return;
}

if (opener is Visual { } visual && visual.IsAttachedToVisualTree()
&& opener.IsEffectivelyVisible && opener.IsEffectivelyEnabled)
{
opener.Focus(NavigationMethod.Tab);
}
});
}

private static void OnKeyDown(object? sender, KeyEventArgs e)
{
if (e.Handled || sender is not Control root)
{
return;
}

var command = e.Key switch
{
Key.Escape => GetCancelCommand(root),
Key.Enter when e.Source is not TextBox { AcceptsReturn: true } => GetPrimaryCommand(root),
_ => null,
};
if (command?.CanExecute(null) == true)
{
command.Execute(null);
e.Handled = true;
}
}

// An overlay is modal, yet disabling the focused control (a busy form) moves focus on to the
// next control, which is on the page behind; the next key would land there. Keep it on the
// overlay instead.
private static void OnLostFocus(object? sender, RoutedEventArgs e)
{
if (sender is not Control root)
{
return;
}

Dispatcher.UIThread.Post(() =>
{
if (root.IsAttachedToVisualTree()
&& !IsWithin(root, TopLevel.GetTopLevel(root)?.FocusManager?.GetFocusedElement()))
{
root.Focus();
}
});
}

// Logical as well as visual: a drop-down's items live in a popup, outside the overlay's visual
// tree but under it logically.
private static bool IsWithin(Control root, IInputElement? element) =>
element is Visual visual
&& (ReferenceEquals(visual, root) || root.IsVisualAncestorOf(visual)
|| root.IsLogicalAncestorOf(visual));

private static bool IsInOverlay(Visual visual) =>
visual.GetSelfAndVisualAncestors().OfType<Control>().Any(c => GetCancelCommand(c) is not null);
}
4 changes: 3 additions & 1 deletion src/LageBuch.App.Shared/Views/AboutView.axaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:b="clr-namespace:LageBuch.App.Shared.Behaviors"
xmlns:vm="clr-namespace:LageBuch.AppLogic.ViewModels;assembly=LageBuch.AppLogic"
x:Class="LageBuch.App.Shared.Views.AboutView"
x:DataType="vm:AboutViewModel">
Expand All @@ -8,7 +9,8 @@
screen. Avalonia centres a Stretch element that MaxWidth has made narrower than its
slot, so a wide window looks exactly as it did. The scrim inset drops 40 -> 16 for the
same reason; on a desktop the card never comes near either. -->
<Border Background="#B3070A10" Padding="16" Focusable="True" KeyDown="OnKeyDown">
<Border Background="#B3070A10" Padding="16"
b:Overlay.CancelCommand="{Binding CloseCommand}" b:Overlay.InitialFocus="{Binding #CloseButton}">
<Border MaxWidth="420" VerticalAlignment="Center" HorizontalAlignment="Stretch"
Background="{StaticResource SurfaceRaisedBrush}"
BorderBrush="{StaticResource HairlineBrush}" BorderThickness="1"
Expand Down
24 changes: 2 additions & 22 deletions src/LageBuch.App.Shared/Views/AboutView.axaml.cs
Original file line number Diff line number Diff line change
@@ -1,29 +1,9 @@
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Threading;
using LageBuch.AppLogic.ViewModels;

namespace LageBuch.App.Shared.Views;

// Focus, Esc and focus return come from b:Overlay on the root (#538).
public partial class AboutView : UserControl
{
public AboutView()
{
InitializeComponent();

// Default focus on Close so a stray Enter just dismisses the dialog. Posted rather than
// called inline: realized as an overlay, the subtree is not yet laid out at
// AttachedToVisualTree time, so a synchronous Focus() is dropped (see OperatorPromptView).
AttachedToVisualTree += (_, _) => Dispatcher.UIThread.Post(() => CloseButton.Focus());
}

// Escape dismisses the dialog — consistent with the operator prompt and confirm dialog.
private void OnKeyDown(object? sender, KeyEventArgs e)
{
if (e.Key == Key.Escape && DataContext is AboutViewModel vm)
{
vm.CloseCommand.Execute(null);
e.Handled = true;
}
}
public AboutView() => InitializeComponent();
}
4 changes: 3 additions & 1 deletion src/LageBuch.App.Shared/Views/ConfirmDialogView.axaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:b="clr-namespace:LageBuch.App.Shared.Behaviors"
xmlns:vm="clr-namespace:LageBuch.AppLogic.ViewModels;assembly=LageBuch.AppLogic"
x:Class="LageBuch.App.Shared.Views.ConfirmDialogView"
x:DataType="vm:ConfirmDialogViewModel">
Expand All @@ -8,7 +9,8 @@
screen. Avalonia centres a Stretch element that MaxWidth has made narrower than its
slot, so a wide window looks exactly as it did. The scrim inset drops 40 -> 16 for the
same reason; on a desktop the card never comes near either. -->
<Border Background="#B3070A10" Padding="16" Focusable="True" KeyDown="OnKeyDown">
<Border Background="#B3070A10" Padding="16"
b:Overlay.CancelCommand="{Binding CancelCommand}" b:Overlay.InitialFocus="{Binding #CancelButton}">
<Border MaxWidth="420" VerticalAlignment="Center" HorizontalAlignment="Stretch"
Background="{StaticResource SurfaceRaisedBrush}"
BorderBrush="{StaticResource HairlineBrush}" BorderThickness="1"
Expand Down
31 changes: 2 additions & 29 deletions src/LageBuch.App.Shared/Views/ConfirmDialogView.axaml.cs
Original file line number Diff line number Diff line change
@@ -1,36 +1,9 @@
using Avalonia.Controls;
using Avalonia.Input;
using LageBuch.AppLogic.ViewModels;

namespace LageBuch.App.Shared.Views;

// Focus, Esc and focus return come from b:Overlay on the root (#538).
public partial class ConfirmDialogView : UserControl
{
public ConfirmDialogView()
{
InitializeComponent();

// Default focus on Cancel so a stray Enter doesn't blindly confirm a destructive action.
AttachedToVisualTree += (_, _) => CancelButton.Focus();
}

// Enter confirms, Escape cancels — consistent with the operator prompt.
private void OnKeyDown(object? sender, KeyEventArgs e)
{
if (DataContext is not ConfirmDialogViewModel vm)
{
return;
}

if (e.Key == Key.Escape)
{
vm.CancelCommand.Execute(null);
e.Handled = true;
}
else if (e.Key == Key.Enter)
{
vm.ConfirmCommand.Execute(null);
e.Handled = true;
}
}
public ConfirmDialogView() => InitializeComponent();
}
5 changes: 4 additions & 1 deletion src/LageBuch.App.Shared/Views/IncidentDataDialogView.axaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:b="clr-namespace:LageBuch.App.Shared.Behaviors"
xmlns:vm="clr-namespace:LageBuch.AppLogic.ViewModels;assembly=LageBuch.AppLogic"
x:Class="LageBuch.App.Shared.Views.IncidentDataDialogView"
x:DataType="vm:IncidentDataDialogViewModel">
Expand All @@ -8,7 +9,9 @@
screen. Avalonia centres a Stretch element that MaxWidth has made narrower than its
slot, so a wide window looks exactly as it did. The scrim inset drops 40 -> 16 for the
same reason; on a desktop the card never comes near either. -->
<Border Background="#B3070A10" Padding="16" Focusable="True" KeyDown="OnKeyDown">
<Border Background="#B3070A10" Padding="16"
b:Overlay.CancelCommand="{Binding CancelCommand}" b:Overlay.PrimaryCommand="{Binding SaveCommand}"
b:Overlay.InitialFocus="{Binding #IncidentDataKeywordBox}">
<Border x:Name="IncidentDataDialogCard" MaxWidth="480" VerticalAlignment="Center" HorizontalAlignment="Stretch"
Background="{StaticResource SurfaceRaisedBrush}"
BorderBrush="{StaticResource HairlineBrush}" BorderThickness="1"
Expand Down
Loading
Loading