Fixed the caching issue that causes mails to be not removed. Improved drag/drop.

This commit is contained in:
Burak Kaan Köse
2026-02-11 11:34:50 +01:00
parent 52ee5f1d8a
commit 37199d84cb
8 changed files with 347 additions and 169 deletions
@@ -484,6 +484,7 @@
"MailOperation_Unarchive": "Unarchive",
"MailOperation_ViewMessageSource": "View message source",
"MailOperation_Zoom": "Zoom",
"MailsDragging": "Dragging {0} item(s)",
"MailsSelected": "{0} item(s) selected",
"MarkFlagUnflag": "Mark as flagged/unflagged",
"MarkReadUnread": "Mark as read/unread",
@@ -233,6 +233,11 @@ public class WinoMailCollection : ObservableRecipient, IRecipient<SelectedItemsC
return !string.IsNullOrEmpty(threadId) && _threadIdToItemsMap.ContainsKey(threadId);
}
/// <summary>
/// Checks whether a mail with the given UniqueId currently exists in this collection.
/// </summary>
public bool ContainsMailUniqueId(Guid uniqueId) => MailCopyIdHashSet.ContainsKey(uniqueId);
/// <summary>
/// Finds a MailItemViewModel by its UniqueId, searching through all items including those inside threads.
/// </summary>
@@ -443,10 +448,17 @@ public class WinoMailCollection : ObservableRecipient, IRecipient<SelectedItemsC
{
// Try cache first
if (_itemToGroupMap.TryGetValue(item, out var cachedGroup))
{
// Cache can become stale during concurrent list refreshes/moves.
// Validate before returning so we don't mutate a detached group.
if (_mailItemSource.Contains(cachedGroup) && cachedGroup.Contains(item))
{
return cachedGroup;
}
_itemToGroupMap.TryRemove(item, out _);
}
// Fallback to search if not in cache
foreach (var group in _mailItemSource)
{
@@ -487,6 +499,8 @@ public class WinoMailCollection : ObservableRecipient, IRecipient<SelectedItemsC
{
MailCopyIdHashSet.Clear();
_threadIdToItemsMap.Clear();
_itemToGroupMap.Clear();
_uniqueIdToMailItemMap.Clear();
_uniqueIdToThreadMap.Clear();
}
@@ -741,9 +755,6 @@ public class WinoMailCollection : ObservableRecipient, IRecipient<SelectedItemsC
/// <returns></returns>
public Task UpdateMailCopy(MailCopy updatedMailCopy, MailUpdateSource mailUpdateSource)
{
// This item doesn't exist in the list.
if (!MailCopyIdHashSet.ContainsKey(updatedMailCopy.UniqueId)) return Task.CompletedTask;
return ExecuteUIThread(() =>
{
var itemContainer = GetMailItemContainer(updatedMailCopy.UniqueId);
@@ -762,6 +773,12 @@ public class WinoMailCollection : ObservableRecipient, IRecipient<SelectedItemsC
itemContainer.ItemViewModel.IsBusy = mailUpdateSource == MailUpdateSource.ClientUpdated;
UpdateUniqueIdHashes(itemContainer.ItemViewModel, true);
// Keep thread membership cache in sync for items rendered inside thread containers.
if (itemContainer.ThreadViewModel != null)
{
_uniqueIdToThreadMap[itemContainer.ItemViewModel.MailCopy.UniqueId] = itemContainer.ThreadViewModel;
}
}
// Trigger thread property notifications if this item is in a thread
@@ -836,17 +853,19 @@ public class WinoMailCollection : ObservableRecipient, IRecipient<SelectedItemsC
public async Task RemoveAsync(MailCopy removeItem)
{
// This item doesn't exist in the list.
if (!MailCopyIdHashSet.ContainsKey(removeItem.UniqueId)) return;
var itemContainer = GetMailItemContainer(removeItem.UniqueId);
if (_uniqueIdToThreadMap.TryGetValue(removeItem.UniqueId, out var threadMailItemViewModel))
// This item doesn't exist in the list.
if (itemContainer?.ItemViewModel == null) return;
if (itemContainer.ThreadViewModel != null)
{
// Item is inside a thread - use cached lookups instead of scanning all groups.
var threadMailItemViewModel = itemContainer.ThreadViewModel;
var group = FindGroupContainingItem(threadMailItemViewModel);
if (group == null) return;
var removalItem = threadMailItemViewModel.ThreadEmails.FirstOrDefault(e => e.MailCopy.UniqueId == removeItem.UniqueId);
if (removalItem == null) return;
var removalItem = itemContainer.ItemViewModel;
// Update ThreadId cache before modifying the thread
UpdateThreadIdCache(threadMailItemViewModel, false);
@@ -889,36 +908,11 @@ public class WinoMailCollection : ObservableRecipient, IRecipient<SelectedItemsC
}
else
{
// Standalone item - use cached lookup.
IMailListItem mailItem = null;
ObservableGroup<object, IMailListItem> group = null;
// Standalone item.
IMailListItem mailItem = itemContainer.ItemViewModel;
var group = FindGroupContainingItem(mailItem);
if (_uniqueIdToMailItemMap.TryGetValue(removeItem.UniqueId, out var cachedItem))
{
mailItem = cachedItem;
group = FindGroupContainingItem(mailItem);
}
// Fallback to scan if not in cache
if (mailItem == null || group == null)
{
for (int i = 0; i < _mailItemSource.Count; i++)
{
var g = _mailItemSource[i];
for (int k = 0; k < g.Count; k++)
{
if (g[k] is MailItemViewModel mvm && mvm.MailCopy.UniqueId == removeItem.UniqueId)
{
mailItem = mvm;
group = g;
break;
}
}
if (mailItem != null) break;
}
}
if (mailItem != null && group != null)
if (group != null)
{
await RemoveItemInternalAsync(group, mailItem);
}
+46 -12
View File
@@ -99,6 +99,16 @@ public partial class MailListPageViewModel : MailBaseViewModel,
[ObservableProperty]
private bool isMultiSelectionModeEnabled;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(SelectedMessageText))]
[NotifyPropertyChangedFor(nameof(DraggingMessageText))]
public partial bool IsDragInProgress { get; set; }
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(SelectedMessageText))]
[NotifyPropertyChangedFor(nameof(DraggingMessageText))]
public partial int DraggingItemsCount { get; set; }
[ObservableProperty]
public partial string SearchQuery { get; set; }
@@ -291,7 +301,13 @@ public partial class MailListPageViewModel : MailBaseViewModel,
public bool IsFolderSynchronizationEnabled => ActiveFolder?.IsSynchronizationEnabled ?? false;
public bool IsArchiveSpecialFolder => ActiveFolder?.SpecialFolderType == SpecialFolderType.Archive;
public string SelectedMessageText => MailCollection.SelectedItemsCount > 0 ? string.Format(Translator.MailsSelected, MailCollection.SelectedItemsCount) : Translator.NoMailSelected;
public string SelectedMessageText => IsDragInProgress
? string.Format(Translator.MailsDragging, DraggingItemsCount)
: MailCollection.SelectedItemsCount > 0
? string.Format(Translator.MailsSelected, MailCollection.SelectedItemsCount)
: Translator.NoMailSelected;
public string DraggingMessageText => string.Format(Translator.MailsDragging, DraggingItemsCount);
/// <summary>
/// Indicates current state of the mail list. Doesn't matter it's loading or no.
@@ -361,6 +377,12 @@ public partial class MailListPageViewModel : MailBaseViewModel,
SelectedFolderPivot?.SelectedItemCount = MailCollection.SelectedItemsCount;
}
public void SetDragState(bool isDragInProgress, int draggingItemsCount = 0)
{
IsDragInProgress = isDragInProgress;
DraggingItemsCount = isDragInProgress ? Math.Max(1, draggingItemsCount) : 0;
}
private void NotifyItemFoundState()
{
OnPropertyChanged(nameof(IsEmpty));
@@ -718,7 +740,15 @@ public partial class MailListPageViewModel : MailBaseViewModel,
{
base.OnMailUpdated(updatedMail, source);
try
{
await listManipulationSemepahore.WaitAsync();
await MailCollection.UpdateMailCopy(updatedMail, source);
}
finally
{
listManipulationSemepahore.Release();
}
// await ExecuteUIThread(() => { SetupTopBarActions(); });
}
@@ -727,22 +757,21 @@ public partial class MailListPageViewModel : MailBaseViewModel,
{
base.OnMailRemoved(removedMail);
if (removedMail.AssignedAccount == null || removedMail.AssignedFolder == null) return;
if (removedMail.AssignedAccount == null) return;
// We should delete the items only if:
// 1. They are deleted from the active folder.
// 2. Deleted from draft or sent folder.
// 3. Removal is not caused by Gmail Unread folder action.
// Delete/sent are special folders that can list their items in other folders.
try
{
await listManipulationSemepahore.WaitAsync();
bool removedFromActiveFolder = ActiveFolder.HandlingFolders.Any(a => a.Id == removedMail.AssignedFolder.Id);
bool removedFromDraftOrSent = removedMail.AssignedFolder.SpecialFolderType == SpecialFolderType.Draft ||
removedMail.AssignedFolder.SpecialFolderType == SpecialFolderType.Sent;
// Remove only if this specific mail copy currently exists in this list.
// Using AssignedFolder-based checks is unreliable for move flows because the
// same MailCopy instance can be updated before this message is handled.
bool removedItemExistsInCurrentList = MailCollection.ContainsMailUniqueId(removedMail.UniqueId);
bool isDeletedByGmailUnreadFolderAction = ActiveFolder.SpecialFolderType == SpecialFolderType.Unread &&
bool isDeletedByGmailUnreadFolderAction = ActiveFolder?.SpecialFolderType == SpecialFolderType.Unread &&
gmailUnreadFolderMarkedAsReadUniqueIds.Contains(removedMail.UniqueId);
if ((removedFromActiveFolder || removedFromDraftOrSent) && !isDeletedByGmailUnreadFolderAction)
if (removedItemExistsInCurrentList && !isDeletedByGmailUnreadFolderAction)
{
bool isDeletedMailSelected = MailCollection.SelectedItems.Any(a => a.MailCopy.UniqueId == removedMail.UniqueId);
@@ -779,6 +808,11 @@ public partial class MailListPageViewModel : MailBaseViewModel,
gmailUnreadFolderMarkedAsReadUniqueIds.Remove(removedMail.UniqueId);
}
}
finally
{
listManipulationSemepahore.Release();
}
}
protected override async void OnFolderDeleted(MailItemFolder folder)
{
@@ -1,10 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using CommunityToolkit.WinUI;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Wino.Core.Domain;
using Wino.Core.Domain.Models.MailItem;
using Wino.Mail.ViewModels.Data;
@@ -21,12 +23,16 @@ public partial class WinoListView : Microsoft.UI.Xaml.Controls.ListView
[GeneratedDependencyProperty]
public partial ICommand? LoadMoreCommand { get; set; }
public event EventHandler<MailDragStateChangedEventArgs>? MailDragStateChanged;
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
DragItemsStarting += ItemDragStarting;
DragItemsStarting -= ItemDragStarting;
DragItemsStarting += ItemDragStarting;
DragItemsCompleted -= ItemDragCompleted;
DragItemsCompleted += ItemDragCompleted;
internalScrollviewer = GetTemplateChild(PART_ScrollViewer) as ScrollViewer;
@@ -222,6 +228,7 @@ public partial class WinoListView : Microsoft.UI.Xaml.Controls.ListView
public void Cleanup()
{
DragItemsStarting -= ItemDragStarting;
DragItemsCompleted -= ItemDragCompleted;
if (internalScrollviewer != null)
{
@@ -236,20 +243,99 @@ public partial class WinoListView : Microsoft.UI.Xaml.Controls.ListView
// Meaning that if users drag 1 mail from Account A/Inbox and 1 mail from Account B/Inbox,
// and drop to Account A/Inbox, the mail from Account B/Inbox will NOT be moved.
var itemsToDrag = ResolveDraggedMailItems(args);
if (itemsToDrag.Count == 0)
{
return;
}
var dragPackage = new MailDragPackage(itemsToDrag.Cast<object>());
args.Data.Properties.Add(nameof(MailDragPackage), dragPackage);
var draggingText = string.Format(Translator.MailsDragging, itemsToDrag.Count);
args.Data.SetText(draggingText);
args.Data.Properties.Title = draggingText;
// args.DragUI.SetContentFromDataPackage();
MailDragStateChanged?.Invoke(this, new MailDragStateChangedEventArgs(true, itemsToDrag.Count));
}
private void ItemDragCompleted(ListViewBase sender, DragItemsCompletedEventArgs args)
{
MailDragStateChanged?.Invoke(this, new MailDragStateChangedEventArgs(false, 0));
}
private List<MailItemViewModel> ResolveDraggedMailItems(DragItemsStartingEventArgs args)
{
var draggedItems = ExpandDragItems(args.Items.Cast<object>());
var selectedItems = GetSelectedMailItemsFromCurrentList();
if (selectedItems.Count > 1)
{
var selectedIds = selectedItems.Select(a => a.UniqueId).ToHashSet();
bool dragStartedFromSelection = draggedItems.Any(a => selectedIds.Contains(a.UniqueId));
if (dragStartedFromSelection)
{
return selectedItems;
}
}
return draggedItems.Count > 0 ? draggedItems : selectedItems;
}
private List<MailItemViewModel> GetSelectedMailItemsFromCurrentList()
{
if (IsThreadListView)
{
var allItems = args.Items.Cast<MailItemViewModel>();
// Set native drag arg properties.
var dragPackage = new MailDragPackage(allItems.Cast<IMailListItem>());
args.Data.Properties.Add(nameof(MailDragPackage), dragPackage);
return Items
.Cast<object>()
.OfType<MailItemViewModel>()
.Where(a => a.IsSelected)
.GroupBy(a => a.UniqueId)
.Select(a => a.First())
.ToList();
}
else
return Items
.Cast<object>()
.OfType<IMailListItem>()
.SelectMany(a => a.GetSelectedMailItems())
.GroupBy(a => a.UniqueId)
.Select(a => a.First())
.ToList();
}
private static List<MailItemViewModel> ExpandDragItems(IEnumerable<object> dragItems)
{
var dragPackage = new MailDragPackage(args.Items.Cast<IMailListItem>());
var result = new List<MailItemViewModel>();
args.Data.Properties.Add(nameof(MailDragPackage), dragPackage);
foreach (var dragItem in dragItems)
{
if (dragItem is MailItemViewModel mailItem)
{
result.Add(mailItem);
}
else if (dragItem is ThreadMailItemViewModel threadItem)
{
result.AddRange(threadItem.ThreadEmails);
}
else if (dragItem is IMailListItem mailListItem)
{
result.AddRange(mailListItem.GetSelectedMailItems());
}
}
return result
.GroupBy(a => a.UniqueId)
.Select(a => a.First())
.ToList();
}
}
public sealed class MailDragStateChangedEventArgs(bool isDragging, int draggedItemCount) : EventArgs
{
public bool IsDragging { get; } = isDragging;
public int DraggedItemCount { get; } = draggedItemCount;
}
+1 -16
View File
@@ -62,7 +62,7 @@ public partial class WinoExpander : Control
clipComposition.Clip = clipComposition.Compositor.CreateInsetClip();
ContentAreaWrapper.SizeChanged += ContentSizeChanged;
HeaderGrid.Tapped += HeaderTapped;
}
private void ContentSizeChanged(object sender, SizeChangedEventArgs e)
@@ -71,21 +71,6 @@ public partial class WinoExpander : Control
TemplateSettings.NegativeContentHeight = -1 * (double)e.NewSize.Height;
}
private void HeaderTapped(object sender, Microsoft.UI.Xaml.Input.TappedRoutedEventArgs e)
{
// Tapped is delegated from executing hover action like flag or delete.
// No need to toggle the expander.
if (Header is MailItemDisplayInformationControl itemDisplayInformationControl &&
itemDisplayInformationControl.IsRunningHoverAction)
{
itemDisplayInformationControl.IsRunningHoverAction = false;
return;
}
// IsExpanded = !IsExpanded;
}
private static void OnIsExpandedChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
if (obj is WinoExpander control)
+27 -18
View File
@@ -64,28 +64,12 @@ public sealed partial class MailAppShell : MailAppShellAbstract,
{
if (droppedContainer.DataContext is IBaseFolderMenuItem draggingFolder)
{
var mailCopies = new List<MailCopy>();
var dragPackage = e.DataView.Properties[nameof(MailDragPackage)] as MailDragPackage;
if (dragPackage == null) return;
e.AcceptedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Move;
// Extract mail copies from IMailItem.
// ThreadViewModels will be divided into pieces.
foreach (var item in dragPackage.DraggingMails)
{
if (item is MailItemViewModel singleMailItemViewModel)
{
mailCopies.Add(singleMailItemViewModel.MailCopy);
}
else if (item is ThreadMailItemViewModel threadViewModel)
{
mailCopies.AddRange(threadViewModel.ThreadEmails.Select(a => a.MailCopy));
}
}
var mailCopies = ExtractMailCopies(dragPackage).ToList();
await ViewModel.PerformMoveOperationAsync(mailCopies, draggingFolder);
}
@@ -125,11 +109,36 @@ public sealed partial class MailAppShell : MailAppShellAbstract,
// Check whether the moving item's account has at least one same as the target folder's account.
var draggedAccountIds = folderMenuItem.HandlingFolders.Select(a => a.MailAccountId);
if (!dragPackage.DraggingMails.Cast<MailCopy>().Any(a => draggedAccountIds.Contains(a.AssignedAccount.Id))) return false;
var draggedMails = ExtractMailCopies(dragPackage);
if (!draggedMails.Any()) return false;
if (!draggedMails.Any(a => draggedAccountIds.Contains(a.AssignedAccount.Id))) return false;
return true;
}
private static IEnumerable<MailCopy> ExtractMailCopies(MailDragPackage dragPackage)
{
foreach (var item in dragPackage.DraggingMails)
{
if (item is MailCopy mailCopy)
{
yield return mailCopy;
}
else if (item is MailItemViewModel singleMailItemViewModel)
{
yield return singleMailItemViewModel.MailCopy;
}
else if (item is ThreadMailItemViewModel threadViewModel)
{
foreach (var threadMail in threadViewModel.ThreadEmails)
{
yield return threadMail.MailCopy;
}
}
}
}
private void ItemDragEnterOnFolder(object sender, DragEventArgs e)
{
// Validate package content.
+24 -1
View File
@@ -69,10 +69,14 @@
<controls:MailItemDisplayInformationControl
x:DefaultBindMode="OneWay"
ActionItem="{x:Bind}"
CanDrag="True"
ContextRequested="MailItemContextRequested"
DragStarting="ThreadHeaderDragStart"
DropCompleted="ThreadHeaderDragFinished"
HoverActionExecuted="MailItemDisplayInformationControl_HoverActionExecuted"
IsThreadExpanderVisible="True"
MailItemInformation="{x:Bind}" />
MailItemInformation="{x:Bind}"
Tapped="ThreadHeaderTapped" />
</controls:WinoExpander.Header>
<controls:WinoExpander.Content>
<listview:WinoListView
@@ -80,6 +84,7 @@
HorizontalContentAlignment="Stretch"
toolkitExt:ListViewExtensions.ItemContainerStretchDirection="Horizontal"
toolkitExt:ScrollViewerExtensions.VerticalScrollBarMargin="0"
CanDragItems="True"
ChoosingItemContainer="WinoListViewChoosingItemContainer"
IsItemClickEnabled="True"
IsThreadListView="True"
@@ -414,6 +419,24 @@
</listview:WinoListView.GroupStyle>
</listview:WinoListView>
<Border
x:Name="DraggingMessageBorder"
Grid.Row="0"
Margin="14"
Padding="10,6"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
x:Load="{x:Bind ViewModel.IsDragInProgress, Mode=OneWay}"
Background="{ThemeResource CardBackgroundFillColorDefaultBrush}"
BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"
BorderThickness="1"
CornerRadius="8">
<TextBlock
FontSize="12"
FontWeight="SemiBold"
Text="{x:Bind ViewModel.DraggingMessageText, Mode=OneWay}" />
</Border>
<!-- Try online search panel. -->
<Grid Grid.Row="1" Visibility="{x:Bind ViewModel.IsOnlineSearchButtonVisible, Mode=OneWay}">
<Button
+88 -42
View File
@@ -63,6 +63,7 @@ public sealed partial class MailListPage : MailListPageAbstract,
Bindings.Update();
ViewModel.MailCollection.ItemSelectionChanged += WinoMailCollectionSelectionChanged;
MailListView.MailDragStateChanged += MailListViewMailDragStateChanged;
UpdateSelectAllButtonStatus();
UpdateAdaptiveness();
@@ -82,8 +83,10 @@ public sealed partial class MailListPage : MailListPageAbstract,
this.Bindings.StopTracking();
ViewModel.MailCollection.ItemSelectionChanged -= WinoMailCollectionSelectionChanged;
MailListView.MailDragStateChanged -= MailListViewMailDragStateChanged;
SelectAllCheckbox.Checked -= SelectAllCheckboxChecked;
SelectAllCheckbox.Unchecked -= SelectAllCheckboxUnchecked;
ViewModel.SetDragState(false);
MailListView.Cleanup();
@@ -430,29 +433,51 @@ public sealed partial class MailListPage : MailListPageAbstract,
/// </summary>
private void ThreadHeaderDragStart(UIElement sender, DragStartingEventArgs args)
{
//if (sender is MailItemDisplayInformationControl control
// && control.ConnectedExpander?.Content is WinoListView contentListView)
//{
// var allItems = contentListView.Items.Where(a => a is MailCopy);
if (sender is MailItemDisplayInformationControl control && control.ActionItem is ThreadMailItemViewModel threadItem)
{
args.AllowedOperations = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Move;
// // Highlight all items.
// allItems.Cast<MailItemViewModel>().ForEach(a => a.IsCustomFocused = true);
// Dragging a thread header should move all mails in that thread.
var draggedThreadItems = threadItem.ThreadEmails.Cast<IMailListItem>().ToList();
var dragCount = draggedThreadItems.Count;
var draggingText = string.Format(Translator.MailsDragging, dragCount);
// // Set native drag arg properties.
// args.AllowedOperations = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Move;
ViewModel.SetDragState(true, dragCount);
// var dragPackage = new MailDragPackage(allItems.Cast<MailCopy>());
var dragPackage = new MailDragPackage(draggedThreadItems);
// args.Data.Properties.Add(nameof(MailDragPackage), dragPackage);
// args.DragUI.SetContentFromDataPackage();
// control.ConnectedExpander.IsExpanded = true;
//}
args.Data.Properties.Add(nameof(MailDragPackage), dragPackage);
args.Data.SetText(draggingText);
args.Data.Properties.Title = draggingText;
args.DragUI.SetContentFromDataPackage();
}
}
private void ThreadHeaderDragFinished(UIElement sender, DropCompletedEventArgs args)
{
ViewModel.SetDragState(false);
}
private void MailListViewMailDragStateChanged(object? sender, MailDragStateChangedEventArgs e)
{
ViewModel.SetDragState(e.IsDragging, e.DraggedItemCount);
}
private async void ThreadHeaderTapped(object sender, TappedRoutedEventArgs e)
{
if (sender is not MailItemDisplayInformationControl control) return;
// Hover action button clicks bubble a tap as well; skip selecting in that case.
if (control.IsRunningHoverAction)
{
control.IsRunningHoverAction = false;
return;
}
if (control.ActionItem is ThreadMailItemViewModel threadItem)
{
await WinoClickItemInternalAsync(threadItem);
}
}
private async void LeftSwipeItemInvoked(Microsoft.UI.Xaml.Controls.SwipeItem sender, Microsoft.UI.Xaml.Controls.SwipeItemInvokedEventArgs args)
@@ -636,44 +661,74 @@ public sealed partial class MailListPage : MailListPageAbstract,
// Treat toolbar multi-select mode the same as holding CTRL for click selection behavior.
bool isCtrlPressed = KeyPressService.IsCtrlKeyPressed() || ViewModel.IsMultiSelectionModeEnabled;
// Helper local to collapse all other threads (we always collapse ALL then possibly re-expand the active thread per rules)
async Task CollapseAllThreadsExceptAsync(ThreadMailItemViewModel? except)
{
bool wasExpanded = except != null && except.IsThreadExpanded;
// Lazily built caches for this invocation.
List<ThreadMailItemViewModel>? threadItems = null;
Dictionary<string, ThreadMailItemViewModel>? threadById = null;
await ViewModel.MailCollection.CollapseAllThreadsAsync();
if (except != null && wasExpanded)
List<ThreadMailItemViewModel> GetThreadItems()
{
// We'll expand explicitly when required by logic below.
except.IsThreadExpanded = true;
}
}
if (threadItems != null) return threadItems;
threadItems = [];
ThreadMailItemViewModel? FindParentThread(MailItemViewModel mail)
{
foreach (var group in ViewModel.MailCollection.MailItems)
{
foreach (var item in group)
{
if (item is ThreadMailItemViewModel thread && thread.ThreadEmails.Contains(mail))
if (item is ThreadMailItemViewModel thread)
{
return thread;
threadItems.Add(thread);
}
}
}
return threadItems;
}
ThreadMailItemViewModel? FindParentThread(MailItemViewModel mail)
{
if (string.IsNullOrEmpty(mail.ThreadId))
{
return null;
}
threadById ??= GetThreadItems()
.Where(t => !string.IsNullOrEmpty(t.ThreadId))
.GroupBy(t => t.ThreadId, StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => g.First(), StringComparer.Ordinal);
return threadById.TryGetValue(mail.ThreadId, out var threadItem) ? threadItem : null;
}
void CollapseAllThreadsExcept(ThreadMailItemViewModel? except)
{
foreach (var thread in GetThreadItems())
{
if (!ReferenceEquals(thread, except) && thread.IsThreadExpanded)
{
thread.IsThreadExpanded = false;
}
}
}
static void SyncThreadSelectionFromChildren(ThreadMailItemViewModel? thread)
{
if (thread == null) return;
bool hasSelectedChildren = thread.ThreadEmails.Any(child => child.IsSelected);
bool hasSelectedChildren = false;
foreach (var child in thread.ThreadEmails)
{
if (child.IsSelected)
{
hasSelectedChildren = true;
break;
}
}
thread.IsSelected = hasSelectedChildren;
// Keep thread open while it has selected children.
if (hasSelectedChildren)
if (hasSelectedChildren && !thread.IsThreadExpanded)
{
thread.IsThreadExpanded = true;
}
@@ -727,7 +782,7 @@ public sealed partial class MailListPage : MailListPageAbstract,
// Reset everything first (exclusive selection scenario)
await ViewModel.MailCollection.UnselectAllAsync();
await CollapseAllThreadsExceptAsync(clickedThread);
CollapseAllThreadsExcept(clickedThread);
if (wasThreadSelected && wasThreadExpanded)
{
@@ -787,20 +842,11 @@ public sealed partial class MailListPage : MailListPageAbstract,
// If parent thread is already expanded, keep it as-is to avoid collapse/expand animation.
if (parentThread != null && parentThread.IsThreadExpanded)
{
foreach (var group in ViewModel.MailCollection.MailItems)
{
foreach (var item in group)
{
if (item is ThreadMailItemViewModel thread && !ReferenceEquals(thread, parentThread))
{
thread.IsThreadExpanded = false;
}
}
}
CollapseAllThreadsExcept(parentThread);
}
else
{
await ViewModel.MailCollection.CollapseAllThreadsAsync();
CollapseAllThreadsExcept(null);
}
if (parentThread != null && selectExpandThread)