abstractspellchecker.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  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 Abstract base class for spell checker implementations.
  16. *
  17. * The spell checker supports two modes - synchronous and asynchronous.
  18. *
  19. * In synchronous mode subclass calls processText_ which processes all the text
  20. * given to it before it returns. If the text string is very long, it could
  21. * cause warnings from the browser that considers the script to be
  22. * busy-looping.
  23. *
  24. * Asynchronous mode allows breaking processing large text segments without
  25. * encountering stop script warnings by rescheduling remaining parts of the
  26. * text processing to another stack.
  27. *
  28. * In asynchronous mode abstract spell checker keeps track of a number of text
  29. * chunks that have been processed after the very beginning, and returns every
  30. * so often so that the calling function could reschedule its execution on a
  31. * different stack (for example by calling setInterval(0)).
  32. *
  33. * @author eae@google.com (Emil A Eklund)
  34. */
  35. goog.provide('goog.ui.AbstractSpellChecker');
  36. goog.provide('goog.ui.AbstractSpellChecker.AsyncResult');
  37. goog.require('goog.a11y.aria');
  38. goog.require('goog.array');
  39. goog.require('goog.asserts');
  40. goog.require('goog.dom');
  41. goog.require('goog.dom.InputType');
  42. goog.require('goog.dom.NodeType');
  43. goog.require('goog.dom.TagName');
  44. goog.require('goog.dom.classlist');
  45. goog.require('goog.dom.selection');
  46. goog.require('goog.events');
  47. goog.require('goog.events.Event');
  48. goog.require('goog.events.EventType');
  49. goog.require('goog.math.Coordinate');
  50. goog.require('goog.spell.SpellCheck');
  51. goog.require('goog.structs.Set');
  52. goog.require('goog.style');
  53. goog.require('goog.ui.Component');
  54. goog.require('goog.ui.MenuItem');
  55. goog.require('goog.ui.MenuSeparator');
  56. goog.require('goog.ui.PopupMenu');
  57. /**
  58. * Abstract base class for spell checker editor implementations. Provides basic
  59. * functionality such as word lookup and caching.
  60. *
  61. * @param {goog.spell.SpellCheck} spellCheck Instance of the SpellCheck
  62. * support object to use. A single instance can be shared by multiple editor
  63. * components.
  64. * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
  65. * @constructor
  66. * @extends {goog.ui.Component}
  67. */
  68. goog.ui.AbstractSpellChecker = function(spellCheck, opt_domHelper) {
  69. goog.ui.Component.call(this, opt_domHelper);
  70. /**
  71. * Handler to use for caching and lookups.
  72. * @type {goog.spell.SpellCheck}
  73. * @protected
  74. */
  75. this.spellCheck = spellCheck;
  76. /**
  77. * Word to element references. Used by replace/ignore.
  78. * @type {Object}
  79. * @private
  80. */
  81. this.wordElements_ = {};
  82. /**
  83. * List of all 'edit word' input elements.
  84. * @type {Array<Element>}
  85. * @private
  86. */
  87. this.inputElements_ = [];
  88. /**
  89. * Global regular expression for splitting a string into individual words and
  90. * blocks of separators. Matches zero or one word followed by zero or more
  91. * separators.
  92. * @type {RegExp}
  93. * @private
  94. */
  95. this.splitRegex_ = new RegExp(
  96. '([^' + goog.spell.SpellCheck.WORD_BOUNDARY_CHARS + ']*)' +
  97. '([' + goog.spell.SpellCheck.WORD_BOUNDARY_CHARS + ']*)',
  98. 'g');
  99. goog.events.listen(
  100. this.spellCheck, goog.spell.SpellCheck.EventType.WORD_CHANGED,
  101. this.onWordChanged_, false, this);
  102. };
  103. goog.inherits(goog.ui.AbstractSpellChecker, goog.ui.Component);
  104. goog.tagUnsealableClass(goog.ui.AbstractSpellChecker);
  105. /**
  106. * The prefix to mark keys with.
  107. * @type {string}
  108. * @private
  109. */
  110. goog.ui.AbstractSpellChecker.KEY_PREFIX_ = ':';
  111. /**
  112. * The attribute name for original element contents (to offer subsequent
  113. * correction menu).
  114. * @type {string}
  115. * @private
  116. */
  117. goog.ui.AbstractSpellChecker.ORIGINAL_ = 'g-spell-original';
  118. /**
  119. * Suggestions menu.
  120. *
  121. * @type {goog.ui.PopupMenu|undefined}
  122. * @private
  123. */
  124. goog.ui.AbstractSpellChecker.prototype.menu_;
  125. /**
  126. * Separator between suggestions and ignore in suggestions menu.
  127. *
  128. * @type {goog.ui.MenuSeparator|undefined}
  129. * @private
  130. */
  131. goog.ui.AbstractSpellChecker.prototype.menuSeparator_;
  132. /**
  133. * Menu item for ignore option.
  134. *
  135. * @type {goog.ui.MenuItem|undefined}
  136. * @private
  137. */
  138. goog.ui.AbstractSpellChecker.prototype.menuIgnore_;
  139. /**
  140. * Menu item for edit word option.
  141. *
  142. * @type {goog.ui.MenuItem|undefined}
  143. * @private
  144. */
  145. goog.ui.AbstractSpellChecker.prototype.menuEdit_;
  146. /**
  147. * Whether the correction UI is visible.
  148. *
  149. * @type {boolean}
  150. * @private
  151. */
  152. goog.ui.AbstractSpellChecker.prototype.isVisible_ = false;
  153. /**
  154. * Cache for corrected words. All corrected words are reverted to their original
  155. * status on resume. Therefore that status is never written to the cache and is
  156. * instead indicated by this set.
  157. *
  158. * @type {goog.structs.Set|undefined}
  159. * @private
  160. */
  161. goog.ui.AbstractSpellChecker.prototype.correctedWords_;
  162. /**
  163. * Class name for suggestions menu.
  164. *
  165. * @type {string}
  166. */
  167. goog.ui.AbstractSpellChecker.prototype.suggestionsMenuClassName =
  168. goog.getCssName('goog-menu');
  169. /**
  170. * Whether corrected words should be highlighted.
  171. *
  172. * @type {boolean}
  173. */
  174. goog.ui.AbstractSpellChecker.prototype.markCorrected = false;
  175. /**
  176. * Word the correction menu is displayed for.
  177. *
  178. * @type {string|undefined}
  179. * @private
  180. */
  181. goog.ui.AbstractSpellChecker.prototype.activeWord_;
  182. /**
  183. * Element the correction menu is displayed for.
  184. *
  185. * @type {Element|undefined}
  186. * @private
  187. */
  188. goog.ui.AbstractSpellChecker.prototype.activeElement_;
  189. /**
  190. * Indicator that the spell checker is running in the asynchronous mode.
  191. *
  192. * @type {boolean}
  193. * @private
  194. */
  195. goog.ui.AbstractSpellChecker.prototype.asyncMode_ = false;
  196. /**
  197. * Maximum number of words to process on a single stack in asynchronous mode.
  198. *
  199. * @type {number}
  200. * @private
  201. */
  202. goog.ui.AbstractSpellChecker.prototype.asyncWordsPerBatch_ = 1000;
  203. /**
  204. * Current text to process when running in the asynchronous mode.
  205. *
  206. * @type {string|undefined}
  207. * @private
  208. */
  209. goog.ui.AbstractSpellChecker.prototype.asyncText_;
  210. /**
  211. * Current start index of the range that spell-checked correctly.
  212. *
  213. * @type {number|undefined}
  214. * @private
  215. */
  216. goog.ui.AbstractSpellChecker.prototype.asyncRangeStart_;
  217. /**
  218. * Current node with which the asynchronous text is associated.
  219. *
  220. * @type {Node|undefined}
  221. * @private
  222. */
  223. goog.ui.AbstractSpellChecker.prototype.asyncNode_;
  224. /**
  225. * Number of elements processed in the asyncronous mode since last yield.
  226. *
  227. * @type {number}
  228. * @private
  229. */
  230. goog.ui.AbstractSpellChecker.prototype.processedElementsCount_ = 0;
  231. /**
  232. * Markers for the text that does not need to be included in the processing.
  233. *
  234. * For rich text editor this is a list of strings formatted as
  235. * tagName.className or className. If both are specified, the element will be
  236. * excluded if BOTH are matched. If only a className is specified, then we will
  237. * exclude regions with the className. If only one marker is needed, it may be
  238. * passed as a string.
  239. * For plain text editor this is a RegExp that matches the excluded text.
  240. *
  241. * Used exclusively by the derived classes
  242. *
  243. * @type {Array<string>|string|RegExp|undefined}
  244. * @protected
  245. */
  246. goog.ui.AbstractSpellChecker.prototype.excludeMarker;
  247. /**
  248. * Numeric Id of the element that has focus. 0 when not set.
  249. *
  250. * @private {number}
  251. */
  252. goog.ui.AbstractSpellChecker.prototype.focusedElementIndex_ = 0;
  253. /**
  254. * Index for the most recently added misspelled word.
  255. *
  256. * @private {number}
  257. */
  258. goog.ui.AbstractSpellChecker.prototype.lastIndex_ = 0;
  259. /**
  260. * @return {goog.spell.SpellCheck} The handler used for caching and lookups.
  261. */
  262. goog.ui.AbstractSpellChecker.prototype.getSpellCheck = function() {
  263. return this.spellCheck;
  264. };
  265. /**
  266. * Sets the spell checker used for caching and lookups.
  267. * @param {goog.spell.SpellCheck} spellCheck The handler used for caching and
  268. * lookups.
  269. */
  270. goog.ui.AbstractSpellChecker.prototype.setSpellCheck = function(spellCheck) {
  271. this.spellCheck = spellCheck;
  272. };
  273. /**
  274. * Sets the handler used for caching and lookups.
  275. * @param {goog.spell.SpellCheck} handler The handler used for caching and
  276. * lookups.
  277. * @deprecated Use #setSpellCheck instead.
  278. */
  279. goog.ui.AbstractSpellChecker.prototype.setHandler = function(handler) {
  280. this.setSpellCheck(handler);
  281. };
  282. /**
  283. * @return {goog.ui.PopupMenu|undefined} The suggestions menu.
  284. * @protected
  285. */
  286. goog.ui.AbstractSpellChecker.prototype.getMenu = function() {
  287. return this.menu_;
  288. };
  289. /**
  290. * @return {goog.ui.MenuItem|undefined} The menu item for edit word option.
  291. * @protected
  292. */
  293. goog.ui.AbstractSpellChecker.prototype.getMenuEdit = function() {
  294. return this.menuEdit_;
  295. };
  296. /**
  297. * @return {number} The index of the latest misspelled word to be added.
  298. * @protected
  299. */
  300. goog.ui.AbstractSpellChecker.prototype.getLastIndex = function() {
  301. return this.lastIndex_;
  302. };
  303. /**
  304. * @return {number} Increments and returns the index for the next misspelled
  305. * word to be added.
  306. * @protected
  307. */
  308. goog.ui.AbstractSpellChecker.prototype.getNextIndex = function() {
  309. return ++this.lastIndex_;
  310. };
  311. /**
  312. * Sets the marker for the excluded text.
  313. *
  314. * {@see goog.ui.AbstractSpellChecker.prototype.excludeMarker}
  315. *
  316. * @param {Array<string>|string|RegExp|null} marker A RegExp for plain text
  317. * or class names for the rich text spell checker for the elements to
  318. * exclude from checking.
  319. */
  320. goog.ui.AbstractSpellChecker.prototype.setExcludeMarker = function(marker) {
  321. this.excludeMarker = marker || undefined;
  322. };
  323. /**
  324. * Checks spelling for all text.
  325. * Should be overridden by implementation.
  326. */
  327. goog.ui.AbstractSpellChecker.prototype.check = function() {
  328. this.isVisible_ = true;
  329. if (this.markCorrected) {
  330. this.correctedWords_ = new goog.structs.Set();
  331. }
  332. };
  333. /**
  334. * Hides correction UI.
  335. * Should be overridden by implementation.
  336. */
  337. goog.ui.AbstractSpellChecker.prototype.resume = function() {
  338. this.isVisible_ = false;
  339. this.clearWordElements();
  340. this.lastIndex_ = 0;
  341. this.setFocusedElementIndex(0);
  342. var input;
  343. while (input = this.inputElements_.pop()) {
  344. input.parentNode.replaceChild(
  345. this.getDomHelper().createTextNode(input.value), input);
  346. }
  347. if (this.correctedWords_) {
  348. this.correctedWords_.clear();
  349. }
  350. };
  351. /**
  352. * @return {boolean} Whether the correction ui is visible.
  353. */
  354. goog.ui.AbstractSpellChecker.prototype.isVisible = function() {
  355. return this.isVisible_;
  356. };
  357. /**
  358. * Clears the word to element references map used by replace/ignore.
  359. * @protected
  360. */
  361. goog.ui.AbstractSpellChecker.prototype.clearWordElements = function() {
  362. this.wordElements_ = {};
  363. };
  364. /**
  365. * Ignores spelling of word.
  366. *
  367. * @param {string} word Word to add.
  368. */
  369. goog.ui.AbstractSpellChecker.prototype.ignoreWord = function(word) {
  370. this.spellCheck.setWordStatus(word, goog.spell.SpellCheck.WordStatus.IGNORED);
  371. };
  372. /**
  373. * Edits a word.
  374. *
  375. * @param {Element} el An element wrapping the word that should be edited.
  376. * @param {string} old Word to edit.
  377. * @private
  378. */
  379. goog.ui.AbstractSpellChecker.prototype.editWord_ = function(el, old) {
  380. var input = this.getDomHelper().createDom(
  381. goog.dom.TagName.INPUT, {'type': goog.dom.InputType.TEXT, 'value': old});
  382. var w = goog.style.getSize(el).width;
  383. // Minimum width to ensure there's always enough room to type.
  384. if (w < 50) {
  385. w = 50;
  386. }
  387. input.style.width = w + 'px';
  388. el.parentNode.replaceChild(input, el);
  389. try {
  390. input.focus();
  391. goog.dom.selection.setCursorPosition(input, old.length);
  392. } catch (o) {
  393. }
  394. this.inputElements_.push(input);
  395. };
  396. /**
  397. * Replaces word.
  398. *
  399. * @param {Element} el An element wrapping the word that should be replaced.
  400. * @param {string} old Word that was replaced.
  401. * @param {string} word Word to replace with.
  402. */
  403. goog.ui.AbstractSpellChecker.prototype.replaceWord = function(el, old, word) {
  404. if (old != word) {
  405. if (!el.getAttribute(goog.ui.AbstractSpellChecker.ORIGINAL_)) {
  406. el.setAttribute(goog.ui.AbstractSpellChecker.ORIGINAL_, old);
  407. }
  408. goog.dom.setTextContent(el, word);
  409. var status = this.spellCheck.checkWord(word);
  410. // Indicate that the word is corrected unless the status is 'INVALID'.
  411. // (if markCorrected is enabled).
  412. if (this.markCorrected && this.correctedWords_ &&
  413. status != goog.spell.SpellCheck.WordStatus.INVALID) {
  414. this.correctedWords_.add(word);
  415. status = goog.spell.SpellCheck.WordStatus.CORRECTED;
  416. }
  417. // Avoid potential collision with the built-in object namespace. For
  418. // example, 'watch' is a reserved name in FireFox.
  419. var oldIndex = goog.ui.AbstractSpellChecker.toInternalKey_(old);
  420. var newIndex = goog.ui.AbstractSpellChecker.toInternalKey_(word);
  421. // Remove reference between old word and element
  422. var elements = this.wordElements_[oldIndex];
  423. goog.array.remove(elements, el);
  424. if (status != goog.spell.SpellCheck.WordStatus.VALID) {
  425. // Create reference between new word and element
  426. if (this.wordElements_[newIndex]) {
  427. this.wordElements_[newIndex].push(el);
  428. } else {
  429. this.wordElements_[newIndex] = [el];
  430. }
  431. }
  432. // Update element based on status.
  433. this.updateElement(el, word, status);
  434. this.dispatchEvent(goog.events.EventType.CHANGE);
  435. }
  436. };
  437. /**
  438. * Retrieves the array of suggested spelling choices.
  439. *
  440. * @return {Array<string>} Suggested spelling choices.
  441. * @private
  442. */
  443. goog.ui.AbstractSpellChecker.prototype.getSuggestions_ = function() {
  444. // Add new suggestion entries.
  445. var suggestions = this.spellCheck.getSuggestions(
  446. /** @type {string} */ (this.activeWord_));
  447. if (!suggestions[0]) {
  448. var originalWord = this.activeElement_.getAttribute(
  449. goog.ui.AbstractSpellChecker.ORIGINAL_);
  450. if (originalWord && originalWord != this.activeWord_) {
  451. suggestions = this.spellCheck.getSuggestions(originalWord);
  452. }
  453. }
  454. return suggestions;
  455. };
  456. /**
  457. * Displays suggestions menu.
  458. *
  459. * @param {Element} el Element to display menu for.
  460. * @param {goog.events.BrowserEvent|goog.math.Coordinate=} opt_pos Position to
  461. * display menu at relative to the viewport (in client coordinates), or a
  462. * mouse event.
  463. */
  464. goog.ui.AbstractSpellChecker.prototype.showSuggestionsMenu = function(
  465. el, opt_pos) {
  466. this.activeWord_ = goog.dom.getTextContent(el);
  467. this.activeElement_ = el;
  468. // Remove suggestion entries from menu, if any.
  469. while (this.menu_.getChildAt(0) != this.menuSeparator_) {
  470. this.menu_.removeChildAt(0, true).dispose();
  471. }
  472. // Add new suggestion entries.
  473. var suggestions = this.getSuggestions_();
  474. for (var suggestion, i = 0; suggestion = suggestions[i]; i++) {
  475. this.menu_.addChildAt(
  476. new goog.ui.MenuItem(suggestion, suggestion, this.getDomHelper()), i,
  477. true);
  478. }
  479. if (!suggestions[0]) {
  480. /** @desc Item shown in menu when no suggestions are available. */
  481. var MSG_SPELL_NO_SUGGESTIONS = goog.getMsg('No Suggestions');
  482. var item =
  483. new goog.ui.MenuItem(MSG_SPELL_NO_SUGGESTIONS, '', this.getDomHelper());
  484. item.setEnabled(false);
  485. this.menu_.addChildAt(item, 0, true);
  486. }
  487. // Show 'Edit word' option if {@link markCorrected} is enabled and don't show
  488. // 'Ignore' option for corrected words.
  489. if (this.markCorrected) {
  490. var corrected =
  491. this.correctedWords_ && this.correctedWords_.contains(this.activeWord_);
  492. this.menuIgnore_.setVisible(!corrected);
  493. this.menuEdit_.setVisible(true);
  494. } else {
  495. this.menuIgnore_.setVisible(true);
  496. this.menuEdit_.setVisible(false);
  497. }
  498. if (opt_pos) {
  499. if (!(opt_pos instanceof goog.math.Coordinate)) { // it's an event
  500. var posX = opt_pos.clientX;
  501. var posY = opt_pos.clientY;
  502. // Certain implementations which derive from AbstractSpellChecker
  503. // use an iframe in which case the coordinates are relative to
  504. // that iframe's view port.
  505. if (this.getElement().contentDocument ||
  506. this.getElement().contentWindow) {
  507. var offset = goog.style.getClientPosition(this.getElement());
  508. posX += offset.x;
  509. posY += offset.y;
  510. }
  511. opt_pos = new goog.math.Coordinate(posX, posY);
  512. }
  513. this.menu_.showAt(opt_pos.x, opt_pos.y);
  514. } else {
  515. this.menu_.setVisible(true);
  516. }
  517. };
  518. /**
  519. * Initializes suggestions menu. Populates menu with separator and ignore option
  520. * that are always valid. Suggestions are later added above the separator.
  521. *
  522. * @protected
  523. */
  524. goog.ui.AbstractSpellChecker.prototype.initSuggestionsMenu = function() {
  525. this.menu_ = new goog.ui.PopupMenu(this.getDomHelper());
  526. this.menuSeparator_ = new goog.ui.MenuSeparator(this.getDomHelper());
  527. // Leave alone setAllowAutoFocus at default (true). This allows menu to get
  528. // keyboard focus and thus allowing non-mouse users to get to the menu.
  529. /** @desc Ignore entry in suggestions menu. */
  530. var MSG_SPELL_IGNORE = goog.getMsg('Ignore');
  531. /** @desc Edit word entry in suggestions menu. */
  532. var MSG_SPELL_EDIT_WORD = goog.getMsg('Edit Word');
  533. this.menu_.addChild(this.menuSeparator_, true);
  534. this.menuIgnore_ =
  535. new goog.ui.MenuItem(MSG_SPELL_IGNORE, '', this.getDomHelper());
  536. this.menu_.addChild(this.menuIgnore_, true);
  537. this.menuEdit_ =
  538. new goog.ui.MenuItem(MSG_SPELL_EDIT_WORD, '', this.getDomHelper());
  539. this.menuEdit_.setVisible(false);
  540. this.menu_.addChild(this.menuEdit_, true);
  541. this.menu_.setParent(this);
  542. this.menu_.render();
  543. var menuElement = this.menu_.getElement();
  544. goog.asserts.assert(menuElement);
  545. goog.dom.classlist.add(menuElement, this.suggestionsMenuClassName);
  546. goog.events.listen(
  547. this.menu_, goog.ui.Component.EventType.ACTION, this.onCorrectionAction,
  548. false, this);
  549. };
  550. /**
  551. * Handles correction menu actions.
  552. *
  553. * @param {goog.events.Event} event Action event.
  554. * @protected
  555. */
  556. goog.ui.AbstractSpellChecker.prototype.onCorrectionAction = function(event) {
  557. var word = /** @type {string} */ (this.activeWord_);
  558. var el = /** @type {Element} */ (this.activeElement_);
  559. if (event.target == this.menuIgnore_) {
  560. this.ignoreWord(word);
  561. } else if (event.target == this.menuEdit_) {
  562. this.editWord_(el, word);
  563. } else {
  564. this.replaceWord(el, word, event.target.getModel());
  565. this.dispatchEvent(goog.ui.Component.EventType.CHANGE);
  566. }
  567. delete this.activeWord_;
  568. delete this.activeElement_;
  569. };
  570. /**
  571. * Removes spell-checker markup and restore the node to text.
  572. *
  573. * @param {Element} el Word element. MUST have a text node child.
  574. * @protected
  575. */
  576. goog.ui.AbstractSpellChecker.prototype.removeMarkup = function(el) {
  577. var firstChild = el.firstChild;
  578. var text = firstChild.nodeValue;
  579. if (el.nextSibling && el.nextSibling.nodeType == goog.dom.NodeType.TEXT) {
  580. if (el.previousSibling &&
  581. el.previousSibling.nodeType == goog.dom.NodeType.TEXT) {
  582. el.previousSibling.nodeValue =
  583. el.previousSibling.nodeValue + text + el.nextSibling.nodeValue;
  584. this.getDomHelper().removeNode(el.nextSibling);
  585. } else {
  586. el.nextSibling.nodeValue = text + el.nextSibling.nodeValue;
  587. }
  588. } else if (
  589. el.previousSibling &&
  590. el.previousSibling.nodeType == goog.dom.NodeType.TEXT) {
  591. el.previousSibling.nodeValue += text;
  592. } else {
  593. el.parentNode.insertBefore(firstChild, el);
  594. }
  595. this.getDomHelper().removeNode(el);
  596. };
  597. /**
  598. * Updates element based on word status. Either converts it to a text node, or
  599. * merges it with the previous or next text node if the status of the world is
  600. * VALID, in which case the element itself is eliminated.
  601. *
  602. * @param {Element} el Word element.
  603. * @param {string} word Word to update status for.
  604. * @param {goog.spell.SpellCheck.WordStatus} status Status of word.
  605. * @protected
  606. */
  607. goog.ui.AbstractSpellChecker.prototype.updateElement = function(
  608. el, word, status) {
  609. if (this.markCorrected && this.correctedWords_ &&
  610. this.correctedWords_.contains(word)) {
  611. status = goog.spell.SpellCheck.WordStatus.CORRECTED;
  612. }
  613. if (status == goog.spell.SpellCheck.WordStatus.VALID) {
  614. this.removeMarkup(el);
  615. } else {
  616. goog.dom.setProperties(el, this.getElementProperties(status));
  617. }
  618. };
  619. /**
  620. * Generates unique Ids for spell checker elements.
  621. * @param {number=} opt_id Id to suffix with.
  622. * @return {string} Unique element id.
  623. * @protected
  624. */
  625. goog.ui.AbstractSpellChecker.prototype.makeElementId = function(opt_id) {
  626. return this.getId() + '.' + (opt_id ? opt_id : this.getNextIndex());
  627. };
  628. /**
  629. * Returns the span element that matches the given number index.
  630. * @param {number} index Number index that is used in the element id.
  631. * @return {Element} The matching span element or null if no span matches.
  632. * @protected
  633. */
  634. goog.ui.AbstractSpellChecker.prototype.getElementByIndex = function(index) {
  635. return this.getDomHelper().getElement(this.makeElementId(index));
  636. };
  637. /**
  638. * Creates an element for a specified word and stores a reference to it.
  639. *
  640. * @param {string} word Word to create element for.
  641. * @param {goog.spell.SpellCheck.WordStatus} status Status of word.
  642. * @return {!HTMLSpanElement} The created element.
  643. * @protected
  644. */
  645. goog.ui.AbstractSpellChecker.prototype.createWordElement = function(
  646. word, status) {
  647. var parameters = this.getElementProperties(status);
  648. // Add id & tabindex as necessary.
  649. if (!parameters['id']) {
  650. parameters['id'] = this.makeElementId();
  651. }
  652. if (!parameters['tabIndex']) {
  653. parameters['tabIndex'] = -1;
  654. }
  655. var el =
  656. this.getDomHelper().createDom(goog.dom.TagName.SPAN, parameters, word);
  657. goog.a11y.aria.setRole(el, 'menuitem');
  658. goog.a11y.aria.setState(el, 'haspopup', true);
  659. this.registerWordElement(word, el);
  660. return el;
  661. };
  662. /**
  663. * Stores a reference to word element.
  664. *
  665. * @param {string} word The word to store.
  666. * @param {HTMLSpanElement} el The element associated with it.
  667. * @protected
  668. */
  669. goog.ui.AbstractSpellChecker.prototype.registerWordElement = function(
  670. word, el) {
  671. // Avoid potential collision with the built-in object namespace. For
  672. // example, 'watch' is a reserved name in FireFox.
  673. var index = goog.ui.AbstractSpellChecker.toInternalKey_(word);
  674. if (this.wordElements_[index]) {
  675. this.wordElements_[index].push(el);
  676. } else {
  677. this.wordElements_[index] = [el];
  678. }
  679. };
  680. /**
  681. * Returns desired element properties for the specified status.
  682. * Should be overridden by implementation.
  683. *
  684. * @param {goog.spell.SpellCheck.WordStatus} status Status of word.
  685. * @return {Object} Properties to apply to the element.
  686. * @protected
  687. */
  688. goog.ui.AbstractSpellChecker.prototype.getElementProperties =
  689. goog.abstractMethod;
  690. /**
  691. * Handles word change events and updates the word elements accordingly.
  692. *
  693. * @param {goog.spell.SpellCheck.WordChangedEvent} event The event object.
  694. * @private
  695. */
  696. goog.ui.AbstractSpellChecker.prototype.onWordChanged_ = function(event) {
  697. // Avoid potential collision with the built-in object namespace. For
  698. // example, 'watch' is a reserved name in FireFox.
  699. var index = goog.ui.AbstractSpellChecker.toInternalKey_(event.word);
  700. var elements = this.wordElements_[index];
  701. if (elements) {
  702. for (var el, i = 0; el = elements[i]; i++) {
  703. this.updateElement(el, event.word, event.status);
  704. }
  705. }
  706. };
  707. /** @override */
  708. goog.ui.AbstractSpellChecker.prototype.disposeInternal = function() {
  709. if (this.isVisible_) {
  710. // Clears wordElements_
  711. this.resume();
  712. }
  713. goog.events.unlisten(
  714. this.spellCheck, goog.spell.SpellCheck.EventType.WORD_CHANGED,
  715. this.onWordChanged_, false, this);
  716. if (this.menu_) {
  717. this.menu_.dispose();
  718. delete this.menu_;
  719. delete this.menuIgnore_;
  720. delete this.menuSeparator_;
  721. }
  722. delete this.spellCheck;
  723. delete this.wordElements_;
  724. goog.ui.AbstractSpellChecker.superClass_.disposeInternal.call(this);
  725. };
  726. /**
  727. * Precharges local dictionary cache. This is optional, but greatly reduces
  728. * amount of subsequent churn in the DOM tree because most of the words become
  729. * known from the very beginning.
  730. *
  731. * @param {string} text Text to process.
  732. * @param {number} words Max number of words to scan.
  733. * @return {number} number of words actually scanned.
  734. * @protected
  735. */
  736. goog.ui.AbstractSpellChecker.prototype.populateDictionary = function(
  737. text, words) {
  738. this.splitRegex_.lastIndex = 0;
  739. var result;
  740. var numScanned = 0;
  741. while (result = this.splitRegex_.exec(text)) {
  742. if (result[0].length == 0) {
  743. break;
  744. }
  745. var word = result[1];
  746. if (word) {
  747. this.spellCheck.checkWord(word);
  748. ++numScanned;
  749. if (numScanned >= words) {
  750. break;
  751. }
  752. }
  753. }
  754. this.spellCheck.processPending();
  755. return numScanned;
  756. };
  757. /**
  758. * Processes word.
  759. * Should be overridden by implementation.
  760. *
  761. * @param {Node} node Node containing word.
  762. * @param {string} text Word to process.
  763. * @param {goog.spell.SpellCheck.WordStatus} status Status of the word.
  764. * @protected
  765. */
  766. goog.ui.AbstractSpellChecker.prototype.processWord = function(
  767. node, text, status) {
  768. throw Error('Need to override processWord_ in derivative class');
  769. };
  770. /**
  771. * Processes range of text that checks out (contains no unrecognized words).
  772. * Should be overridden by implementation. May contain words and separators.
  773. *
  774. * @param {Node} node Node containing text range.
  775. * @param {string} text text to process.
  776. * @protected
  777. */
  778. goog.ui.AbstractSpellChecker.prototype.processRange = function(node, text) {
  779. throw Error('Need to override processRange_ in derivative class');
  780. };
  781. /**
  782. * Starts asynchronous processing mode.
  783. *
  784. * @protected
  785. */
  786. goog.ui.AbstractSpellChecker.prototype.initializeAsyncMode = function() {
  787. if (this.asyncMode_ || this.processedElementsCount_ ||
  788. this.asyncText_ != null || this.asyncNode_) {
  789. throw Error('Async mode already in progress.');
  790. }
  791. this.asyncMode_ = true;
  792. this.processedElementsCount_ = 0;
  793. delete this.asyncText_;
  794. this.asyncRangeStart_ = 0;
  795. delete this.asyncNode_;
  796. this.blockReadyEvents();
  797. };
  798. /**
  799. * Finalizes asynchronous processing mode. Should be called after there is no
  800. * more text to process and processTextAsync and/or continueAsyncProcessing
  801. * returned FINISHED.
  802. *
  803. * @protected
  804. */
  805. goog.ui.AbstractSpellChecker.prototype.finishAsyncProcessing = function() {
  806. if (!this.asyncMode_ || this.asyncText_ != null || this.asyncNode_) {
  807. throw Error('Async mode not started or there is still text to process.');
  808. }
  809. this.asyncMode_ = false;
  810. this.processedElementsCount_ = 0;
  811. this.unblockReadyEvents();
  812. this.spellCheck.processPending();
  813. };
  814. /**
  815. * Blocks processing of spell checker READY events. This is used in dictionary
  816. * recharge and async mode so that completion is not signaled prematurely.
  817. *
  818. * @protected
  819. */
  820. goog.ui.AbstractSpellChecker.prototype.blockReadyEvents = function() {
  821. goog.events.listen(
  822. this.spellCheck, goog.spell.SpellCheck.EventType.READY,
  823. goog.events.Event.stopPropagation, true);
  824. };
  825. /**
  826. * Unblocks processing of spell checker READY events. This is used in
  827. * dictionary recharge and async mode so that completion is not signaled
  828. * prematurely.
  829. *
  830. * @protected
  831. */
  832. goog.ui.AbstractSpellChecker.prototype.unblockReadyEvents = function() {
  833. goog.events.unlisten(
  834. this.spellCheck, goog.spell.SpellCheck.EventType.READY,
  835. goog.events.Event.stopPropagation, true);
  836. };
  837. /**
  838. * Splits text into individual words and blocks of separators. Calls virtual
  839. * processWord_ and processRange_ methods.
  840. *
  841. * @param {Node} node Node containing text.
  842. * @param {string} text Text to process.
  843. * @return {goog.ui.AbstractSpellChecker.AsyncResult} operation result.
  844. * @protected
  845. */
  846. goog.ui.AbstractSpellChecker.prototype.processTextAsync = function(node, text) {
  847. if (!this.asyncMode_ || this.asyncText_ != null || this.asyncNode_) {
  848. throw Error('Not in async mode or previous text has not been processed.');
  849. }
  850. this.splitRegex_.lastIndex = 0;
  851. var stringSegmentStart = 0;
  852. var result;
  853. while (result = this.splitRegex_.exec(text)) {
  854. if (result[0].length == 0) {
  855. break;
  856. }
  857. var word = result[1];
  858. if (word) {
  859. var status = this.spellCheck.checkWord(word);
  860. if (status != goog.spell.SpellCheck.WordStatus.VALID) {
  861. var precedingText =
  862. text.substr(stringSegmentStart, result.index - stringSegmentStart);
  863. if (precedingText) {
  864. this.processRange(node, precedingText);
  865. }
  866. stringSegmentStart = result.index + word.length;
  867. this.processWord(node, word, status);
  868. }
  869. }
  870. this.processedElementsCount_++;
  871. if (this.processedElementsCount_ > this.asyncWordsPerBatch_) {
  872. this.asyncText_ = text;
  873. this.asyncRangeStart_ = stringSegmentStart;
  874. this.asyncNode_ = node;
  875. this.processedElementsCount_ = 0;
  876. return goog.ui.AbstractSpellChecker.AsyncResult.PENDING;
  877. }
  878. }
  879. var leftoverText = text.substr(stringSegmentStart);
  880. if (leftoverText) {
  881. this.processRange(node, leftoverText);
  882. }
  883. return goog.ui.AbstractSpellChecker.AsyncResult.DONE;
  884. };
  885. /**
  886. * Continues processing started by processTextAsync. Calls virtual
  887. * processWord_ and processRange_ methods.
  888. *
  889. * @return {goog.ui.AbstractSpellChecker.AsyncResult} operation result.
  890. * @protected
  891. */
  892. goog.ui.AbstractSpellChecker.prototype.continueAsyncProcessing = function() {
  893. if (!this.asyncMode_ || this.asyncText_ == null || !this.asyncNode_) {
  894. throw Error('Not in async mode or processing not started.');
  895. }
  896. var node = /** @type {Node} */ (this.asyncNode_);
  897. var stringSegmentStart = this.asyncRangeStart_;
  898. goog.asserts.assertNumber(stringSegmentStart);
  899. var text = this.asyncText_;
  900. var result;
  901. while (result = this.splitRegex_.exec(text)) {
  902. if (result[0].length == 0) {
  903. break;
  904. }
  905. var word = result[1];
  906. if (word) {
  907. var status = this.spellCheck.checkWord(word);
  908. if (status != goog.spell.SpellCheck.WordStatus.VALID) {
  909. var precedingText =
  910. text.substr(stringSegmentStart, result.index - stringSegmentStart);
  911. if (precedingText) {
  912. this.processRange(node, precedingText);
  913. }
  914. stringSegmentStart = result.index + word.length;
  915. this.processWord(node, word, status);
  916. }
  917. }
  918. this.processedElementsCount_++;
  919. if (this.processedElementsCount_ > this.asyncWordsPerBatch_) {
  920. this.processedElementsCount_ = 0;
  921. this.asyncRangeStart_ = stringSegmentStart;
  922. return goog.ui.AbstractSpellChecker.AsyncResult.PENDING;
  923. }
  924. }
  925. delete this.asyncText_;
  926. this.asyncRangeStart_ = 0;
  927. delete this.asyncNode_;
  928. var leftoverText = text.substr(stringSegmentStart);
  929. if (leftoverText) {
  930. this.processRange(node, leftoverText);
  931. }
  932. return goog.ui.AbstractSpellChecker.AsyncResult.DONE;
  933. };
  934. /**
  935. * Converts a word to an internal key representation. This is necessary to
  936. * avoid collisions with object's internal namespace. Only words that are
  937. * reserved need to be escaped.
  938. *
  939. * @param {string} word The word to map.
  940. * @return {string} The index.
  941. * @private
  942. */
  943. goog.ui.AbstractSpellChecker.toInternalKey_ = function(word) {
  944. if (word in Object.prototype) {
  945. return goog.ui.AbstractSpellChecker.KEY_PREFIX_ + word;
  946. }
  947. return word;
  948. };
  949. /**
  950. * Navigate keyboard focus in the given direction.
  951. *
  952. * @param {goog.ui.AbstractSpellChecker.Direction} direction The direction to
  953. * navigate in.
  954. * @return {boolean} Whether the action is handled here. If not handled
  955. * here, the initiating event may be propagated.
  956. * @protected
  957. */
  958. goog.ui.AbstractSpellChecker.prototype.navigate = function(direction) {
  959. var handled = false;
  960. var isMovingToNextWord =
  961. direction == goog.ui.AbstractSpellChecker.Direction.NEXT;
  962. var focusedIndex = this.getFocusedElementIndex();
  963. var el;
  964. do {
  965. // Determine new index based on given direction.
  966. focusedIndex += isMovingToNextWord ? 1 : -1;
  967. if (focusedIndex < 1 || focusedIndex > this.getLastIndex()) {
  968. // Exit the loop, because this focusedIndex cannot have an element.
  969. handled = true;
  970. break;
  971. }
  972. // Word elements are removed during the correction action. If no element is
  973. // found for the new focusedIndex, then try again with the next value.
  974. } while (!(el = this.getElementByIndex(focusedIndex)));
  975. if (el) {
  976. this.setFocusedElementIndex(focusedIndex);
  977. this.focusOnElement(el);
  978. handled = true;
  979. }
  980. return handled;
  981. };
  982. /**
  983. * Returns the index of the currently focussed invalid word element. This index
  984. * starts at one instead of zero.
  985. *
  986. * @return {number} the index of the currently focussed element
  987. * @protected
  988. */
  989. goog.ui.AbstractSpellChecker.prototype.getFocusedElementIndex = function() {
  990. return this.focusedElementIndex_;
  991. };
  992. /**
  993. * Sets the index of the currently focussed invalid word element. This index
  994. * should start at one instead of zero.
  995. *
  996. * @param {number} focusElementIndex the index of the currently focussed element
  997. * @protected
  998. */
  999. goog.ui.AbstractSpellChecker.prototype.setFocusedElementIndex = function(
  1000. focusElementIndex) {
  1001. this.focusedElementIndex_ = focusElementIndex;
  1002. };
  1003. /**
  1004. * Sets the focus on the provided word element.
  1005. *
  1006. * @param {Element} element The word element that should receive focus.
  1007. * @protected
  1008. */
  1009. goog.ui.AbstractSpellChecker.prototype.focusOnElement = function(element) {
  1010. element.focus();
  1011. };
  1012. /**
  1013. * Constants for representing the direction while navigating.
  1014. *
  1015. * @enum {number}
  1016. */
  1017. goog.ui.AbstractSpellChecker.Direction = {
  1018. PREVIOUS: 0,
  1019. NEXT: 1
  1020. };
  1021. /**
  1022. * Constants for the result of asynchronous processing.
  1023. * @enum {number}
  1024. */
  1025. goog.ui.AbstractSpellChecker.AsyncResult = {
  1026. /**
  1027. * Caller must reschedule operation and call continueAsyncProcessing on the
  1028. * new stack frame.
  1029. */
  1030. PENDING: 1,
  1031. /**
  1032. * Current element has been fully processed. Caller can call
  1033. * processTextAsync or finishAsyncProcessing.
  1034. */
  1035. DONE: 2
  1036. };