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
47 changes: 47 additions & 0 deletions windows/src/GoalMaker.App/Controls/KeyboardSpot.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
namespace GoalMaker.App.Controls;

/// <summary>
/// Where the keyboard was in a list that is redrawn from new rows (the Focus Board, its add panel): the
/// row's id, its place and which part of the row. A redraw drops the element that had the keyboard, so
/// the page puts it back on the same row, or on the row now in its place when that one has gone.
/// Forgotten once the keyboard leaves the list, so a later redraw (a sync) does not pull it back.
/// </summary>
public sealed class KeyboardSpot
{
private string? id;
private int index;

/// <summary>Which part of the row had the keyboard, by its element name.</summary>
public string Part { get; private set; } = string.Empty;

public bool IsSet => id is not null;

public void Remember(string rowId, int rowIndex, string part)
{
id = rowId;
index = Math.Max(rowIndex, 0);
Part = part;
}

public void Forget()
{
id = null;
Part = string.Empty;
}

/// <summary>
/// The place in <paramref name="ids"/> to put the keyboard back on: the same row if it is still there,
/// else the one now in its place (the last when it was the end). Null when nothing is remembered or the
/// list is empty.
/// </summary>
public int? Pick(IReadOnlyList<string> ids)
{
if (id is null || ids.Count == 0) return null;
for (var i = 0; i < ids.Count; i++)
{
if (ids[i] == id) return i;
}

return Math.Min(index, ids.Count - 1);
}
}
2 changes: 1 addition & 1 deletion windows/src/GoalMaker.App/Resources/Strings.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -1417,7 +1417,7 @@
<sys:String x:Key="Focus.MoveUp">Move up (Alt+Up)</sys:String>
<sys:String x:Key="Focus.MoveDown">Move down (Alt+Down)</sys:String>
<sys:String x:Key="Focus.Late">Late</sys:String>
<sys:String x:Key="Focus.QuickAddPlaceholder">Add a task to the board, like "Hand in the form @School friday"</sys:String>
<sys:String x:Key="Focus.QuickAddPlaceholder">New task, like "Hand in the form @School friday"</sys:String>
<sys:String x:Key="Focus.Search">Search open tasks</sys:String>
<sys:String x:Key="Focus.NoMatch">No open task matches.</sys:String>
<sys:String x:Key="Focus.FilteredEmpty">Nothing on the board matches the filter.</sys:String>
Expand Down
6 changes: 5 additions & 1 deletion windows/src/GoalMaker.App/ViewModels/FocusAddRowViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,16 @@ public sealed class FocusAddRowViewModel

public bool HasSubtitle => Subtitle.Length > 0;

public FocusAddRowViewModel(TaskItem task, AreaItem? area, DateOnly today, Brush? areaBrush = null)
/// <summary>What Narrator reads after the title: "Late" first for a late task, then the date and area.</summary>
public string HelpText { get; }

public FocusAddRowViewModel(TaskItem task, AreaItem? area, DateOnly today, string lateLabel, Brush? areaBrush = null)
{
Id = task.Id;
Title = task.Title;
(DateText, IsLate) = FocusDate.For(task, today);
AreaName = area?.Name;
AreaBrush = areaBrush;
HelpText = FocusDate.HelpText(Subtitle, IsLate, lateLabel);
}
}
4 changes: 4 additions & 0 deletions windows/src/GoalMaker.App/ViewModels/FocusDate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,8 @@ public static (string Text, bool IsLate) For(TaskItem task, DateOnly today) =>
(task.Deadline ?? task.PlannedDate) is { } date
? (date.ToString("d MMM", CultureInfo.CurrentCulture), date < today)
: (string.Empty, false);

/// <summary>The help text a screen reader gets for a row: the late mark is otherwise only a color and an icon.</summary>
public static string HelpText(string subtitle, bool isLate, string lateLabel) =>
isLate ? string.Join(" · ", new[] { lateLabel, subtitle }.Where(part => part.Length > 0)) : subtitle;
}
16 changes: 14 additions & 2 deletions windows/src/GoalMaker.App/ViewModels/FocusRowViewModel.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Windows.Media;
using CommunityToolkit.Mvvm.ComponentModel;
using GoalMaker.Core.Planning;

namespace GoalMaker.App.ViewModels;
Expand All @@ -7,7 +8,7 @@ namespace GoalMaker.App.ViewModels;
/// One row on the Focus Board: its place as shown (1 at the top), the title, and a line with the date
/// (the deadline, else the planned day; late ones in the danger color) and the area with its color.
/// </summary>
public sealed class FocusRowViewModel
public sealed partial class FocusRowViewModel : ObservableObject
{
public string Id { get; }
public string Title { get; }
Expand Down Expand Up @@ -39,7 +40,17 @@ public sealed class FocusRowViewModel

public bool HasSubtitle => Subtitle.Length > 0;

public FocusRowViewModel(TaskItem task, AreaItem? area, DateOnly today, int place = 1, int count = 1, Brush? areaBrush = null)
/// <summary>What Narrator reads after the title: "Late" first for a late task, then the date and area.</summary>
public string HelpText { get; }

/// <summary>
/// The done box. Ticking it completes the task, which leaves the board; when the task stays open (a
/// repeating one moving on, a change that did nothing) the view model unticks it again.
/// </summary>
[ObservableProperty]
private bool isDone;

public FocusRowViewModel(TaskItem task, AreaItem? area, DateOnly today, int place, int count, string lateLabel, Brush? areaBrush = null)
{
Id = task.Id;
Title = task.Title;
Expand All @@ -50,5 +61,6 @@ public FocusRowViewModel(TaskItem task, AreaItem? area, DateOnly today, int plac
(DateText, IsLate) = FocusDate.For(task, today);
AreaName = area?.Name;
AreaBrush = areaBrush;
HelpText = FocusDate.HelpText(Subtitle, IsLate, lateLabel);
}
}
7 changes: 5 additions & 2 deletions windows/src/GoalMaker.App/ViewModels/FocusViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -144,13 +144,13 @@ private void Refresh()
private FocusRowViewModel Row(TaskItem task, Dictionary<string, AreaItem> areaMap, DateOnly today, int place, int count)
{
var area = areaMap.GetValueOrDefault(task.AreaId ?? "");
return new FocusRowViewModel(task, area, today, place, count, area is null ? null : areaBrush(area.ColorId));
return new FocusRowViewModel(task, area, today, place, count, strings.Get("Focus.Late"), area is null ? null : areaBrush(area.ColorId));
}

private FocusAddRowViewModel Candidate(TaskItem task, Dictionary<string, AreaItem> areaMap, DateOnly today)
{
var area = areaMap.GetValueOrDefault(task.AreaId ?? "");
return new FocusAddRowViewModel(task, area, today, area is null ? null : areaBrush(area.ColorId));
return new FocusAddRowViewModel(task, area, today, strings.Get("Focus.Late"), area is null ? null : areaBrush(area.ColorId));
}

private IReadOnlyList<TaskItem> Narrow(IReadOnlyList<TaskItem> found) =>
Expand Down Expand Up @@ -179,6 +179,9 @@ private void Complete(FocusRowViewModel? row)
{
if (row is null) return;
tasks.SetDone(row.Id, true);

// Not done after all (a repeating task moved on, or nothing changed): the box must not stay ticked.
if (!tasks.All().Any(task => task.Id == row.Id && task.State == TaskState.Done)) row.IsDone = false;
}

[RelayCommand]
Expand Down
5 changes: 3 additions & 2 deletions windows/src/GoalMaker.App/Views/FocusPage.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -242,11 +242,12 @@
Foreground="{DynamicResource GM.AccentBrush}" />
<CheckBox x:Name="Done" Grid.Column="1" TabIndex="0" VerticalAlignment="Center"
Foreground="{DynamicResource GM.TextBrush}"
IsChecked="{Binding IsDone}"
Command="{Binding DataContext.CompleteCommand, ElementName=BoardRows}"
CommandParameter="{Binding}"
ToolTip="{DynamicResource Focus.Complete}"
AutomationProperties.Name="{Binding Title}"
AutomationProperties.HelpText="{Binding Subtitle}">
AutomationProperties.HelpText="{Binding HelpText}">
<StackPanel>
<TextBlock Text="{Binding Title}" FontSize="14" TextWrapping="Wrap" />
<ContentControl Focusable="False" Content="{Binding}" ContentTemplate="{StaticResource FocusDetails}" />
Expand Down Expand Up @@ -379,7 +380,7 @@
CommandParameter="{Binding}"
ToolTip="{DynamicResource Focus.AddToBoard}"
AutomationProperties.Name="{Binding Title}"
AutomationProperties.HelpText="{DynamicResource Focus.AddToBoard}">
AutomationProperties.HelpText="{Binding HelpText}">
<DockPanel>
<ui:SymbolIcon DockPanel.Dock="Right" Margin="8,0,0,0" VerticalAlignment="Center"
Symbol="Add24" Foreground="{DynamicResource GM.AccentBrush}" />
Expand Down
104 changes: 81 additions & 23 deletions windows/src/GoalMaker.App/Views/FocusPage.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,36 @@
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using GoalMaker.App.Controls;
using GoalMaker.App.ViewModels;

namespace GoalMaker.App.Views;

/// <summary>
/// The Focus Board. Behavior is in <see cref="FocusViewModel"/>; this only moves the keyboard: Ctrl+N to the
/// quick add field, Ctrl+F to the search box, Alt+Up and Alt+Down on a row, and back onto a row after the
/// board is redrawn (a move, a completion), since the redraw drops the element that had the keyboard.
/// quick add field, Ctrl+F to the search box, Alt+Up and Alt+Down on a row, Esc back to the board from the
/// add panel, and back onto a row after the board or the add panel is redrawn (a move, a completion, an
/// add), since the redraw drops the element that had the keyboard.
/// </summary>
public partial class FocusPage
{
private readonly FocusViewModel viewModel;

// Where the keyboard was on the board: the row's task, its place and which part of it.
private string? keyboardRowId;
private int keyboardRowIndex;
private string keyboardPart = "Done";
private WeakReference<UIElement>? keyboardElement;
private readonly KeyboardSpot boardSpot = new();
private readonly KeyboardSpot candidateSpot = new();
private WeakReference<UIElement>? boardElement;
private WeakReference<UIElement>? candidateElement;

public FocusPage(FocusViewModel viewModel)
{
InitializeComponent();
this.viewModel = viewModel;
DataContext = viewModel;
PreviewKeyDown += OnPreviewKeyDown;
KeyDown += OnKeyDown;
BoardRows.PreviewGotKeyboardFocus += OnBoardGotKeyboardFocus;
BoardRows.PreviewLostKeyboardFocus += (_, e) => ForgetWhenLeaving(BoardRows, boardSpot, e);
Candidates.PreviewGotKeyboardFocus += OnCandidateGotKeyboardFocus;
Candidates.PreviewLostKeyboardFocus += (_, e) => ForgetWhenLeaving(Candidates, candidateSpot, e);
viewModel.PropertyChanged += OnViewModelChanged;
Unloaded += (_, _) => viewModel.PropertyChanged -= OnViewModelChanged;
Loaded += (_, _) =>
Expand Down Expand Up @@ -65,41 +69,95 @@ private void OnPreviewKeyDown(object sender, KeyEventArgs e)
}
}

// Esc anywhere on the page while the add panel is open goes back to the board. The search box's own Esc
// (clear what is typed first) and an open drop-down handle theirs before this sees it.
private void OnKeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Escape || Keyboard.Modifiers != ModifierKeys.None || !viewModel.IsAddOpen) return;
viewModel.CloseAddDialogCommand.Execute(null);
e.Handled = true;
}

private void OnBoardGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
if (e.NewFocus is not FrameworkElement element || element.DataContext is not FocusRowViewModel row) return;
keyboardRowId = row.Id;
keyboardRowIndex = viewModel.Items.IndexOf(row);
keyboardPart = element.Name is "Up" or "Down" or "Off" ? element.Name : "Done";
keyboardElement = new WeakReference<UIElement>(element);
boardSpot.Remember(row.Id, viewModel.Items.IndexOf(row), element.Name is "Up" or "Down" or "Off" ? element.Name : "Done");
boardElement = new WeakReference<UIElement>(element);
}

private void OnCandidateGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
if (e.NewFocus is not FrameworkElement element || element.DataContext is not FocusAddRowViewModel row) return;
candidateSpot.Remember(row.Id, viewModel.Candidates.IndexOf(row), "Add");
candidateElement = new WeakReference<UIElement>(element);
}

// The keyboard went to something else on show (not nowhere, as when its row is redrawn): forget the row,
// so a later redraw, such as a sync, does not pull the keyboard back onto it.
private void ForgetWhenLeaving(ItemsControl list, KeyboardSpot spot, KeyboardFocusChangedEventArgs e)
{
if (e.NewFocus is UIElement next and not Window && next != this && next.IsVisible && !list.IsAncestorOf(next))
{
spot.Forget();
}
}

private void OnViewModelChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName != nameof(FocusViewModel.Items) || keyboardRowId is null) return;
Dispatcher.BeginInvoke(DispatcherPriority.Loaded, RestoreKeyboard);
if (e.PropertyName == nameof(FocusViewModel.Items) && boardSpot.IsSet)
{
Dispatcher.BeginInvoke(DispatcherPriority.Loaded, RestoreBoard);
}
else if (e.PropertyName == nameof(FocusViewModel.Candidates) && candidateSpot.IsSet)
{
Dispatcher.BeginInvoke(DispatcherPriority.Loaded, RestoreCandidate);
}
}

// Once the board is redrawn: if the keyboard was on a row that is gone and has not moved on to anything
// else on show, put it on the same task (moved), or on the row now in its place (completed or taken off).
private void RestoreKeyboard()
// Whether the keyboard was dropped by a redraw: the element that had it is gone, and it has not moved on
// to anything else on show.
private bool WasDropped(WeakReference<UIElement>? had)
{
if (keyboardElement is null || !keyboardElement.TryGetTarget(out var before) || before.IsVisible) return;
if (had is null || !had.TryGetTarget(out var before) || before.IsVisible) return false;
var now = Keyboard.FocusedElement as UIElement;
if (now is not null and not Window && now.IsVisible && now != this) return;
return now is null or Window || !now.IsVisible || now == this;
}

// Puts the keyboard on the same task (moved), or on the row now in its place (completed or taken off).
private void RestoreBoard()
{
if (!WasDropped(boardElement)) return;
var items = viewModel.Items;
if (items.Count == 0)
if (boardSpot.Pick([.. items.Select(item => item.Id)]) is not { } index)
{
QuickAddBox.Focus();
return;
}

var row = items.FirstOrDefault(item => item.Id == keyboardRowId) ?? items[Math.Clamp(keyboardRowIndex, 0, items.Count - 1)];
if (BoardRows.ItemContainerGenerator.ContainerFromItem(row) is not ContentPresenter presenter) return;
if (BoardRows.ItemContainerGenerator.ContainerFromItem(items[index]) is not ContentPresenter presenter) return;
presenter.ApplyTemplate();
var template = presenter.ContentTemplate;
var target = template?.FindName(keyboardPart, presenter) as UIElement;
var target = template?.FindName(boardSpot.Part, presenter) as UIElement;
if (target is null || !target.IsEnabled || target.Visibility != Visibility.Visible) target = template?.FindName("Done", presenter) as UIElement;
target?.Focus();
}

// After an add from the panel: the next task offered in its place, or the search box when none is left.
private void RestoreCandidate()
{
if (!WasDropped(candidateElement)) return;
var rows = viewModel.Candidates;
if (candidateSpot.Pick([.. rows.Select(row => row.Id)]) is { } index
&& Candidates.ItemContainerGenerator.ContainerFromItem(rows[index]) is ContentPresenter presenter
&& System.Windows.Media.VisualTreeHelper.GetChildrenCount(presenter) > 0
&& System.Windows.Media.VisualTreeHelper.GetChild(presenter, 0) is UIElement button
&& button.IsVisible)
{
button.Focus();
return;
}

candidateSpot.Forget();
if (SearchBox.IsVisible) SearchBox.Focus();
}
}
52 changes: 52 additions & 0 deletions windows/tests/GoalMaker.App.Tests/FocusViewModelTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -210,4 +210,56 @@ public void WithNoOpenTasksTheAddPanelSaysSoInsteadOfAllOnTheBoard()
Assert.False(page.HasNoOpenTasks);
Assert.True(page.IsAllOnBoard);
}

[Fact]
public void ALateRowSaysLateToAScreenReaderNotOnlyInColor()
{
var late = planner.Tasks.Add("Hand in the form @School")!;
planner.Tasks.SetDeadline(late.Id, new DateOnly(2026, 9, 16));
var other = planner.Tasks.Add("Renew the card")!;
planner.Tasks.SetDeadline(other.Id, new DateOnly(2026, 9, 10));
var page = Page();
page.AddToBoardCommand.Execute(page.Candidates.Single(row => row.Id == late.Id));

var row = page.Items.Single();
Assert.StartsWith("Focus.Late · ", row.HelpText);
Assert.EndsWith(row.Subtitle, row.HelpText);
Assert.StartsWith("Focus.Late · ", page.Candidates.Single().HelpText);
}

[Fact]
public void ARowThatIsNotLateReadsItsDateAndArea()
{
var page = Page();
page.QuickAddTitle = "Hand in the form @School";
page.QuickAddCommand.Execute(null);
Assert.Equal("School", page.Items.Single().HelpText);
}

[Fact]
public void TheDoneBoxUnticksWhenTheTaskStaysOpen()
{
var page = Page();
page.QuickAddTitle = "Hand in the form";
page.QuickAddCommand.Execute(null);
// A row for a task the store does not know: completing it changes nothing, so the box must not stay ticked.
var row = new FocusRowViewModel(planner.Task("Hand in the form") with { Id = "not-in-the-store" }, null, new DateOnly(2026, 9, 18), 1, 1, "Late");
row.IsDone = true;
page.CompleteCommand.Execute(row);
Assert.False(row.IsDone);
}

[Fact]
public void TickingTheDoneBoxCompletesTheTaskAndTakesItOffTheBoard()
{
var page = Page();
page.QuickAddTitle = "Hand in the form";
page.QuickAddCommand.Execute(null);
var row = page.Items.Single();

row.IsDone = true;
page.CompleteCommand.Execute(row);
Assert.Empty(page.Items);
Assert.Equal(TaskState.Done, planner.Tasks.All().Single().State);
}
}
Loading