2
0

TreeViewTextFilter.cs 1.9 KB

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