Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TEST] Testing wrapper #3599

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 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
5 changes: 5 additions & 0 deletions examples/QuickJournal/Models/JournalEntry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,10 @@ public partial class JournalEntry : IRealmObject
public string? Body { get; set; }

public EntryMetadata? Metadata { get; set; }

public override string ToString()
{
return $"{Title} - {Body}";
}
}
}
115 changes: 94 additions & 21 deletions examples/QuickJournal/ViewModels/EntriesViewModel.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
using CommunityToolkit.Maui.Alerts;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using QuickJournal.Messages;
using QuickJournal.Models;
using Realms;

Expand All @@ -13,18 +13,30 @@ public partial class EntriesViewModel : ObservableObject
private readonly Realm realm;

[ObservableProperty]
private IQueryable<JournalEntry>? entries;
private IEnumerable<JournalEntryViewModel>? entries;

public EntriesViewModel()
{
realm = Realm.GetInstance();
Entries = realm.All<JournalEntry>();

// We are using a WeakReferenceManager here to get notified when JournalEntriesDetailPage is closed.
// This could have been implemeted hooking up on the back button behaviour
// (with Shell.BackButtonBehaviour), but there is a current bug in MAUI
// that would make the application crash (https://github.com/dotnet/maui/pull/11438)
WeakReferenceMessenger.Default.Register<EntryModifiedMessage>(this, EntryModifiedHandler);
realm.Write(() =>
{
realm.RemoveAll();
for (int i = 0; i < 200; i++)
{
realm.Add(new JournalEntry
{
Title = $"Title-{i}",
Body = $"Body-{i}",
Metadata = new EntryMetadata
{
CreatedDate = DateTimeOffset.Now,
}
});
}
});

Entries = new WrapperCollection<JournalEntry, JournalEntryViewModel>(realm.All<JournalEntry>(), i => new JournalEntryViewModel(i));
}

[RelayCommand]
Expand All @@ -41,40 +53,101 @@ public async Task AddEntry()
});
});

await GoToEntry(entry);
await GoToEntry(new JournalEntryViewModel(entry));
}

[RelayCommand]
public async Task EditEntry(JournalEntry entry)
public async Task EditEntry(JournalEntryViewModel entry)
{
await GoToEntry(entry);
}

[RelayCommand]
public async Task DeleteEntry(JournalEntry entry)
public async Task DeleteEntry(JournalEntryViewModel entry)
{
await realm.WriteAsync(() =>
{
realm.Remove(entry);
realm.Remove(entry.Entry);
});
}

private async Task GoToEntry(JournalEntry entry)
private async Task GoToEntry(JournalEntryViewModel entry)
{
var navigationParameter = new Dictionary<string, object>
{
{ "Entry", entry },
{ "Entry", entry.Entry },
};
await Shell.Current.GoToAsync($"entryDetail", navigationParameter);
}
}

public class WrapperCollection<T, TViewModel> : INotifyCollectionChanged, IReadOnlyList<TViewModel>
where T : IRealmObject
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If here IEnumerable is used instead of IReadOnlyList, the enumerator is called for all the elements

where TViewModel : class
{
private IRealmCollection<T> _results;
private Func<T, TViewModel> _viewModelFactory;

public int Count => _results.Count;

public TViewModel this[int index]
{
get
{
var item = _viewModelFactory(_results[index]);
Console.WriteLine($"Indexer: {item}");
return item;
}
}

public event NotifyCollectionChangedEventHandler? CollectionChanged
{
add { _results.CollectionChanged += value; }
remove { _results.CollectionChanged -= value; }
}

public WrapperCollection(IQueryable<T> query, Func<T, TViewModel> viewModelFactory)
{
_results = query.AsRealmCollection();
_viewModelFactory = viewModelFactory;
}

public IEnumerator<TViewModel> GetEnumerator()
{
foreach (var item in _results)
{
Console.WriteLine($"Enumerator: {item}");
yield return _viewModelFactory(item);
}
}

IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

public class JournalEntryViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;

public JournalEntry Entry { get; private set; }

public string Summary => Entry.Title + Entry.Body;

public JournalEntryViewModel(JournalEntry entry)
{
Entry = entry;
Entry.PropertyChanged += Inner_PropertyChanged;
}

public override string ToString()
{
return Entry.ToString();
}

private async void EntryModifiedHandler(object recipient, EntryModifiedMessage message)
private void Inner_PropertyChanged(object? sender, PropertyChangedEventArgs e)
{
var newEntry = message.Value;
if (string.IsNullOrEmpty(newEntry.Body + newEntry.Title))
if (e.PropertyName == nameof(JournalEntry.Title) || e.PropertyName == nameof(JournalEntry.Body))
{
await DeleteEntry(newEntry);
await Toast.Make("Empty note discarded").Show();
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Summary)));
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions examples/QuickJournal/Views/EntriesPage.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@
</ListView.Behaviors>
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Title}"
Detail="{Binding Metadata.CreatedDate, StringFormat='{0:dddd, MMMM d yyyy}'}">
<TextCell Text="{Binding Summary}"
Detail="{Binding Entry.Metadata.CreatedDate, StringFormat='{0:dddd, MMMM d yyyy}'}">
<TextCell.ContextActions>
<MenuItem Text="Delete" IsDestructive="true"
Command="{Binding Path=BindingContext.DeleteEntryCommand, Source={x:Reference entriesPage}}"
Expand Down
Loading