CollectionNavigator.cs 8.9 KB

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