CollectionNavigatorBase.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. namespace Terminal.Gui.Views;
  2. /// <inheritdoc/>
  3. internal abstract class CollectionNavigatorBase : ICollectionNavigator
  4. {
  5. private DateTime _lastKeystroke = DateTime.Now;
  6. private string _searchString = "";
  7. /// <inheritdoc/>
  8. public ICollectionNavigatorMatcher Matcher { get; set; } = new DefaultCollectionNavigatorMatcher ();
  9. /// <inheritdoc/>
  10. public string SearchString
  11. {
  12. get => _searchString;
  13. private set
  14. {
  15. _searchString = value;
  16. OnSearchStringChanged (new (value));
  17. }
  18. }
  19. /// <inheritdoc/>
  20. public int TypingDelay { get; set; } = 500;
  21. /// <inheritdoc/>
  22. public int? GetNextMatchingItem (int? currentIndex, char keyStruck)
  23. {
  24. if (currentIndex.HasValue && currentIndex < 0)
  25. {
  26. throw new ArgumentOutOfRangeException (nameof (currentIndex), @"Must be non-negative");
  27. }
  28. if (!char.IsControl (keyStruck))
  29. {
  30. // maybe user pressed 'd' and now presses 'd' again.
  31. // a candidate search is things that begin with "dd"
  32. // but if we find none then we must fallback on cycling
  33. // d instead and discard the candidate state
  34. var candidateState = "";
  35. TimeSpan elapsedTime = DateTime.Now - _lastKeystroke;
  36. Logging.Debug ($"CollectionNavigator began processing '{keyStruck}', it has been {elapsedTime} since last keystroke");
  37. // is it a second or third (etc) keystroke within a short time
  38. if (SearchString.Length > 0 && elapsedTime < TimeSpan.FromMilliseconds (TypingDelay))
  39. {
  40. // "dd" is a candidate
  41. candidateState = SearchString + keyStruck;
  42. Logging.Debug ($"Appending, search is now for '{candidateState}'");
  43. }
  44. else
  45. {
  46. // its a fresh keystroke after some time
  47. // or its first ever key press
  48. SearchString = new (keyStruck, 1);
  49. Logging.Debug ("It has been too long since last key press so beginning new search");
  50. }
  51. int? idxCandidate = GetNextMatchingItem (
  52. currentIndex,
  53. candidateState,
  54. // prefer not to move if there are multiple characters e.g. "ca" + 'r' should stay on "car" and not jump to "cart"
  55. candidateState.Length > 1
  56. );
  57. Logging.Debug ($"CollectionNavigator searching (preferring minimum movement) matched:{idxCandidate}");
  58. if (idxCandidate is { })
  59. {
  60. // found "dd" so candidate search string is accepted
  61. _lastKeystroke = DateTime.Now;
  62. SearchString = candidateState;
  63. Logging.Debug ($"Found collection item that matched search:{idxCandidate}");
  64. return idxCandidate;
  65. }
  66. //// nothing matches "dd" so discard it as a candidate
  67. //// and just cycle "d" instead
  68. _lastKeystroke = DateTime.Now;
  69. idxCandidate = GetNextMatchingItem (currentIndex, candidateState);
  70. Logging.Debug ($"CollectionNavigator searching (any match) matched:{idxCandidate}");
  71. // if a match wasn't found, the user typed a 'wrong' key in their search ("can" + 'z'
  72. // instead of "can" + 'd').
  73. if (SearchString.Length > 1 && idxCandidate is null)
  74. {
  75. Logging.Debug ("CollectionNavigator ignored key and returned existing index");
  76. // ignore it since we're still within the typing delay
  77. // don't add it to SearchString either
  78. return currentIndex;
  79. }
  80. // if no changes to current state manifested
  81. if (idxCandidate == currentIndex || idxCandidate is null)
  82. {
  83. Logging.Debug ("CollectionNavigator found no changes to current index, so clearing search");
  84. // clear history and treat as a fresh letter
  85. ClearSearchString ();
  86. // match on the fresh letter alone
  87. SearchString = new (keyStruck, 1);
  88. idxCandidate = GetNextMatchingItem (currentIndex, SearchString);
  89. Logging.Debug ($"CollectionNavigator new SearchString {SearchString} matched index:{idxCandidate}");
  90. return idxCandidate ?? currentIndex;
  91. }
  92. Logging.Debug ($"CollectionNavigator final answer was:{idxCandidate}");
  93. // Found another "d" or just leave index as it was
  94. return idxCandidate;
  95. }
  96. Logging.Debug ("CollectionNavigator found key press was not actionable so clearing search and returning null");
  97. // clear state because keypress was a control char
  98. ClearSearchString ();
  99. // control char indicates no selection
  100. return null;
  101. }
  102. /// <summary>This event is raised when <see cref="SearchString"/> is changed. Useful for debugging.</summary>
  103. public event EventHandler<KeystrokeNavigatorEventArgs>? SearchStringChanged;
  104. /// <summary>Returns the collection being navigated element at <paramref name="idx"/>.</summary>
  105. /// <returns></returns>
  106. protected abstract object ElementAt (int idx);
  107. /// <summary>Return the number of elements in the collection</summary>
  108. protected abstract int GetCollectionLength ();
  109. /// <summary>
  110. /// Raised when the <see cref="SearchString"/> is changed. Useful for debugging. Raises the
  111. /// <see cref="SearchStringChanged"/> event.
  112. /// </summary>
  113. /// <param name="e"></param>
  114. protected virtual void OnSearchStringChanged (KeystrokeNavigatorEventArgs e) { SearchStringChanged?.Invoke (this, e); }
  115. /// <summary>Gets the index of the next item in the collection that matches <paramref name="search"/>.</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">
  119. /// Set to <see langword="true"/> to stop the search on the first match if there are
  120. /// multiple matches for <paramref name="search"/>. e.g. "ca" + 'r' should stay on "car" and not jump to "cart". If
  121. /// <see langword="false"/> (the default), the next matching item will be returned, even if it is above in the
  122. /// collection.
  123. /// </param>
  124. /// <returns>The index of the next matching item or <see langword="null"/> if no match was found.</returns>
  125. internal int? GetNextMatchingItem (int? currentIndex, string search, bool minimizeMovement = false)
  126. {
  127. if (string.IsNullOrEmpty (search))
  128. {
  129. return null;
  130. }
  131. int collectionLength = GetCollectionLength ();
  132. if (currentIndex.HasValue && currentIndex < collectionLength && Matcher.IsMatch (search, ElementAt (currentIndex.Value)))
  133. {
  134. // we are already at a match
  135. if (minimizeMovement)
  136. {
  137. // if we would rather not jump around (e.g. user is typing lots of text to get this match)
  138. return currentIndex;
  139. }
  140. for (var i = 1; i < collectionLength; i++)
  141. {
  142. //circular
  143. int? idxCandidate = (i + currentIndex) % collectionLength;
  144. if (Matcher.IsMatch (search, ElementAt (idxCandidate!.Value)))
  145. {
  146. return idxCandidate;
  147. }
  148. }
  149. // nothing else starts with the search term
  150. return currentIndex;
  151. }
  152. // search terms no longer match the current selection or there is none
  153. for (var i = 0; i < collectionLength; i++)
  154. {
  155. if (Matcher.IsMatch (search, ElementAt (i)))
  156. {
  157. return i;
  158. }
  159. }
  160. // Nothing matches
  161. return null;
  162. }
  163. private void ClearSearchString ()
  164. {
  165. SearchString = "";
  166. _lastKeystroke = DateTime.Now;
  167. }
  168. }