inputhandler.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337
  1. // Copyright 2006 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 for managing the interactions between an
  16. * auto-complete object and a text-input or textarea.
  17. *
  18. * IME note:
  19. *
  20. * We used to suspend autocomplete while there are IME preedit characters, but
  21. * now for parity with Search we do not. We still detect the beginning and end
  22. * of IME entry because we need to listen to more events while an IME commit is
  23. * happening, but we update continuously as the user types.
  24. *
  25. * IMEs vary across operating systems, browsers, and even input languages. This
  26. * class tries to handle IME for:
  27. * - Windows x {FF3, IE7, Chrome} x MS IME 2002 (Japanese)
  28. * - Mac x {FF3, Safari3} x Kotoeri (Japanese)
  29. * - Linux x {FF3} x UIM + Anthy (Japanese)
  30. *
  31. * TODO(user): We cannot handle {Mac, Linux} x FF3 correctly.
  32. * TODO(user): We need to support Windows x Google IME.
  33. *
  34. * This class was tested with hiragana input. The event sequence when inputting
  35. * 'ai<enter>' with IME on (which commits two characters) is as follows:
  36. *
  37. * Notation: [key down code, key press, key up code]
  38. * key code or +: event fired
  39. * -: event not fired
  40. *
  41. * - Win/FF3: [WIN_IME, +, A], [-, -, ENTER]
  42. * Note: No events are fired for 'i'.
  43. *
  44. * - Win/IE7: [WIN_IME, -, A], [WIN_IME, -, I], [WIN_IME, -, ENTER]
  45. *
  46. * - Win/Chrome: Same as Win/IE7
  47. *
  48. * - Mac/FF3: [A, -, A], [I, -, I], [ENTER, -, ENTER]
  49. *
  50. * - Mac/Safari3: Same as Win/IE7
  51. *
  52. * - Linux/FF3: No events are generated.
  53. *
  54. * With IME off,
  55. *
  56. * - ALL: [A, +, A], [I, +, I], [ENTER, +, ENTER]
  57. * Note: Key code of key press event varies across configuration.
  58. *
  59. * With Microsoft Pinyin IME 3.0 (Simplified Chinese),
  60. *
  61. * - Win/IE7: Same as Win/IE7 with MS IME 2002 (Japanese)
  62. *
  63. * The issue with this IME is that the key sequence that ends preedit is not
  64. * a single ENTER key up.
  65. * - ENTER key up following either ENTER or SPACE ends preedit.
  66. * - SPACE key up following even number of LEFT, RIGHT, or SPACE (any
  67. * combination) ends preedit.
  68. * TODO(user): We only support SPACE-then-ENTER sequence.
  69. * TODO(mpd): With the change to autocomplete during IME, this might not be an
  70. * issue. Remove this comment once tested.
  71. *
  72. * With Microsoft Korean IME 2002,
  73. *
  74. * - Win/IE7: Same as Win/IE7 with MS IME 2002 (Japanese), but there is no
  75. * sequence that ends the preedit.
  76. *
  77. * The following is the algorithm we use to detect IME preedit:
  78. *
  79. * - WIN_IME key down starts predit.
  80. * - (1) ENTER key up or (2) CTRL-M key up ends preedit.
  81. * - Any key press not immediately following WIN_IME key down signifies that
  82. * preedit has ended.
  83. *
  84. * If you need to change this algorithm, please note the OS, browser, language,
  85. * and behavior above so that we can avoid regressions. Contact mpd or yuzo
  86. * if you have questions or concerns.
  87. *
  88. */
  89. goog.provide('goog.ui.ac.InputHandler');
  90. goog.require('goog.Disposable');
  91. goog.require('goog.Timer');
  92. goog.require('goog.a11y.aria');
  93. goog.require('goog.a11y.aria.Role');
  94. goog.require('goog.a11y.aria.State');
  95. goog.require('goog.dom');
  96. goog.require('goog.dom.selection');
  97. goog.require('goog.events.EventHandler');
  98. goog.require('goog.events.EventType');
  99. goog.require('goog.events.KeyCodes');
  100. goog.require('goog.events.KeyHandler');
  101. goog.require('goog.string');
  102. goog.require('goog.userAgent');
  103. goog.require('goog.userAgent.product');
  104. /**
  105. * Class for managing the interaction between an auto-complete object and a
  106. * text-input or textarea.
  107. *
  108. * @param {?string=} opt_separators Separators to split multiple entries.
  109. * If none passed, uses ',' and ';'.
  110. * @param {?string=} opt_literals Characters used to delimit text literals.
  111. * @param {?boolean=} opt_multi Whether to allow multiple entries
  112. * (Default: true).
  113. * @param {?number=} opt_throttleTime Number of milliseconds to throttle
  114. * keyevents with (Default: 150). Use -1 to disable updates on typing. Note
  115. * that typing the separator will update autocomplete suggestions.
  116. * @constructor
  117. * @extends {goog.Disposable}
  118. */
  119. goog.ui.ac.InputHandler = function(
  120. opt_separators, opt_literals, opt_multi, opt_throttleTime) {
  121. goog.Disposable.call(this);
  122. var throttleTime = opt_throttleTime || 150;
  123. /**
  124. * Whether this input accepts multiple values
  125. * @type {boolean}
  126. * @private
  127. */
  128. this.multi_ = opt_multi != null ? opt_multi : true;
  129. // Set separators depends on this.multi_ being set correctly
  130. this.setSeparators(
  131. opt_separators || goog.ui.ac.InputHandler.STANDARD_LIST_SEPARATORS);
  132. /**
  133. * Characters that are used to delimit literal text. Separarator characters
  134. * found within literal text are not processed as separators
  135. * @type {string}
  136. * @private
  137. */
  138. this.literals_ = opt_literals || '';
  139. /**
  140. * Whether to prevent highlighted item selection when tab is pressed.
  141. * @type {boolean}
  142. * @private
  143. */
  144. this.preventSelectionOnTab_ = false;
  145. /**
  146. * Whether to prevent the default behavior (moving focus to another element)
  147. * when tab is pressed. This occurs by default only for multi-value mode.
  148. * @type {boolean}
  149. * @private
  150. */
  151. this.preventDefaultOnTab_ = this.multi_;
  152. /**
  153. * A timer object used to monitor for changes when an element is active.
  154. *
  155. * TODO(user): Consider tuning the throttle time, so that it takes into
  156. * account the length of the token. When the token is short it is likely to
  157. * match lots of rows, therefore we want to check less frequently. Even
  158. * something as simple as <3-chars = 150ms, then 100ms otherwise.
  159. *
  160. * @type {goog.Timer}
  161. * @private
  162. */
  163. this.timer_ = throttleTime > 0 ? new goog.Timer(throttleTime) : null;
  164. /**
  165. * Event handler used by the input handler to manage events.
  166. * @type {goog.events.EventHandler<!goog.ui.ac.InputHandler>}
  167. * @private
  168. */
  169. this.eh_ = new goog.events.EventHandler(this);
  170. /**
  171. * Event handler to help us find an input element that already has the focus.
  172. * @type {goog.events.EventHandler<!goog.ui.ac.InputHandler>}
  173. * @private
  174. */
  175. this.activateHandler_ = new goog.events.EventHandler(this);
  176. /**
  177. * The keyhandler used for listening on most key events. This takes care of
  178. * abstracting away some of the browser differences.
  179. * @type {goog.events.KeyHandler}
  180. * @private
  181. */
  182. this.keyHandler_ = new goog.events.KeyHandler();
  183. /**
  184. * The last key down key code.
  185. * @type {number}
  186. * @private
  187. */
  188. this.lastKeyCode_ = -1; // Initialize to a non-existent value.
  189. };
  190. goog.inherits(goog.ui.ac.InputHandler, goog.Disposable);
  191. goog.tagUnsealableClass(goog.ui.ac.InputHandler);
  192. /**
  193. * Whether or not we need to pause the execution of the blur handler in order
  194. * to allow the execution of the selection handler to run first. This is
  195. * currently true when running on IOS version prior to 4.2, since we need
  196. * some special logic for these devices to handle bug 4484488.
  197. * @type {boolean}
  198. * @private
  199. */
  200. goog.ui.ac.InputHandler.REQUIRES_ASYNC_BLUR_ =
  201. (goog.userAgent.product.IPHONE || goog.userAgent.product.IPAD) &&
  202. // Check the webkit version against the version for iOS 4.2.1.
  203. !goog.userAgent.isVersionOrHigher('533.17.9');
  204. /**
  205. * Standard list separators.
  206. * @type {string}
  207. * @const
  208. */
  209. goog.ui.ac.InputHandler.STANDARD_LIST_SEPARATORS = ',;';
  210. /**
  211. * Literals for quotes.
  212. * @type {string}
  213. * @const
  214. */
  215. goog.ui.ac.InputHandler.QUOTE_LITERALS = '"';
  216. /**
  217. * The AutoComplete instance this inputhandler is associated with.
  218. * @type {goog.ui.ac.AutoComplete}
  219. */
  220. goog.ui.ac.InputHandler.prototype.ac_;
  221. /**
  222. * Characters that can be used to split multiple entries in an input string
  223. * @type {string}
  224. * @private
  225. */
  226. goog.ui.ac.InputHandler.prototype.separators_;
  227. /**
  228. * The separator we use to reconstruct the string
  229. * @type {string}
  230. * @private
  231. */
  232. goog.ui.ac.InputHandler.prototype.defaultSeparator_;
  233. /**
  234. * Regular expression used from trimming tokens or null for no trimming.
  235. * @type {RegExp}
  236. * @private
  237. */
  238. goog.ui.ac.InputHandler.prototype.trimmer_;
  239. /**
  240. * Regular expression to test whether a separator exists
  241. * @type {RegExp}
  242. * @private
  243. */
  244. goog.ui.ac.InputHandler.prototype.separatorCheck_;
  245. /**
  246. * Should auto-completed tokens be wrapped in whitespace? Used in selectRow.
  247. * @type {boolean}
  248. * @private
  249. */
  250. goog.ui.ac.InputHandler.prototype.whitespaceWrapEntries_ = true;
  251. /**
  252. * Should the occurrence of a literal indicate a token boundary?
  253. * @type {boolean}
  254. * @private
  255. */
  256. goog.ui.ac.InputHandler.prototype.generateNewTokenOnLiteral_ = true;
  257. /**
  258. * Whether to flip the orientation of up & down for hiliting next
  259. * and previous autocomplete entries.
  260. * @type {boolean}
  261. * @private
  262. */
  263. goog.ui.ac.InputHandler.prototype.upsideDown_ = false;
  264. /**
  265. * If we're in 'multi' mode, does typing a separator force the updating of
  266. * suggestions?
  267. * For example, if somebody finishes typing "obama, hillary,", should the last
  268. * comma trigger updating suggestions in a guaranteed manner? Especially useful
  269. * when the suggestions depend on complete keywords. Note that "obama, hill"
  270. * (a leading sub-string of "obama, hillary" will lead to different and possibly
  271. * irrelevant suggestions.
  272. * @type {boolean}
  273. * @private
  274. */
  275. goog.ui.ac.InputHandler.prototype.separatorUpdates_ = true;
  276. /**
  277. * If we're in 'multi' mode, does typing a separator force the current term to
  278. * autocomplete?
  279. * For example, if 'tomato' is a suggested completion and the user has typed
  280. * 'to,', do we autocomplete to turn that into 'tomato,'?
  281. * @type {boolean}
  282. * @private
  283. */
  284. goog.ui.ac.InputHandler.prototype.separatorSelects_ = true;
  285. /**
  286. * The id of the currently active timeout, so it can be cleared if required.
  287. * @type {?number}
  288. * @private
  289. */
  290. goog.ui.ac.InputHandler.prototype.activeTimeoutId_ = null;
  291. /**
  292. * The element that is currently active.
  293. * @type {Element}
  294. * @private
  295. */
  296. goog.ui.ac.InputHandler.prototype.activeElement_ = null;
  297. /**
  298. * The previous value of the active element.
  299. * @type {string}
  300. * @private
  301. */
  302. goog.ui.ac.InputHandler.prototype.lastValue_ = '';
  303. /**
  304. * Flag used to indicate that the IME key has been seen and we need to wait for
  305. * the up event.
  306. * @type {boolean}
  307. * @private
  308. */
  309. goog.ui.ac.InputHandler.prototype.waitingForIme_ = false;
  310. /**
  311. * Flag used to indicate that the user just selected a row and we should
  312. * therefore ignore the change of the input value.
  313. * @type {boolean}
  314. * @private
  315. */
  316. goog.ui.ac.InputHandler.prototype.rowJustSelected_ = false;
  317. /**
  318. * Flag indicating whether the result list should be updated continuously
  319. * during typing or only after a short pause.
  320. * @type {boolean}
  321. * @private
  322. */
  323. goog.ui.ac.InputHandler.prototype.updateDuringTyping_ = true;
  324. /**
  325. * Attach an instance of an AutoComplete
  326. * @param {goog.ui.ac.AutoComplete} ac Autocomplete object.
  327. */
  328. goog.ui.ac.InputHandler.prototype.attachAutoComplete = function(ac) {
  329. this.ac_ = ac;
  330. };
  331. /**
  332. * Returns the associated autocomplete instance.
  333. * @return {goog.ui.ac.AutoComplete} The associated autocomplete instance.
  334. */
  335. goog.ui.ac.InputHandler.prototype.getAutoComplete = function() {
  336. return this.ac_;
  337. };
  338. /**
  339. * Returns the current active element.
  340. * @return {Element} The currently active element.
  341. */
  342. goog.ui.ac.InputHandler.prototype.getActiveElement = function() {
  343. return this.activeElement_;
  344. };
  345. /**
  346. * Returns the value of the current active element.
  347. * @return {string} The value of the current active element.
  348. */
  349. goog.ui.ac.InputHandler.prototype.getValue = function() {
  350. return this.activeElement_.value;
  351. };
  352. /**
  353. * Sets the value of the current active element.
  354. * @param {string} value The new value.
  355. */
  356. goog.ui.ac.InputHandler.prototype.setValue = function(value) {
  357. this.activeElement_.value = value;
  358. };
  359. /**
  360. * Returns the current cursor position.
  361. * @return {number} The index of the cursor position.
  362. */
  363. goog.ui.ac.InputHandler.prototype.getCursorPosition = function() {
  364. return goog.dom.selection.getStart(this.activeElement_);
  365. };
  366. /**
  367. * Sets the cursor at the given position.
  368. * @param {number} pos The index of the cursor position.
  369. */
  370. goog.ui.ac.InputHandler.prototype.setCursorPosition = function(pos) {
  371. goog.dom.selection.setStart(this.activeElement_, pos);
  372. goog.dom.selection.setEnd(this.activeElement_, pos);
  373. };
  374. /**
  375. * Attaches the input handler to a target element. The target element
  376. * should be a textarea, input box, or other focusable element with the
  377. * same interface.
  378. * @param {Element|goog.events.EventTarget} target An element to attach the
  379. * input handler to.
  380. */
  381. goog.ui.ac.InputHandler.prototype.attachInput = function(target) {
  382. if (goog.dom.isElement(target)) {
  383. var el = /** @type {!Element} */ (target);
  384. goog.a11y.aria.setRole(el, goog.a11y.aria.Role.COMBOBOX);
  385. goog.a11y.aria.setState(el, goog.a11y.aria.State.AUTOCOMPLETE, 'list');
  386. }
  387. this.eh_.listen(target, goog.events.EventType.FOCUS, this.handleFocus);
  388. this.eh_.listen(target, goog.events.EventType.BLUR, this.handleBlur);
  389. if (!this.activeElement_) {
  390. this.activateHandler_.listen(
  391. target, goog.events.EventType.KEYDOWN,
  392. this.onKeyDownOnInactiveElement_);
  393. // Don't wait for a focus event if the element already has focus.
  394. if (goog.dom.isElement(target)) {
  395. var ownerDocument = goog.dom.getOwnerDocument(
  396. /** @type {Element} */ (target));
  397. if (goog.dom.getActiveElement(ownerDocument) == target) {
  398. this.processFocus(/** @type {!Element} */ (target));
  399. }
  400. }
  401. }
  402. };
  403. /**
  404. * Detaches the input handler from the provided element.
  405. * @param {Element|goog.events.EventTarget} target An element to detach the
  406. * input handler from.
  407. */
  408. goog.ui.ac.InputHandler.prototype.detachInput = function(target) {
  409. if (goog.dom.isElement(target)) {
  410. var el = /** @type {!Element} */ (target);
  411. goog.a11y.aria.removeRole(el);
  412. goog.a11y.aria.removeState(el, goog.a11y.aria.State.AUTOCOMPLETE);
  413. }
  414. if (target == this.activeElement_) {
  415. this.handleBlur();
  416. }
  417. this.eh_.unlisten(target, goog.events.EventType.FOCUS, this.handleFocus);
  418. this.eh_.unlisten(target, goog.events.EventType.BLUR, this.handleBlur);
  419. if (!this.activeElement_) {
  420. this.activateHandler_.unlisten(
  421. target, goog.events.EventType.KEYDOWN,
  422. this.onKeyDownOnInactiveElement_);
  423. }
  424. };
  425. /**
  426. * Attaches the input handler to multiple elements.
  427. * @param {...Element} var_args Elements to attach the input handler too.
  428. */
  429. goog.ui.ac.InputHandler.prototype.attachInputs = function(var_args) {
  430. for (var i = 0; i < arguments.length; i++) {
  431. this.attachInput(arguments[i]);
  432. }
  433. };
  434. /**
  435. * Detaches the input handler from multuple elements.
  436. * @param {...Element} var_args Variable arguments for elements to unbind from.
  437. */
  438. goog.ui.ac.InputHandler.prototype.detachInputs = function(var_args) {
  439. for (var i = 0; i < arguments.length; i++) {
  440. this.detachInput(arguments[i]);
  441. }
  442. };
  443. /**
  444. * Selects the given row. Implements the SelectionHandler interface.
  445. * @param {Object} row The row to select.
  446. * @param {boolean=} opt_multi Should this be treated as a single or multi-token
  447. * auto-complete? Overrides previous setting of opt_multi on constructor.
  448. * @return {boolean} Whether to suppress the update event.
  449. */
  450. goog.ui.ac.InputHandler.prototype.selectRow = function(row, opt_multi) {
  451. if (this.activeElement_) {
  452. this.setTokenText(row.toString(), opt_multi);
  453. }
  454. return false;
  455. };
  456. /**
  457. * Sets the text of the current token without updating the autocomplete
  458. * choices.
  459. * @param {string} tokenText The text for the current token.
  460. * @param {boolean=} opt_multi Should this be treated as a single or multi-token
  461. * auto-complete? Overrides previous setting of opt_multi on constructor.
  462. * @protected
  463. */
  464. goog.ui.ac.InputHandler.prototype.setTokenText = function(
  465. tokenText, opt_multi) {
  466. if (goog.isDef(opt_multi) ? opt_multi : this.multi_) {
  467. var index = this.getTokenIndex_(this.getValue(), this.getCursorPosition());
  468. // Break up the current input string.
  469. var entries = this.splitInput_(this.getValue());
  470. // Get the new value, ignoring whitespace associated with the entry.
  471. var replaceValue = tokenText;
  472. // Only add punctuation if there isn't already a separator available.
  473. if (!this.separatorCheck_.test(replaceValue)) {
  474. replaceValue =
  475. goog.string.trimRight(replaceValue) + this.defaultSeparator_;
  476. }
  477. // Ensure there's whitespace wrapping the entries, if whitespaceWrapEntries_
  478. // has been set to true.
  479. if (this.whitespaceWrapEntries_) {
  480. if (index != 0 && !goog.string.isEmptyOrWhitespace(entries[index - 1])) {
  481. replaceValue = ' ' + replaceValue;
  482. }
  483. // Add a space only if it's the last token; otherwise, we assume the
  484. // next token already has the proper spacing.
  485. if (index == entries.length - 1) {
  486. replaceValue = replaceValue + ' ';
  487. }
  488. }
  489. // If the token needs changing, then update the input box and move the
  490. // cursor to the correct position.
  491. if (replaceValue != entries[index]) {
  492. // Replace the value in the array.
  493. entries[index] = replaceValue;
  494. var el = this.activeElement_;
  495. // If there is an uncommitted IME in Firefox or IE 9, setting the value
  496. // fails and results in actually clearing the value that's already in the
  497. // input.
  498. // The FF bug is http://bugzilla.mozilla.org/show_bug.cgi?id=549674
  499. // Blurring before setting the value works around this problem. We'd like
  500. // to do this only if there is an uncommitted IME, but this isn't possible
  501. // to detect. Since text editing is finicky we restrict this
  502. // workaround to Firefox and IE 9 where it's necessary.
  503. // (Note: this has been fixed in Edge and since FF 41)
  504. if (goog.userAgent.GECKO ||
  505. (goog.userAgent.IE && goog.userAgent.isVersionOrHigher('9'))) {
  506. el.blur();
  507. }
  508. // Join the array and replace the contents of the input.
  509. el.value = entries.join('');
  510. // Calculate which position to put the cursor at.
  511. var pos = 0;
  512. for (var i = 0; i <= index; i++) {
  513. pos += entries[i].length;
  514. }
  515. // Set the cursor.
  516. el.focus();
  517. this.setCursorPosition(pos);
  518. }
  519. } else {
  520. this.setValue(tokenText);
  521. }
  522. // Avoid triggering an autocomplete just because the value changed.
  523. this.rowJustSelected_ = true;
  524. };
  525. /** @override */
  526. goog.ui.ac.InputHandler.prototype.disposeInternal = function() {
  527. goog.ui.ac.InputHandler.superClass_.disposeInternal.call(this);
  528. if (this.activeTimeoutId_ != null) {
  529. // Need to check against null explicitly because 0 is a valid value.
  530. window.clearTimeout(this.activeTimeoutId_);
  531. }
  532. this.eh_.dispose();
  533. delete this.eh_;
  534. this.activateHandler_.dispose();
  535. this.keyHandler_.dispose();
  536. goog.dispose(this.timer_);
  537. };
  538. /**
  539. * Sets the entry separator characters.
  540. *
  541. * @param {string} separators The separator characters to set.
  542. * @param {string=} opt_defaultSeparators The defaultSeparator character to set.
  543. */
  544. goog.ui.ac.InputHandler.prototype.setSeparators = function(
  545. separators, opt_defaultSeparators) {
  546. this.separators_ = separators;
  547. this.defaultSeparator_ = goog.isDefAndNotNull(opt_defaultSeparators) ?
  548. opt_defaultSeparators :
  549. this.separators_.substring(0, 1);
  550. var wspaceExp = this.multi_ ? '[\\s' + this.separators_ + ']+' : '[\\s]+';
  551. this.trimmer_ = new RegExp('^' + wspaceExp + '|' + wspaceExp + '$', 'g');
  552. this.separatorCheck_ = new RegExp('\\s*[' + this.separators_ + ']$');
  553. };
  554. /**
  555. * Sets whether to flip the orientation of up & down for hiliting next
  556. * and previous autocomplete entries.
  557. * @param {boolean} upsideDown Whether the orientation is upside down.
  558. */
  559. goog.ui.ac.InputHandler.prototype.setUpsideDown = function(upsideDown) {
  560. this.upsideDown_ = upsideDown;
  561. };
  562. /**
  563. * Sets whether auto-completed tokens should be wrapped with whitespace.
  564. * @param {boolean} newValue boolean value indicating whether or not
  565. * auto-completed tokens should be wrapped with whitespace.
  566. */
  567. goog.ui.ac.InputHandler.prototype.setWhitespaceWrapEntries = function(
  568. newValue) {
  569. this.whitespaceWrapEntries_ = newValue;
  570. };
  571. /**
  572. * Sets whether new tokens should be generated from literals. That is, should
  573. * hello'world be two tokens, assuming ' is a literal?
  574. * @param {boolean} newValue boolean value indicating whether or not
  575. * new tokens should be generated from literals.
  576. */
  577. goog.ui.ac.InputHandler.prototype.setGenerateNewTokenOnLiteral = function(
  578. newValue) {
  579. this.generateNewTokenOnLiteral_ = newValue;
  580. };
  581. /**
  582. * Sets the regular expression used to trim the tokens before passing them to
  583. * the matcher: every substring that matches the given regular expression will
  584. * be removed. This can also be set to null to disable trimming.
  585. * @param {RegExp} trimmer Regexp to use for trimming or null to disable it.
  586. */
  587. goog.ui.ac.InputHandler.prototype.setTrimmingRegExp = function(trimmer) {
  588. this.trimmer_ = trimmer;
  589. };
  590. /**
  591. * Sets whether we will prevent the default input behavior (moving focus to the
  592. * next focusable element) on TAB.
  593. * @param {boolean} newValue Whether to preventDefault on TAB.
  594. */
  595. goog.ui.ac.InputHandler.prototype.setPreventDefaultOnTab = function(newValue) {
  596. this.preventDefaultOnTab_ = newValue;
  597. };
  598. /**
  599. * Sets whether we will prevent highlighted item selection on TAB.
  600. * @param {boolean} newValue Whether to prevent selection on TAB.
  601. */
  602. goog.ui.ac.InputHandler.prototype.setPreventSelectionOnTab = function(
  603. newValue) {
  604. this.preventSelectionOnTab_ = newValue;
  605. };
  606. /**
  607. * Sets whether separators perform autocomplete.
  608. * @param {boolean} newValue Whether to autocomplete on separators.
  609. */
  610. goog.ui.ac.InputHandler.prototype.setSeparatorCompletes = function(newValue) {
  611. this.separatorUpdates_ = newValue;
  612. this.separatorSelects_ = newValue;
  613. };
  614. /**
  615. * Sets whether separators perform autocomplete.
  616. * @param {boolean} newValue Whether to autocomplete on separators.
  617. */
  618. goog.ui.ac.InputHandler.prototype.setSeparatorSelects = function(newValue) {
  619. this.separatorSelects_ = newValue;
  620. };
  621. /**
  622. * Gets the time to wait before updating the results. If the update during
  623. * typing flag is switched on, this delay counts from the last update,
  624. * otherwise from the last keypress.
  625. * @return {number} Throttle time in milliseconds.
  626. */
  627. goog.ui.ac.InputHandler.prototype.getThrottleTime = function() {
  628. return this.timer_ ? this.timer_.getInterval() : -1;
  629. };
  630. /**
  631. * Sets whether a row has just been selected.
  632. * @param {boolean} justSelected Whether or not the row has just been selected.
  633. */
  634. goog.ui.ac.InputHandler.prototype.setRowJustSelected = function(justSelected) {
  635. this.rowJustSelected_ = justSelected;
  636. };
  637. /**
  638. * Sets the time to wait before updating the results.
  639. * @param {number} time New throttle time in milliseconds.
  640. */
  641. goog.ui.ac.InputHandler.prototype.setThrottleTime = function(time) {
  642. if (time < 0) {
  643. this.timer_.dispose();
  644. this.timer_ = null;
  645. return;
  646. }
  647. if (this.timer_) {
  648. this.timer_.setInterval(time);
  649. } else {
  650. this.timer_ = new goog.Timer(time);
  651. }
  652. };
  653. /**
  654. * Gets whether the result list is updated during typing.
  655. * @return {boolean} Value of the flag.
  656. */
  657. goog.ui.ac.InputHandler.prototype.getUpdateDuringTyping = function() {
  658. return this.updateDuringTyping_;
  659. };
  660. /**
  661. * Sets whether the result list should be updated during typing.
  662. * @param {boolean} value New value of the flag.
  663. */
  664. goog.ui.ac.InputHandler.prototype.setUpdateDuringTyping = function(value) {
  665. this.updateDuringTyping_ = value;
  666. };
  667. /**
  668. * Handles a key event.
  669. * @param {goog.events.BrowserEvent} e Browser event object.
  670. * @return {boolean} True if the key event was handled.
  671. * @protected
  672. */
  673. goog.ui.ac.InputHandler.prototype.handleKeyEvent = function(e) {
  674. switch (e.keyCode) {
  675. // If the menu is open and 'down' caused a change then prevent the default
  676. // action and prevent scrolling. If the box isn't a multi autocomplete
  677. // and the menu isn't open, we force it open now.
  678. case goog.events.KeyCodes.DOWN:
  679. if (this.ac_.isOpen()) {
  680. this.moveDown_();
  681. e.preventDefault();
  682. return true;
  683. } else if (!this.multi_) {
  684. this.update(true);
  685. e.preventDefault();
  686. return true;
  687. }
  688. break;
  689. // If the menu is open and 'up' caused a change then prevent the default
  690. // action and prevent scrolling.
  691. case goog.events.KeyCodes.UP:
  692. if (this.ac_.isOpen()) {
  693. this.moveUp_();
  694. e.preventDefault();
  695. return true;
  696. }
  697. break;
  698. // If tab key is pressed, select the current highlighted item. The default
  699. // action is also prevented if the input is a multi input, to prevent the
  700. // user tabbing out of the field.
  701. case goog.events.KeyCodes.TAB:
  702. if (this.ac_.isOpen() && !e.shiftKey && !this.preventSelectionOnTab_) {
  703. // Ensure the menu is up to date before completing.
  704. this.update();
  705. if (this.ac_.selectHilited() && this.preventDefaultOnTab_) {
  706. e.preventDefault();
  707. return true;
  708. }
  709. } else {
  710. this.ac_.dismiss();
  711. }
  712. break;
  713. // On enter, just select the highlighted row.
  714. case goog.events.KeyCodes.ENTER:
  715. if (this.ac_.isOpen()) {
  716. // Ensure the menu is up to date before completing.
  717. this.update();
  718. if (this.ac_.selectHilited()) {
  719. e.preventDefault();
  720. e.stopPropagation();
  721. return true;
  722. }
  723. } else {
  724. this.ac_.dismiss();
  725. }
  726. break;
  727. // On escape tell the autocomplete to dismiss.
  728. case goog.events.KeyCodes.ESC:
  729. if (this.ac_.isOpen()) {
  730. this.ac_.dismiss();
  731. e.preventDefault();
  732. e.stopPropagation();
  733. return true;
  734. }
  735. break;
  736. // The IME keycode indicates an IME sequence has started, we ignore all
  737. // changes until we get an enter key-up.
  738. case goog.events.KeyCodes.WIN_IME:
  739. if (!this.waitingForIme_) {
  740. this.startWaitingForIme_();
  741. return true;
  742. }
  743. break;
  744. default:
  745. if (this.timer_ && !this.updateDuringTyping_) {
  746. // Waits throttle time before sending the request again.
  747. this.timer_.stop();
  748. this.timer_.start();
  749. }
  750. }
  751. return this.handleSeparator_(e);
  752. };
  753. /**
  754. * Handles a key event for a separator key.
  755. * @param {goog.events.BrowserEvent} e Browser event object.
  756. * @return {boolean} True if the key event was handled.
  757. * @private
  758. */
  759. goog.ui.ac.InputHandler.prototype.handleSeparator_ = function(e) {
  760. var isSeparatorKey = this.multi_ && e.charCode &&
  761. this.separators_.indexOf(String.fromCharCode(e.charCode)) != -1;
  762. if (this.separatorUpdates_ && isSeparatorKey) {
  763. this.update();
  764. }
  765. if (this.separatorSelects_ && isSeparatorKey) {
  766. if (this.ac_.selectHilited()) {
  767. e.preventDefault();
  768. return true;
  769. }
  770. }
  771. return false;
  772. };
  773. /**
  774. * @return {boolean} Whether this inputhandler need to listen on key-up.
  775. * @protected
  776. */
  777. goog.ui.ac.InputHandler.prototype.needKeyUpListener = function() {
  778. return false;
  779. };
  780. /**
  781. * Handles the key up event. Registered only if needKeyUpListener returns true.
  782. * @param {goog.events.Event} e The keyup event.
  783. * @return {boolean} Whether an action was taken or not.
  784. * @protected
  785. */
  786. goog.ui.ac.InputHandler.prototype.handleKeyUp = function(e) {
  787. return false;
  788. };
  789. /**
  790. * Adds the necessary input event handlers.
  791. * @private
  792. */
  793. goog.ui.ac.InputHandler.prototype.addEventHandlers_ = function() {
  794. this.keyHandler_.attach(this.activeElement_);
  795. this.eh_.listen(
  796. this.keyHandler_, goog.events.KeyHandler.EventType.KEY, this.onKey_);
  797. if (this.needKeyUpListener()) {
  798. this.eh_.listen(
  799. this.activeElement_, goog.events.EventType.KEYUP, this.handleKeyUp);
  800. }
  801. this.eh_.listen(
  802. this.activeElement_, goog.events.EventType.MOUSEDOWN, this.onMouseDown_);
  803. // IE6 also needs a keypress to check if the user typed a separator
  804. if (goog.userAgent.IE) {
  805. this.eh_.listen(
  806. this.activeElement_, goog.events.EventType.KEYPRESS,
  807. this.onIeKeyPress_);
  808. }
  809. };
  810. /**
  811. * Removes the necessary input event handlers.
  812. * @private
  813. */
  814. goog.ui.ac.InputHandler.prototype.removeEventHandlers_ = function() {
  815. this.eh_.unlisten(
  816. this.keyHandler_, goog.events.KeyHandler.EventType.KEY, this.onKey_);
  817. this.keyHandler_.detach();
  818. this.eh_.unlisten(
  819. this.activeElement_, goog.events.EventType.KEYUP, this.handleKeyUp);
  820. this.eh_.unlisten(
  821. this.activeElement_, goog.events.EventType.MOUSEDOWN, this.onMouseDown_);
  822. if (goog.userAgent.IE) {
  823. this.eh_.unlisten(
  824. this.activeElement_, goog.events.EventType.KEYPRESS,
  825. this.onIeKeyPress_);
  826. }
  827. if (this.waitingForIme_) {
  828. this.stopWaitingForIme_();
  829. }
  830. };
  831. /**
  832. * Handles an element getting focus.
  833. * @param {goog.events.Event} e Browser event object.
  834. * @protected
  835. */
  836. goog.ui.ac.InputHandler.prototype.handleFocus = function(e) {
  837. this.processFocus(/** @type {Element} */ (e.target || null));
  838. };
  839. /**
  840. * Registers handlers for the active element when it receives focus.
  841. * @param {Element} target The element to focus.
  842. * @protected
  843. */
  844. goog.ui.ac.InputHandler.prototype.processFocus = function(target) {
  845. this.activateHandler_.removeAll();
  846. if (this.ac_) {
  847. this.ac_.cancelDelayedDismiss();
  848. }
  849. // Double-check whether the active element has actually changed.
  850. // This is a fix for Safari 3, which fires spurious focus events.
  851. if (target != this.activeElement_) {
  852. this.activeElement_ = target;
  853. if (this.timer_) {
  854. this.timer_.start();
  855. this.eh_.listen(this.timer_, goog.Timer.TICK, this.onTick_);
  856. }
  857. this.lastValue_ = this.getValue();
  858. this.addEventHandlers_();
  859. }
  860. };
  861. /**
  862. * Handles an element blurring.
  863. * @param {goog.events.Event=} opt_e Browser event object.
  864. * @protected
  865. */
  866. goog.ui.ac.InputHandler.prototype.handleBlur = function(opt_e) {
  867. // Phones running iOS prior to version 4.2.
  868. if (goog.ui.ac.InputHandler.REQUIRES_ASYNC_BLUR_) {
  869. // @bug 4484488 This is required so that the menu works correctly on
  870. // iOS prior to version 4.2. Otherwise, the blur action closes the menu
  871. // before the menu button click can be processed.
  872. // In order to fix the bug, we set a timeout to process the blur event, so
  873. // that any pending selection event can be processed first.
  874. this.activeTimeoutId_ =
  875. window.setTimeout(goog.bind(this.processBlur, this), 0);
  876. return;
  877. } else {
  878. this.processBlur();
  879. }
  880. };
  881. /**
  882. * Helper function that does the logic to handle an element blurring.
  883. * @protected
  884. */
  885. goog.ui.ac.InputHandler.prototype.processBlur = function() {
  886. // it's possible that a blur event could fire when there's no active element,
  887. // in the case where attachInput was called on an input that already had
  888. // the focus
  889. if (this.activeElement_) {
  890. this.removeEventHandlers_();
  891. this.activeElement_ = null;
  892. if (this.timer_) {
  893. this.timer_.stop();
  894. this.eh_.unlisten(this.timer_, goog.Timer.TICK, this.onTick_);
  895. }
  896. if (this.ac_) {
  897. // Pause dismissal slightly to take into account any other events that
  898. // might fire on the renderer (e.g. a click will lose the focus).
  899. this.ac_.dismissOnDelay();
  900. }
  901. }
  902. };
  903. /**
  904. * Handles the timer's tick event. Calculates the current token, and reports
  905. * any update to the autocomplete.
  906. * @param {goog.events.Event} e Browser event object.
  907. * @private
  908. */
  909. goog.ui.ac.InputHandler.prototype.onTick_ = function(e) {
  910. this.update();
  911. };
  912. /**
  913. * Handles typing in an inactive input element. Activate it.
  914. * @param {goog.events.BrowserEvent} e Browser event object.
  915. * @private
  916. */
  917. goog.ui.ac.InputHandler.prototype.onKeyDownOnInactiveElement_ = function(e) {
  918. this.handleFocus(e);
  919. };
  920. /**
  921. * Handles typing in the active input element. Checks if the key is a special
  922. * key and does the relevant action as appropriate.
  923. * @param {goog.events.BrowserEvent} e Browser event object.
  924. * @private
  925. */
  926. goog.ui.ac.InputHandler.prototype.onKey_ = function(e) {
  927. this.lastKeyCode_ = e.keyCode;
  928. if (this.ac_) {
  929. this.handleKeyEvent(e);
  930. }
  931. };
  932. /**
  933. * Handles a KEYPRESS event generated by typing in the active input element.
  934. * Checks if IME input is ended.
  935. * @param {goog.events.BrowserEvent} e Browser event object.
  936. * @private
  937. */
  938. goog.ui.ac.InputHandler.prototype.onKeyPress_ = function(e) {
  939. if (this.waitingForIme_ &&
  940. this.lastKeyCode_ != goog.events.KeyCodes.WIN_IME) {
  941. this.stopWaitingForIme_();
  942. }
  943. };
  944. /**
  945. * Handles the key-up event. This is only ever used by Mac FF or when we are in
  946. * an IME entry scenario.
  947. * @param {goog.events.BrowserEvent} e Browser event object.
  948. * @private
  949. */
  950. goog.ui.ac.InputHandler.prototype.onKeyUp_ = function(e) {
  951. if (this.waitingForIme_ &&
  952. (e.keyCode == goog.events.KeyCodes.ENTER ||
  953. (e.keyCode == goog.events.KeyCodes.M && e.ctrlKey))) {
  954. this.stopWaitingForIme_();
  955. }
  956. };
  957. /**
  958. * Handles mouse-down event.
  959. * @param {goog.events.BrowserEvent} e Browser event object.
  960. * @private
  961. */
  962. goog.ui.ac.InputHandler.prototype.onMouseDown_ = function(e) {
  963. if (this.ac_) {
  964. this.handleMouseDown(e);
  965. }
  966. };
  967. /**
  968. * For subclasses to override to handle the mouse-down event.
  969. * @param {goog.events.BrowserEvent} e Browser event object.
  970. * @protected
  971. */
  972. goog.ui.ac.InputHandler.prototype.handleMouseDown = function(e) {};
  973. /**
  974. * Starts waiting for IME.
  975. * @private
  976. */
  977. goog.ui.ac.InputHandler.prototype.startWaitingForIme_ = function() {
  978. if (this.waitingForIme_) {
  979. return;
  980. }
  981. this.eh_.listen(
  982. this.activeElement_, goog.events.EventType.KEYUP, this.onKeyUp_);
  983. this.eh_.listen(
  984. this.activeElement_, goog.events.EventType.KEYPRESS, this.onKeyPress_);
  985. this.waitingForIme_ = true;
  986. };
  987. /**
  988. * Stops waiting for IME.
  989. * @private
  990. */
  991. goog.ui.ac.InputHandler.prototype.stopWaitingForIme_ = function() {
  992. if (!this.waitingForIme_) {
  993. return;
  994. }
  995. this.waitingForIme_ = false;
  996. this.eh_.unlisten(
  997. this.activeElement_, goog.events.EventType.KEYPRESS, this.onKeyPress_);
  998. this.eh_.unlisten(
  999. this.activeElement_, goog.events.EventType.KEYUP, this.onKeyUp_);
  1000. };
  1001. /**
  1002. * Handles the key-press event for IE, checking to see if the user typed a
  1003. * separator character.
  1004. * @param {goog.events.BrowserEvent} e Browser event object.
  1005. * @private
  1006. */
  1007. goog.ui.ac.InputHandler.prototype.onIeKeyPress_ = function(e) {
  1008. this.handleSeparator_(e);
  1009. };
  1010. /**
  1011. * Checks if an update has occurred and notified the autocomplete of the new
  1012. * token.
  1013. * @param {boolean=} opt_force If true the menu will be forced to update.
  1014. */
  1015. goog.ui.ac.InputHandler.prototype.update = function(opt_force) {
  1016. if (this.activeElement_ &&
  1017. (opt_force || this.getValue() != this.lastValue_)) {
  1018. if (opt_force || !this.rowJustSelected_) {
  1019. var token = this.parseToken();
  1020. if (this.ac_) {
  1021. this.ac_.setTarget(this.activeElement_);
  1022. this.ac_.setToken(token, this.getValue());
  1023. }
  1024. }
  1025. this.lastValue_ = this.getValue();
  1026. }
  1027. this.rowJustSelected_ = false;
  1028. };
  1029. /**
  1030. * Parses a text area or input box for the currently highlighted token.
  1031. * @return {string} Token to complete.
  1032. * @protected
  1033. */
  1034. goog.ui.ac.InputHandler.prototype.parseToken = function() {
  1035. return this.parseToken_();
  1036. };
  1037. /**
  1038. * Moves hilite up. May hilite next or previous depending on orientation.
  1039. * @return {boolean} True if successful.
  1040. * @private
  1041. */
  1042. goog.ui.ac.InputHandler.prototype.moveUp_ = function() {
  1043. return this.upsideDown_ ? this.ac_.hiliteNext() : this.ac_.hilitePrev();
  1044. };
  1045. /**
  1046. * Moves hilite down. May hilite next or previous depending on orientation.
  1047. * @return {boolean} True if successful.
  1048. * @private
  1049. */
  1050. goog.ui.ac.InputHandler.prototype.moveDown_ = function() {
  1051. return this.upsideDown_ ? this.ac_.hilitePrev() : this.ac_.hiliteNext();
  1052. };
  1053. /**
  1054. * Parses a text area or input box for the currently highlighted token.
  1055. * @return {string} Token to complete.
  1056. * @private
  1057. */
  1058. goog.ui.ac.InputHandler.prototype.parseToken_ = function() {
  1059. var caret = this.getCursorPosition();
  1060. var text = this.getValue();
  1061. return this.trim_(this.splitInput_(text)[this.getTokenIndex_(text, caret)]);
  1062. };
  1063. /**
  1064. * Trims a token of characters that we want to ignore
  1065. * @param {string} text string to trim.
  1066. * @return {string} Trimmed string.
  1067. * @private
  1068. */
  1069. goog.ui.ac.InputHandler.prototype.trim_ = function(text) {
  1070. return this.trimmer_ ? String(text).replace(this.trimmer_, '') : text;
  1071. };
  1072. /**
  1073. * Gets the index of the currently highlighted token
  1074. * @param {string} text string to parse.
  1075. * @param {number} caret Position of cursor in string.
  1076. * @return {number} Index of token.
  1077. * @private
  1078. */
  1079. goog.ui.ac.InputHandler.prototype.getTokenIndex_ = function(text, caret) {
  1080. // Split up the input string into multiple entries
  1081. var entries = this.splitInput_(text);
  1082. // Short-circuit to select the last entry
  1083. if (caret == text.length) return entries.length - 1;
  1084. // Calculate which of the entries the cursor is currently in
  1085. var current = 0;
  1086. for (var i = 0, pos = 0; i < entries.length && pos <= caret; i++) {
  1087. pos += entries[i].length;
  1088. current = i;
  1089. }
  1090. // Get the token for the current item
  1091. return current;
  1092. };
  1093. /**
  1094. * Splits an input string of text at the occurrence of a character in
  1095. * {@link goog.ui.ac.InputHandler.prototype.separators_} and creates
  1096. * an array of tokens. Each token may contain additional whitespace and
  1097. * formatting marks. If necessary use
  1098. * {@link goog.ui.ac.InputHandler.prototype.trim_} to clean up the
  1099. * entries.
  1100. *
  1101. * @param {string} text Input text.
  1102. * @return {!Array<string>} Parsed array.
  1103. * @private
  1104. */
  1105. goog.ui.ac.InputHandler.prototype.splitInput_ = function(text) {
  1106. if (!this.multi_) {
  1107. return [text];
  1108. }
  1109. var arr = String(text).split('');
  1110. var parts = [];
  1111. var cache = [];
  1112. for (var i = 0, inLiteral = false; i < arr.length; i++) {
  1113. if (this.literals_ && this.literals_.indexOf(arr[i]) != -1) {
  1114. if (this.generateNewTokenOnLiteral_ && !inLiteral) {
  1115. parts.push(cache.join(''));
  1116. cache.length = 0;
  1117. }
  1118. cache.push(arr[i]);
  1119. inLiteral = !inLiteral;
  1120. } else if (!inLiteral && this.separators_.indexOf(arr[i]) != -1) {
  1121. cache.push(arr[i]);
  1122. parts.push(cache.join(''));
  1123. cache.length = 0;
  1124. } else {
  1125. cache.push(arr[i]);
  1126. }
  1127. }
  1128. parts.push(cache.join(''));
  1129. return parts;
  1130. };