CollectionNavigator.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace Terminal.Gui {
  5. /// <summary>
  6. /// Navigates a collection of items using keystrokes. The keystrokes are used to build a search string.
  7. /// The <see cref="SearchString"/> is used to find the next item in the collection that matches the search string
  8. /// when <see cref="GetNextMatchingItem(int, char)"/> is called.
  9. /// <para>
  10. /// If the user types keystrokes that can't be found in the collection,
  11. /// the search string is cleared and the next item is found that starts with the last keystroke.
  12. /// </para>
  13. /// <para>
  14. /// If the user pauses keystrokes for a short time (250ms), the search string is cleared.
  15. /// </para>
  16. /// </summary>
  17. public class CollectionNavigator {
  18. /// <summary>
  19. /// Constructs a new CollectionNavigator.
  20. /// </summary>
  21. public CollectionNavigator () { }
  22. /// <summary>
  23. /// Constructs a new CollectionNavigator for the given collection.
  24. /// </summary>
  25. /// <param name="collection"></param>
  26. public CollectionNavigator (IEnumerable<object> collection) => Collection = collection;
  27. DateTime lastKeystroke = DateTime.Now;
  28. internal int TypingDelay { get; set; } = 250;
  29. /// <summary>
  30. /// The compararer function to use when searching the collection.
  31. /// </summary>
  32. public StringComparer Comparer { get; set; } = StringComparer.InvariantCultureIgnoreCase;
  33. /// <summary>
  34. /// The collection of objects to search. <see cref="object.ToString()"/> is used to search the collection.
  35. /// </summary>
  36. public IEnumerable<object> Collection { get; set; }
  37. /// <summary>
  38. /// Event arguments for the <see cref="CollectionNavigator.SearchStringChanged"/> event.
  39. /// </summary>
  40. public class KeystrokeNavigatorEventArgs {
  41. /// <summary>
  42. /// he current <see cref="SearchString"/>.
  43. /// </summary>
  44. public string SearchString { get; }
  45. /// <summary>
  46. /// Initializes a new instance of <see cref="KeystrokeNavigatorEventArgs"/>
  47. /// </summary>
  48. /// <param name="searchString">The current <see cref="SearchString"/>.</param>
  49. public KeystrokeNavigatorEventArgs (string searchString)
  50. {
  51. SearchString = searchString;
  52. }
  53. }
  54. /// <summary>
  55. /// This event is invoked when <see cref="SearchString"/> changes. Useful for debugging.
  56. /// </summary>
  57. public event Action<KeystrokeNavigatorEventArgs> SearchStringChanged;
  58. private string _searchString = "";
  59. /// <summary>
  60. /// Gets the current search string. This includes the set of keystrokes that have been pressed
  61. /// since the last unsuccessful match or after a 250ms delay. Useful for debugging.
  62. /// </summary>
  63. public string SearchString {
  64. get => _searchString;
  65. private set {
  66. _searchString = value;
  67. OnSearchStringChanged (new KeystrokeNavigatorEventArgs (value));
  68. }
  69. }
  70. /// <summary>
  71. /// Invoked when the <see cref="SearchString"/> changes. Useful for debugging. Invokes the <see cref="SearchStringChanged"/> event.
  72. /// </summary>
  73. /// <param name="e"></param>
  74. public virtual void OnSearchStringChanged (KeystrokeNavigatorEventArgs e)
  75. {
  76. SearchStringChanged?.Invoke (e);
  77. }
  78. /// <summary>
  79. /// Gets the index of the next item in the collection that matches the current <see cref="SearchString"/> plus the provided character (typically
  80. /// from a key press).
  81. /// </summary>
  82. /// <param name="currentIndex">The index in the collection to start the search from.</param>
  83. /// <param name="keyStruck">The character of the key the user pressed.</param>
  84. /// <returns>The index of the item that matches what the user has typed.
  85. /// Returns <see langword="-1"/> if no item in the collection matched.</returns>
  86. public int GetNextMatchingItem (int currentIndex, char keyStruck)
  87. {
  88. AssertCollectionIsNotNull ();
  89. if (!char.IsControl (keyStruck)) {
  90. // maybe user pressed 'd' and now presses 'd' again.
  91. // a candidate search is things that begin with "dd"
  92. // but if we find none then we must fallback on cycling
  93. // d instead and discard the candidate state
  94. string candidateState = "";
  95. // is it a second or third (etc) keystroke within a short time
  96. if (SearchString.Length > 0 && DateTime.Now - lastKeystroke < TimeSpan.FromMilliseconds (TypingDelay)) {
  97. // "dd" is a candidate
  98. candidateState = SearchString + keyStruck;
  99. } else {
  100. // its a fresh keystroke after some time
  101. // or its first ever key press
  102. SearchString = new string (keyStruck, 1);
  103. }
  104. var idxCandidate = GetNextMatchingItem (currentIndex, candidateState,
  105. // prefer not to move if there are multiple characters e.g. "ca" + 'r' should stay on "car" and not jump to "cart"
  106. candidateState.Length > 1);
  107. if (idxCandidate != -1) {
  108. // found "dd" so candidate searchstring is accepted
  109. lastKeystroke = DateTime.Now;
  110. SearchString = candidateState;
  111. return idxCandidate;
  112. }
  113. //// nothing matches "dd" so discard it as a candidate
  114. //// and just cycle "d" instead
  115. lastKeystroke = DateTime.Now;
  116. idxCandidate = GetNextMatchingItem (currentIndex, candidateState);
  117. // if no changes to current state manifested
  118. if (idxCandidate == currentIndex || idxCandidate == -1) {
  119. // clear history and treat as a fresh letter
  120. ClearSearchString ();
  121. // match on the fresh letter alone
  122. SearchString = new string (keyStruck, 1);
  123. idxCandidate = GetNextMatchingItem (currentIndex, SearchString);
  124. return idxCandidate == -1 ? currentIndex : idxCandidate;
  125. }
  126. // Found another "d" or just leave index as it was
  127. return idxCandidate;
  128. } else {
  129. // clear state because keypress was a control char
  130. ClearSearchString ();
  131. // control char indicates no selection
  132. return -1;
  133. }
  134. }
  135. /// <summary>
  136. /// Gets the index of the next item in the collection that matches <paramref name="search"/>.
  137. /// </summary>
  138. /// <param name="currentIndex">The index in the collection to start the search from.</param>
  139. /// <param name="search">The search string to use.</param>
  140. /// <param name="minimizeMovement">Set to <see langword="true"/> to stop the search on the first match
  141. /// if there are multiple matches for <paramref name="search"/>.
  142. /// e.g. "ca" + 'r' should stay on "car" and not jump to "cart". If <see langword="false"/> (the default),
  143. /// the next matching item will be returned, even if it is above in the collection.
  144. /// </param>
  145. /// <returns>The index of the next matching item or <see langword="-1"/> if no match was found.</returns>
  146. internal int GetNextMatchingItem (int currentIndex, string search, bool minimizeMovement = false)
  147. {
  148. if (string.IsNullOrEmpty (search)) {
  149. return -1;
  150. }
  151. AssertCollectionIsNotNull ();
  152. // find indexes of items that start with the search text
  153. int [] matchingIndexes = Collection.Select ((item, idx) => (item, idx))
  154. .Where (k => k.item?.ToString ().StartsWith (search, StringComparison.InvariantCultureIgnoreCase) ?? false)
  155. .Select (k => k.idx)
  156. .ToArray ();
  157. // if there are items beginning with search
  158. if (matchingIndexes.Length > 0) {
  159. // is one of them currently selected?
  160. var currentlySelected = Array.IndexOf (matchingIndexes, currentIndex);
  161. if (currentlySelected == -1) {
  162. // we are not currently selecting any item beginning with the search
  163. // so jump to first item in list that begins with the letter
  164. return matchingIndexes [0];
  165. } else {
  166. // the current index is part of the matching collection
  167. if (minimizeMovement) {
  168. // if we would rather not jump around (e.g. user is typing lots of text to get this match)
  169. return matchingIndexes [currentlySelected];
  170. }
  171. // cycle to next (circular)
  172. return matchingIndexes [(currentlySelected + 1) % matchingIndexes.Length];
  173. }
  174. }
  175. // nothing starts with the search
  176. return -1;
  177. }
  178. private void AssertCollectionIsNotNull ()
  179. {
  180. if (Collection == null) {
  181. throw new InvalidOperationException ("Collection is null");
  182. }
  183. }
  184. private void ClearSearchString ()
  185. {
  186. SearchString = "";
  187. lastKeystroke = DateTime.Now;
  188. }
  189. /// <summary>
  190. /// Returns true if <paramref name="kb"/> is a searchable key
  191. /// (e.g. letters, numbers etc) that is valid to pass to to this
  192. /// class for search filtering.
  193. /// </summary>
  194. /// <param name="kb"></param>
  195. /// <returns></returns>
  196. public static bool IsCompatibleKey (KeyEvent kb)
  197. {
  198. return !kb.IsAlt && !kb.IsCapslock && !kb.IsCtrl && !kb.IsScrolllock && !kb.IsNumlock;
  199. }
  200. }
  201. }