TreeViewTextFilter.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #nullable disable
  2. namespace Terminal.Gui.Views;
  3. /// <summary>
  4. /// <see cref="ITreeViewFilter{T}"/> implementation which searches the <see cref="TreeView{T}.AspectGetter"/> of
  5. /// the model for the given <see cref="Text"/>.
  6. /// </summary>
  7. /// <typeparam name="T"></typeparam>
  8. public class TreeViewTextFilter<T> : ITreeViewFilter<T> where T : class
  9. {
  10. private readonly TreeView<T> _forTree;
  11. private string text;
  12. /// <summary>
  13. /// Creates a new instance of the filter for use with <paramref name="forTree"/>. Set <see cref="Text"/> to begin
  14. /// filtering.
  15. /// </summary>
  16. /// <param name="forTree"></param>
  17. /// <exception cref="ArgumentNullException"></exception>
  18. public TreeViewTextFilter (TreeView<T> forTree) { _forTree = forTree ?? throw new ArgumentNullException (nameof (forTree)); }
  19. /// <summary>The case sensitivity of the search match. Defaults to <see cref="StringComparison.OrdinalIgnoreCase"/>.</summary>
  20. public StringComparison Comparer { get; set; } = StringComparison.OrdinalIgnoreCase;
  21. /// <summary>The text that will be searched for in the <see cref="TreeView{T}"/></summary>
  22. public string Text
  23. {
  24. get => text;
  25. set
  26. {
  27. text = value;
  28. RefreshTreeView ();
  29. }
  30. }
  31. /// <summary>
  32. /// Returns <typeparamref name="T"/> if there is no <see cref="Text"/> or the text matches the
  33. /// <see cref="TreeView{T}.AspectGetter"/> of the <paramref name="model"/>.
  34. /// </summary>
  35. /// <param name="model"></param>
  36. /// <returns></returns>
  37. public bool IsMatch (T model)
  38. {
  39. if (string.IsNullOrWhiteSpace (Text))
  40. {
  41. return true;
  42. }
  43. return _forTree.AspectGetter (model)?.IndexOf (Text, Comparer) != -1;
  44. }
  45. private void RefreshTreeView ()
  46. {
  47. _forTree.InvalidateLineMap ();
  48. _forTree.SetNeedsDraw ();
  49. }
  50. }