CollectionNavigatorBase.cs 7.9 KB

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