remotearraymatcher.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. // Copyright 2007 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 Class that retrieves autocomplete matches via an ajax call.
  16. *
  17. */
  18. goog.provide('goog.ui.ac.RemoteArrayMatcher');
  19. goog.require('goog.Disposable');
  20. goog.require('goog.Uri');
  21. goog.require('goog.events');
  22. goog.require('goog.net.EventType');
  23. goog.require('goog.net.XhrIo');
  24. /**
  25. * An array matcher that requests matches via ajax.
  26. * @param {string} url The Uri which generates the auto complete matches. The
  27. * search term is passed to the server as the 'token' query param.
  28. * @param {boolean=} opt_noSimilar If true, request that the server does not do
  29. * similarity matches for the input token against the dictionary.
  30. * The value is sent to the server as the 'use_similar' query param which is
  31. * either "1" (opt_noSimilar==false) or "0" (opt_noSimilar==true).
  32. * @param {goog.net.XmlHttpFactory=} opt_xmlHttpFactory Specify the
  33. * XmlHttpFactory used to retrieve the matches.
  34. * @constructor
  35. * @extends {goog.Disposable}
  36. */
  37. goog.ui.ac.RemoteArrayMatcher = function(
  38. url, opt_noSimilar, opt_xmlHttpFactory) {
  39. goog.Disposable.call(this);
  40. /**
  41. * The base URL for the ajax call. The token and max_matches are added as
  42. * query params.
  43. * @type {string}
  44. * @private
  45. */
  46. this.url_ = url;
  47. /**
  48. * Whether similar matches should be found as well. This is sent as a hint
  49. * to the server only.
  50. * @type {boolean}
  51. * @private
  52. */
  53. this.useSimilar_ = !opt_noSimilar;
  54. /**
  55. * The XhrIo object used for making remote requests. When a new request
  56. * is made, the current one is aborted and the new one sent.
  57. * @type {goog.net.XhrIo}
  58. * @private
  59. */
  60. this.xhr_ = new goog.net.XhrIo(opt_xmlHttpFactory);
  61. };
  62. goog.inherits(goog.ui.ac.RemoteArrayMatcher, goog.Disposable);
  63. /**
  64. * The HTTP send method (GET, POST) to use when making the ajax call.
  65. * @type {string}
  66. * @private
  67. */
  68. goog.ui.ac.RemoteArrayMatcher.prototype.method_ = 'GET';
  69. /**
  70. * Data to submit during a POST.
  71. * @type {string|undefined}
  72. * @private
  73. */
  74. goog.ui.ac.RemoteArrayMatcher.prototype.content_ = undefined;
  75. /**
  76. * Headers to send with every HTTP request.
  77. * @type {Object|goog.structs.Map}
  78. * @private
  79. */
  80. goog.ui.ac.RemoteArrayMatcher.prototype.headers_ = null;
  81. /**
  82. * Key to the listener on XHR. Used to clear previous listeners.
  83. * @type {goog.events.Key}
  84. * @private
  85. */
  86. goog.ui.ac.RemoteArrayMatcher.prototype.lastListenerKey_ = null;
  87. /**
  88. * Set the send method ("GET", "POST").
  89. * @param {string} method The send method; default: GET.
  90. */
  91. goog.ui.ac.RemoteArrayMatcher.prototype.setMethod = function(method) {
  92. this.method_ = method;
  93. };
  94. /**
  95. * Set the post data.
  96. * @param {string} content Post data.
  97. */
  98. goog.ui.ac.RemoteArrayMatcher.prototype.setContent = function(content) {
  99. this.content_ = content;
  100. };
  101. /**
  102. * Set the HTTP headers.
  103. * @param {Object|goog.structs.Map} headers Map of headers to add to the
  104. * request.
  105. */
  106. goog.ui.ac.RemoteArrayMatcher.prototype.setHeaders = function(headers) {
  107. this.headers_ = headers;
  108. };
  109. /**
  110. * Set the timeout interval.
  111. * @param {number} interval Number of milliseconds after which an
  112. * incomplete request will be aborted; 0 means no timeout is set.
  113. */
  114. goog.ui.ac.RemoteArrayMatcher.prototype.setTimeoutInterval = function(
  115. interval) {
  116. this.xhr_.setTimeoutInterval(interval);
  117. };
  118. /**
  119. * Builds a complete GET-style URL, given the base URI and autocomplete related
  120. * parameter values.
  121. * <b>Override this to build any customized lookup URLs.</b>
  122. * <b>Can be used to change request method and any post content as well.</b>
  123. * @param {string} uri The base URI of the request target.
  124. * @param {string} token Current token in autocomplete.
  125. * @param {number} maxMatches Maximum number of matches required.
  126. * @param {boolean} useSimilar A hint to the server.
  127. * @param {string=} opt_fullString Complete text in the input element.
  128. * @return {?string} The complete url. Return null if no request should be sent.
  129. * @protected
  130. */
  131. goog.ui.ac.RemoteArrayMatcher.prototype.buildUrl = function(
  132. uri, token, maxMatches, useSimilar, opt_fullString) {
  133. var url = new goog.Uri(uri);
  134. url.setParameterValue('token', token);
  135. url.setParameterValue('max_matches', String(maxMatches));
  136. url.setParameterValue('use_similar', String(Number(useSimilar)));
  137. return url.toString();
  138. };
  139. /**
  140. * Returns whether the suggestions should be updated?
  141. * <b>Override this to prevent updates eg - when token is empty.</b>
  142. * @param {string} uri The base URI of the request target.
  143. * @param {string} token Current token in autocomplete.
  144. * @param {number} maxMatches Maximum number of matches required.
  145. * @param {boolean} useSimilar A hint to the server.
  146. * @param {string=} opt_fullString Complete text in the input element.
  147. * @return {boolean} Whether new matches be requested.
  148. * @protected
  149. */
  150. goog.ui.ac.RemoteArrayMatcher.prototype.shouldRequestMatches = function(
  151. uri, token, maxMatches, useSimilar, opt_fullString) {
  152. return true;
  153. };
  154. /**
  155. * Parses and retrieves the array of suggestions from XHR response.
  156. * <b>Override this if the response is not a simple JSON array.</b>
  157. * @param {string} responseText The XHR response text.
  158. * @return {Array<string>} The array of suggestions.
  159. * @protected
  160. */
  161. goog.ui.ac.RemoteArrayMatcher.prototype.parseResponseText = function(
  162. responseText) {
  163. var matches = [];
  164. // If there is no response text, JSON.parse will throw a syntax error.
  165. if (responseText) {
  166. try {
  167. matches = JSON.parse(responseText);
  168. } catch (exception) {
  169. }
  170. }
  171. return /** @type {Array<string>} */ (matches);
  172. };
  173. /**
  174. * Handles the XHR response.
  175. * @param {string} token The XHR autocomplete token.
  176. * @param {Function} matchHandler The AutoComplete match handler.
  177. * @param {goog.events.Event} event The XHR success event.
  178. */
  179. goog.ui.ac.RemoteArrayMatcher.prototype.xhrCallback = function(
  180. token, matchHandler, event) {
  181. var text = event.target.getResponseText();
  182. matchHandler(token, this.parseResponseText(text));
  183. };
  184. /**
  185. * Retrieve a set of matching rows from the server via ajax.
  186. * @param {string} token The text that should be matched; passed to the server
  187. * as the 'token' query param.
  188. * @param {number} maxMatches The maximum number of matches requested from the
  189. * server; passed as the 'max_matches' query param. The server is
  190. * responsible for limiting the number of matches that are returned.
  191. * @param {Function} matchHandler Callback to execute on the result after
  192. * matching.
  193. * @param {string=} opt_fullString The full string from the input box.
  194. */
  195. goog.ui.ac.RemoteArrayMatcher.prototype.requestMatchingRows = function(
  196. token, maxMatches, matchHandler, opt_fullString) {
  197. if (!this.shouldRequestMatches(
  198. this.url_, token, maxMatches, this.useSimilar_, opt_fullString)) {
  199. return;
  200. }
  201. // Set the query params on the URL.
  202. var url = this.buildUrl(
  203. this.url_, token, maxMatches, this.useSimilar_, opt_fullString);
  204. if (!url) {
  205. // Do nothing if there is no URL.
  206. return;
  207. }
  208. // The callback evals the server response and calls the match handler on
  209. // the array of matches.
  210. var callback = goog.bind(this.xhrCallback, this, token, matchHandler);
  211. // Abort the current request and issue the new one; prevent requests from
  212. // being queued up by the browser with a slow server
  213. if (this.xhr_.isActive()) {
  214. this.xhr_.abort();
  215. }
  216. // This ensures if previous XHR is aborted or ends with error, the
  217. // corresponding success-callbacks are cleared.
  218. if (this.lastListenerKey_) {
  219. goog.events.unlistenByKey(this.lastListenerKey_);
  220. }
  221. // Listen once ensures successful callback gets cleared by itself.
  222. this.lastListenerKey_ =
  223. goog.events.listenOnce(this.xhr_, goog.net.EventType.SUCCESS, callback);
  224. this.xhr_.send(url, this.method_, this.content_, this.headers_);
  225. };
  226. /** @override */
  227. goog.ui.ac.RemoteArrayMatcher.prototype.disposeInternal = function() {
  228. this.xhr_.dispose();
  229. goog.ui.ac.RemoteArrayMatcher.superClass_.disposeInternal.call(this);
  230. };