cachingmatcher.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview Matcher which maintains a client-side cache on top of some
  16. * other matcher.
  17. * @author reinerp@google.com (Reiner Pope)
  18. */
  19. goog.provide('goog.ui.ac.CachingMatcher');
  20. goog.require('goog.array');
  21. goog.require('goog.async.Throttle');
  22. goog.require('goog.ui.ac.ArrayMatcher');
  23. goog.require('goog.ui.ac.RenderOptions');
  24. /**
  25. * A matcher which wraps another (typically slow) matcher and
  26. * keeps a client-side cache of the results. For instance, you can use this to
  27. * wrap a RemoteArrayMatcher to hide the latency of the underlying matcher
  28. * having to make ajax request.
  29. *
  30. * Objects in the cache are deduped on their stringified forms.
  31. *
  32. * Note - when the user types a character, they will instantly get a set of
  33. * local results, and then some time later, the results from the server will
  34. * show up.
  35. *
  36. * @constructor
  37. * @param {!Object} baseMatcher The underlying matcher to use. Must implement
  38. * requestMatchingRows.
  39. * @final
  40. */
  41. goog.ui.ac.CachingMatcher = function(baseMatcher) {
  42. /** @private {!Array<!Object>}} The cache. */
  43. this.rows_ = [];
  44. /**
  45. * Set of stringified rows, for fast deduping. Each element of this.rows_
  46. * is stored in rowStrings_ as (' ' + row) to ensure we avoid builtin
  47. * properties like 'toString'.
  48. * @private {Object<string, boolean>}
  49. */
  50. this.rowStrings_ = {};
  51. /**
  52. * Maximum number of rows in the cache. If the cache grows larger than this,
  53. * the entire cache will be emptied.
  54. * @private {number}
  55. */
  56. this.maxCacheSize_ = 1000;
  57. /** @private {!Object} The underlying matcher to use. */
  58. this.baseMatcher_ = baseMatcher;
  59. /**
  60. * Local matching function.
  61. * @private {function(string, number, !Array<!Object>): !Array<!Object>}
  62. */
  63. this.getMatchesForRows_ = goog.ui.ac.ArrayMatcher.getMatchesForRows;
  64. /** @private {number} Number of matches to request from the base matcher. */
  65. this.baseMatcherMaxMatches_ = 100;
  66. /** @private {goog.async.Throttle} */
  67. this.throttledTriggerBaseMatch_ =
  68. new goog.async.Throttle(this.triggerBaseMatch_, 150, this);
  69. /** @private {string} */
  70. this.mostRecentToken_ = '';
  71. /** @private {Function} */
  72. this.mostRecentMatchHandler_ = null;
  73. /** @private {number} */
  74. this.mostRecentMaxMatches_ = 10;
  75. /**
  76. * The set of rows which we last displayed.
  77. *
  78. * NOTE(reinerp): The need for this is subtle. When a server result comes
  79. * back, we don't want to suddenly change the list of results without the user
  80. * doing anything. So we make sure to add the new server results to the end of
  81. * the currently displayed list.
  82. *
  83. * We need to keep track of the last rows we displayed, because the "similar
  84. * matcher" we use locally might otherwise reorder results.
  85. *
  86. * @private {Array<!Object>}
  87. */
  88. this.mostRecentMatches_ = [];
  89. };
  90. /**
  91. * Sets the number of milliseconds with which to throttle the match requests
  92. * on the underlying matcher.
  93. *
  94. * Default value: 150.
  95. *
  96. * @param {number} throttleTime .
  97. */
  98. goog.ui.ac.CachingMatcher.prototype.setThrottleTime = function(throttleTime) {
  99. this.throttledTriggerBaseMatch_ =
  100. new goog.async.Throttle(this.triggerBaseMatch_, throttleTime, this);
  101. };
  102. /**
  103. * Sets the maxMatches to use for the base matcher. If the base matcher makes
  104. * AJAX requests, it may help to make this a large number so that the local
  105. * cache gets populated quickly.
  106. *
  107. * Default value: 100.
  108. *
  109. * @param {number} maxMatches The value to set.
  110. */
  111. goog.ui.ac.CachingMatcher.prototype.setBaseMatcherMaxMatches = function(
  112. maxMatches) {
  113. this.baseMatcherMaxMatches_ = maxMatches;
  114. };
  115. /**
  116. * Sets the maximum size of the local cache. If the local cache grows larger
  117. * than this size, it will be emptied.
  118. *
  119. * Default value: 1000.
  120. *
  121. * @param {number} maxCacheSize .
  122. */
  123. goog.ui.ac.CachingMatcher.prototype.setMaxCacheSize = function(maxCacheSize) {
  124. this.maxCacheSize_ = maxCacheSize;
  125. };
  126. /**
  127. * Sets the local matcher to use.
  128. *
  129. * The local matcher should be a function with the same signature as
  130. * {@link goog.ui.ac.ArrayMatcher.getMatchesForRows}, i.e. its arguments are
  131. * searchToken, maxMatches, rowsToSearch; and it returns a list of matching
  132. * rows.
  133. *
  134. * Default value: {@link goog.ui.ac.ArrayMatcher.getMatchesForRows}.
  135. *
  136. * @param {function(string, number, !Array<!Object>): !Array<!Object>}
  137. * localMatcher
  138. */
  139. goog.ui.ac.CachingMatcher.prototype.setLocalMatcher = function(localMatcher) {
  140. this.getMatchesForRows_ = localMatcher;
  141. };
  142. /**
  143. * Function used to pass matches to the autocomplete.
  144. * @param {string} token Token to match.
  145. * @param {number} maxMatches Max number of matches to return.
  146. * @param {Function} matchHandler callback to execute after matching.
  147. */
  148. goog.ui.ac.CachingMatcher.prototype.requestMatchingRows = function(
  149. token, maxMatches, matchHandler) {
  150. this.mostRecentMaxMatches_ = maxMatches;
  151. this.mostRecentToken_ = token;
  152. this.mostRecentMatchHandler_ = matchHandler;
  153. this.throttledTriggerBaseMatch_.fire();
  154. var matches = this.getMatchesForRows_(token, maxMatches, this.rows_);
  155. matchHandler(token, matches);
  156. this.mostRecentMatches_ = matches;
  157. };
  158. /** Clears the cache. */
  159. goog.ui.ac.CachingMatcher.prototype.clearCache = function() {
  160. this.rows_ = [];
  161. this.rowStrings_ = {};
  162. };
  163. /**
  164. * Adds the specified rows to the cache.
  165. * @param {!Array<!Object>} rows .
  166. * @private
  167. */
  168. goog.ui.ac.CachingMatcher.prototype.addRows_ = function(rows) {
  169. goog.array.forEach(rows, function(row) {
  170. // The ' ' prefix is to avoid colliding with builtins like toString.
  171. if (!this.rowStrings_[' ' + row]) {
  172. this.rows_.push(row);
  173. this.rowStrings_[' ' + row] = true;
  174. }
  175. }, this);
  176. };
  177. /**
  178. * Checks if the cache is larger than the maximum cache size. If so clears it.
  179. * @private
  180. */
  181. goog.ui.ac.CachingMatcher.prototype.clearCacheIfTooLarge_ = function() {
  182. if (this.rows_.length > this.maxCacheSize_) {
  183. this.clearCache();
  184. }
  185. };
  186. /**
  187. * Triggers a match request against the base matcher. This function is
  188. * unthrottled, so don't call it directly; instead use
  189. * this.throttledTriggerBaseMatch_.
  190. * @private
  191. */
  192. goog.ui.ac.CachingMatcher.prototype.triggerBaseMatch_ = function() {
  193. this.baseMatcher_.requestMatchingRows(
  194. this.mostRecentToken_, this.baseMatcherMaxMatches_,
  195. goog.bind(this.onBaseMatch_, this));
  196. };
  197. /**
  198. * Handles a match response from the base matcher.
  199. * @param {string} token The token against which the base match was called.
  200. * @param {!Array<!Object>} matches The matches returned by the base matcher.
  201. * @private
  202. */
  203. goog.ui.ac.CachingMatcher.prototype.onBaseMatch_ = function(token, matches) {
  204. // NOTE(reinerp): The user might have typed some more characters since the
  205. // base matcher request was sent out, which manifests in that token might be
  206. // older than this.mostRecentToken_. We make sure to do our local matches
  207. // using this.mostRecentToken_ rather than token so that we display results
  208. // relevant to what the user is seeing right now.
  209. // NOTE(reinerp): We compute a diff between the currently displayed results
  210. // and the new results we would get now that the server results have come
  211. // back. Using this diff, we make sure the new results are only added to the
  212. // end of the list of results. See the documentation on
  213. // this.mostRecentMatches_ for details
  214. this.addRows_(matches);
  215. var oldMatchesSet = {};
  216. goog.array.forEach(this.mostRecentMatches_, function(match) {
  217. // The ' ' prefix is to avoid colliding with builtins like toString.
  218. oldMatchesSet[' ' + match] = true;
  219. });
  220. var newMatches = this.getMatchesForRows_(
  221. this.mostRecentToken_, this.mostRecentMaxMatches_, this.rows_);
  222. newMatches = goog.array.filter(
  223. newMatches, function(match) { return !(oldMatchesSet[' ' + match]); });
  224. newMatches = this.mostRecentMatches_.concat(newMatches)
  225. .slice(0, this.mostRecentMaxMatches_);
  226. this.mostRecentMatches_ = newMatches;
  227. // We've gone to the effort of keeping the existing rows as before, so let's
  228. // make sure to keep them highlighted.
  229. var options = new goog.ui.ac.RenderOptions();
  230. options.setPreserveHilited(true);
  231. this.mostRecentMatchHandler_(this.mostRecentToken_, newMatches, options);
  232. // We clear the cache *after* running the local match, so we don't
  233. // suddenly remove results just because the remote match came back.
  234. this.clearCacheIfTooLarge_();
  235. };