CollectionNavigator.cs 8.4 KB

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