TreeViewTextFilter.cs 1.8 KB

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