CollectionNavigatorBase.cs 9.0 KB

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