using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Chronos.App.Archiving;
namespace Chronos.App.Sections;
public partial class ArchiveView : UserControl
{
private bool _restoring;
private string? _focusKey;
private IInputElement? _beforeDialog;
public ArchiveView()
{
InitializeComponent();
DataContextChanged += OnDataContextChanged;
Tree.GotKeyboardFocus += (_, e) =>
{
if (e.NewFocus is ListBoxItem { DataContext: ArchiveTreeRowViewModel row }) _focusKey = row.Node.Key;
};
}
private ArchiveViewModel? Model => DataContext as ArchiveViewModel;
/// "Adopt folder ▾", "Maintenance ▾" and the set filter open their menu under themselves.
private void OnOpenMenu(object sender, RoutedEventArgs e)
{
if (sender is not Button { ContextMenu: { } menu } button) return;
menu.DataContext = DataContext;
menu.PlacementTarget = button;
menu.Placement = PlacementMode.Bottom;
menu.IsOpen = true;
}
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (e.OldValue is ArchiveViewModel old)
{
old.RowsRebuilt -= RestoreSelection;
old.PropertyChanged -= OnModelChanged;
}
if (e.NewValue is ArchiveViewModel model)
{
model.RowsRebuilt += RestoreSelection;
model.PropertyChanged += OnModelChanged;
}
}
/// The selected tree rows are the set the mass operations act on.
private void OnTreeSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (!_restoring) Model?.SetSelection(Tree.SelectedItems.OfType());
}
/// The rows were rebuilt (a reload, a year opened or closed): the list shows the same selection and keeps the keyboard where it was.
private void RestoreSelection()
{
if (Model is not { } model) return;
// The rebuild removed the focused row's container; the keyboard goes back to the row with the same key.
var refocus = Tree.IsKeyboardFocusWithin || Keyboard.FocusedElement is null ? _focusKey : null;
_restoring = true;
try
{
Tree.SelectedItems.Clear();
foreach (var row in model.TreeRows.Where(model.IsSelectedRow)) Tree.SelectedItems.Add(row);
}
finally
{
_restoring = false;
}
if (refocus is null || model.TreeRows.FirstOrDefault(r => r.Node.Key == refocus) is not { } again) return;
Dispatcher.BeginInvoke(DispatcherPriority.Input, () =>
{
Tree.ScrollIntoView(again);
(Tree.ItemContainerGenerator.ContainerFromItem(again) as ListBoxItem)?.Focus();
});
}
private void OnTreeKeyDown(object sender, KeyEventArgs e)
{
if (Model is not { } model || Keyboard.FocusedElement is not ListBoxItem { DataContext: ArchiveTreeRowViewModel row } || !row.HasChildren || row.IsArchive) return;
if (!Toggles(e.Key, Tree.FlowDirection, row.IsExpanded)) return;
model.Toggle(row);
e.Handled = true;
}
///
/// Whether opens or closes a year: the arrow towards the indented side opens it (Right, or
/// Left in a right-to-left layout, as a tree view does), the other arrow closes it, Enter toggles it.
///
internal static bool Toggles(Key key, FlowDirection direction, bool isExpanded)
{
var (open, close) = direction == FlowDirection.RightToLeft ? (Key.Left, Key.Right) : (Key.Right, Key.Left);
return key == open ? !isExpanded
: key == close ? isExpanded
: key == Key.Enter;
}
///
/// A dialog that opens takes the keyboard (its first field or button); when it closes, the keyboard goes back to the
/// control that opened it, or to the tree when that control can no longer take it.
///
private void OnModelChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName != nameof(ArchiveViewModel.Dialog) || Model is not { } model) return;
if (model.Dialog is not null)
{
if (!IsVisible) return;
// Raised before the screen behind the dialog is disabled: the control that opened it still has the keyboard.
_beforeDialog ??= Keyboard.FocusedElement is Visual focused && IsAncestorOf(focused) ? Keyboard.FocusedElement : null;
Dispatcher.BeginInvoke(DispatcherPriority.Input, () => DialogHost.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)));
return;
}
var back = _beforeDialog;
_beforeDialog = null;
if (!IsVisible) return;
Dispatcher.BeginInvoke(DispatcherPriority.Input, () =>
{
if (back is UIElement { IsVisible: true, IsEnabled: true, Focusable: true } element && element.Focus()) return;
Tree.Focus();
});
}
}