CollectionNavigatorBase.cs 7.6 KB

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