CollectionNavigatorBase.cs 7.8 KB

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