CollectionNavigatorBase.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. using Microsoft.Extensions.Logging;
  2. namespace Terminal.Gui;
  3. /// <summary>
  4. /// Navigates a collection of items using keystrokes. The keystrokes are used to build a search string. The
  5. /// <see cref="SearchString"/> is used to find the next item in the collection that matches the search string when
  6. /// <see cref="GetNextMatchingItem(int, char)"/> is called.
  7. /// <para>
  8. /// If the user types keystrokes that can't be found in the collection, the search string is cleared and the next
  9. /// item is found that starts with the last keystroke.
  10. /// </para>
  11. /// <para>If the user pauses keystrokes for a short time (see <see cref="TypingDelay"/>), the search string is cleared.</para>
  12. /// </summary>
  13. public abstract class CollectionNavigatorBase
  14. {
  15. private DateTime _lastKeystroke = DateTime.Now;
  16. private string _searchString = "";
  17. /// <summary>The comparer function to use when searching the collection.</summary>
  18. public StringComparer Comparer { get; set; } = StringComparer.InvariantCultureIgnoreCase;
  19. /// <summary>
  20. /// Gets the current search string. This includes the set of keystrokes that have been pressed since the last
  21. /// unsuccessful match or after <see cref="TypingDelay"/>) milliseconds. Useful for debugging.
  22. /// </summary>
  23. public string SearchString
  24. {
  25. get => _searchString;
  26. private set
  27. {
  28. _searchString = value;
  29. OnSearchStringChanged (new KeystrokeNavigatorEventArgs (value));
  30. }
  31. }
  32. /// <summary>
  33. /// Gets or sets the number of milliseconds to delay before clearing the search string. The delay is reset on each
  34. /// call to <see cref="GetNextMatchingItem(int, char)"/>. The default is 500ms.
  35. /// </summary>
  36. public int TypingDelay { get; set; } = 500;
  37. /// <summary>
  38. /// Gets the index of the next item in the collection that matches the current <see cref="SearchString"/> plus the
  39. /// provided character (typically from a key press).
  40. /// </summary>
  41. /// <param name="currentIndex">The index in the collection to start the search from.</param>
  42. /// <param name="keyStruck">The character of the key the user pressed.</param>
  43. /// <returns>
  44. /// The index of the item that matches what the user has typed. Returns <see langword="-1"/> if no item in the
  45. /// collection matched.
  46. /// </returns>
  47. public int GetNextMatchingItem (int currentIndex, char keyStruck)
  48. {
  49. if (!char.IsControl (keyStruck))
  50. {
  51. // maybe user pressed 'd' and now presses 'd' again.
  52. // a candidate search is things that begin with "dd"
  53. // but if we find none then we must fallback on cycling
  54. // d instead and discard the candidate state
  55. var candidateState = "";
  56. var elapsedTime = DateTime.Now - _lastKeystroke;
  57. Logging.Trace($"CollectionNavigator began processing '{keyStruck}', it has been {elapsedTime} since last keystroke");
  58. // is it a second or third (etc) keystroke within a short time
  59. if (SearchString.Length > 0 && elapsedTime < TimeSpan.FromMilliseconds (TypingDelay))
  60. {
  61. // "dd" is a candidate
  62. candidateState = SearchString + keyStruck;
  63. Logging.Trace($"Appending, search is now for '{candidateState}'");
  64. }
  65. else
  66. {
  67. // its a fresh keystroke after some time
  68. // or its first ever key press
  69. SearchString = new string (keyStruck, 1);
  70. Logging.Trace($"It has been too long since last key press so beginning new search");
  71. }
  72. int idxCandidate = GetNextMatchingItem (
  73. currentIndex,
  74. candidateState,
  75. // prefer not to move if there are multiple characters e.g. "ca" + 'r' should stay on "car" and not jump to "cart"
  76. candidateState.Length > 1
  77. );
  78. Logging.Trace($"CollectionNavigator searching (preferring minimum movement) matched:{idxCandidate}");
  79. if (idxCandidate != -1)
  80. {
  81. // found "dd" so candidate search string is accepted
  82. _lastKeystroke = DateTime.Now;
  83. SearchString = candidateState;
  84. Logging.Trace($"Found collection item that matched search:{idxCandidate}");
  85. return idxCandidate;
  86. }
  87. //// nothing matches "dd" so discard it as a candidate
  88. //// and just cycle "d" instead
  89. _lastKeystroke = DateTime.Now;
  90. idxCandidate = GetNextMatchingItem (currentIndex, candidateState);
  91. Logging.Trace($"CollectionNavigator searching (any match) matched:{idxCandidate}");
  92. // if a match wasn't found, the user typed a 'wrong' key in their search ("can" + 'z'
  93. // instead of "can" + 'd').
  94. if (SearchString.Length > 1 && idxCandidate == -1)
  95. {
  96. Logging.Trace("CollectionNavigator ignored key and returned existing index");
  97. // ignore it since we're still within the typing delay
  98. // don't add it to SearchString either
  99. return currentIndex;
  100. }
  101. // if no changes to current state manifested
  102. if (idxCandidate == currentIndex || idxCandidate == -1)
  103. {
  104. Logging.Trace("CollectionNavigator found no changes to current index, so clearing search");
  105. // clear history and treat as a fresh letter
  106. ClearSearchString ();
  107. // match on the fresh letter alone
  108. SearchString = new string (keyStruck, 1);
  109. idxCandidate = GetNextMatchingItem (currentIndex, SearchString);
  110. Logging.Trace($"CollectionNavigator new SearchString {SearchString} matched index:{idxCandidate}" );
  111. return idxCandidate == -1 ? currentIndex : idxCandidate;
  112. }
  113. Logging.Trace($"CollectionNavigator final answer was:{idxCandidate}" );
  114. // Found another "d" or just leave index as it was
  115. return idxCandidate;
  116. }
  117. Logging.Trace("CollectionNavigator found key press was not actionable so clearing search and returning -1");
  118. // clear state because keypress was a control char
  119. ClearSearchString ();
  120. // control char indicates no selection
  121. return -1;
  122. }
  123. /// <summary>
  124. /// Returns true if <paramref name="a"/> is a searchable key (e.g. letters, numbers, etc) that are valid to pass
  125. /// to this class for search filtering.
  126. /// </summary>
  127. /// <param name="a"></param>
  128. /// <returns></returns>
  129. public static bool IsCompatibleKey (Key a)
  130. {
  131. Rune rune = a.AsRune;
  132. return rune != default (Rune) && !Rune.IsControl (rune);
  133. }
  134. /// <summary>
  135. /// Invoked when the <see cref="SearchString"/> changes. Useful for debugging. Invokes the
  136. /// <see cref="SearchStringChanged"/> event.
  137. /// </summary>
  138. /// <param name="e"></param>
  139. public virtual void OnSearchStringChanged (KeystrokeNavigatorEventArgs e) { SearchStringChanged?.Invoke (this, e); }
  140. /// <summary>This event is invoked when <see cref="SearchString"/> changes. Useful for debugging.</summary>
  141. [CanBeNull]
  142. public event EventHandler<KeystrokeNavigatorEventArgs> SearchStringChanged;
  143. /// <summary>Returns the collection being navigated element at <paramref name="idx"/>.</summary>
  144. /// <returns></returns>
  145. protected abstract object ElementAt (int idx);
  146. /// <summary>Return the number of elements in the collection</summary>
  147. protected abstract int GetCollectionLength ();
  148. /// <summary>Gets the index of the next item in the collection that matches <paramref name="search"/>.</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">
  152. /// Set to <see langword="true"/> to stop the search on the first match if there are
  153. /// multiple matches for <paramref name="search"/>. e.g. "ca" + 'r' should stay on "car" and not jump to "cart". If
  154. /// <see langword="false"/> (the default), the next matching item will be returned, even if it is above in the
  155. /// collection.
  156. /// </param>
  157. /// <returns>The index of the next matching item or <see langword="-1"/> if no match was found.</returns>
  158. internal int GetNextMatchingItem (int currentIndex, string search, bool minimizeMovement = false)
  159. {
  160. if (string.IsNullOrEmpty (search))
  161. {
  162. return -1;
  163. }
  164. int collectionLength = GetCollectionLength ();
  165. if (currentIndex != -1 && currentIndex < collectionLength && IsMatch (search, ElementAt (currentIndex)))
  166. {
  167. // we are already at a match
  168. if (minimizeMovement)
  169. {
  170. // if we would rather not jump around (e.g. user is typing lots of text to get this match)
  171. return currentIndex;
  172. }
  173. for (var i = 1; i < collectionLength; i++)
  174. {
  175. //circular
  176. int idxCandidate = (i + currentIndex) % collectionLength;
  177. if (IsMatch (search, ElementAt (idxCandidate)))
  178. {
  179. return idxCandidate;
  180. }
  181. }
  182. // nothing else starts with the search term
  183. return currentIndex;
  184. }
  185. // search terms no longer match the current selection or there is none
  186. for (var i = 0; i < collectionLength; i++)
  187. {
  188. if (IsMatch (search, ElementAt (i)))
  189. {
  190. return i;
  191. }
  192. }
  193. // Nothing matches
  194. return -1;
  195. }
  196. private void ClearSearchString ()
  197. {
  198. SearchString = "";
  199. _lastKeystroke = DateTime.Now;
  200. }
  201. private bool IsMatch (string search, object value) { return value?.ToString ().StartsWith (search, StringComparison.InvariantCultureIgnoreCase) ?? false; }
  202. }