Debian Codegraph @

closure-library/closure/goog/ui/ac/renderer.js

raw
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 /**
16 * @fileoverview Class for rendering the results of an auto complete and
17 * allow the user to select an row.
18 *
19 */
20
21 goog.provide('goog.ui.ac.Renderer');
22 goog.provide('goog.ui.ac.Renderer.CustomRenderer');
23
24 goog.require('goog.a11y.aria');
25 goog.require('goog.a11y.aria.Role');
26 goog.require('goog.a11y.aria.State');
27 goog.require('goog.array');
28 goog.require('goog.asserts');
29 goog.require('goog.dispose');
30 goog.require('goog.dom');
31 goog.require('goog.dom.NodeType');
32 goog.require('goog.dom.TagName');
33 goog.require('goog.dom.classlist');
34 goog.require('goog.events');
35 goog.require('goog.events.EventTarget');
36 goog.require('goog.events.EventType');
37 goog.require('goog.fx.dom.FadeInAndShow');
38 goog.require('goog.fx.dom.FadeOutAndHide');
39 goog.require('goog.positioning');
40 goog.require('goog.positioning.Corner');
41 goog.require('goog.positioning.Overflow');
42 goog.require('goog.string');
43 goog.require('goog.style');
44 goog.require('goog.ui.IdGenerator');
45 goog.require('goog.ui.ac.AutoComplete');
46
47
48
49 /**
50 * Class for rendering the results of an auto-complete in a drop down list.
51 *
52 * @constructor
53 * @param {Element=} opt_parentNode optional reference to the parent element
54 * that will hold the autocomplete elements. goog.dom.getDocument().body
55 * will be used if this is null.
56 * @param {?({renderRow}|{render})=} opt_customRenderer Custom full renderer to
57 * render each row. Should be something with a renderRow or render method.
58 * @param {boolean=} opt_rightAlign Determines if the autocomplete will always
59 * be right aligned. False by default.
60 * @param {boolean=} opt_useStandardHighlighting Determines if standard
61 * highlighting should be applied to each row of data. Standard highlighting
62 * bolds every matching substring for a given token in each row. True by
63 * default.
64 * @extends {goog.events.EventTarget}
65 * @suppress {underscore}
66 */
67 goog.ui.ac.Renderer = function(
68 opt_parentNode, opt_customRenderer, opt_rightAlign,
69 opt_useStandardHighlighting) {
70 goog.ui.ac.Renderer.base(this, 'constructor');
71
72 /**
73 * Reference to the parent element that will hold the autocomplete elements
74 * @type {Element}
75 * @private
76 */
77 this.parent_ = opt_parentNode || goog.dom.getDocument().body;
78
79 /**
80 * Dom helper for the parent element's document.
81 * @type {goog.dom.DomHelper}
82 * @private
83 */
84 this.dom_ = goog.dom.getDomHelper(this.parent_);
85
86 /**
87 * Whether to reposition the autocomplete UI below the target node
88 * @type {boolean}
89 * @private
90 */
91 this.reposition_ = !opt_parentNode;
92
93 /**
94 * Reference to the main element that controls the rendered autocomplete
95 * @type {Element}
96 * @private
97 */
98 this.element_ = null;
99
100 /**
101 * The current token that has been entered
102 * @type {string}
103 * @private
104 */
105 this.token_ = '';
106
107 /**
108 * Array used to store the current set of rows being displayed
109 * @type {Array<!Object>}
110 * @private
111 */
112 this.rows_ = [];
113
114 /**
115 * Array of the node divs that hold each result that is being displayed.
116 * @type {Array<Element>}
117 * @protected
118 * @suppress {underscore|visibility}
119 */
120 this.rowDivs_ = [];
121
122 /**
123 * The index of the currently highlighted row
124 * @type {number}
125 * @protected
126 * @suppress {underscore|visibility}
127 */
128 this.hilitedRow_ = -1;
129
130 /**
131 * The time that the rendering of the menu rows started
132 * @type {number}
133 * @protected
134 * @suppress {underscore|visibility}
135 */
136 this.startRenderingRows_ = -1;
137
138 /**
139 * Store the current state for the renderer
140 * @type {boolean}
141 * @private
142 */
143 this.visible_ = false;
144
145 /**
146 * Classname for the main element. This must be a single valid class name.
147 * @type {string}
148 */
149 this.className = goog.getCssName('ac-renderer');
150
151 /**
152 * Classname for row divs. This must be a single valid class name.
153 * @type {string}
154 */
155 this.rowClassName = goog.getCssName('ac-row');
156
157 // TODO(gboyer): Remove this as soon as we remove references and ensure that
158 // no groups are pushing javascript using this.
159 /**
160 * The old class name for active row. This name is deprecated because its
161 * name is generic enough that a typical implementation would require a
162 * descendant selector.
163 * Active row will have rowClassName & activeClassName &
164 * legacyActiveClassName.
165 * @type {string}
166 * @private
167 */
168 this.legacyActiveClassName_ = goog.getCssName('active');
169
170 /**
171 * Class name for active row div. This must be a single valid class name.
172 * Active row will have rowClassName & activeClassName &
173 * legacyActiveClassName.
174 * @type {string}
175 */
176 this.activeClassName = goog.getCssName('ac-active');
177
178 /**
179 * Class name for the bold tag highlighting the matched part of the text.
180 * @type {string}
181 */
182 this.highlightedClassName = goog.getCssName('ac-highlighted');
183
184 /**
185 * Custom full renderer
186 * @type {?({renderRow}|{render})}
187 * @private
188 */
189 this.customRenderer_ = opt_customRenderer || null;
190
191 /**
192 * Flag to indicate whether standard highlighting should be applied.
193 * this is set to true if left unspecified to retain existing
194 * behaviour for autocomplete clients
195 * @type {boolean}
196 * @private
197 */
198 this.useStandardHighlighting_ =
199 opt_useStandardHighlighting != null ? opt_useStandardHighlighting : true;
200
201 /**
202 * Flag to indicate whether matches should be done on whole words instead
203 * of any string.
204 * @type {boolean}
205 * @private
206 */
207 this.matchWordBoundary_ = true;
208
209 /**
210 * Flag to set all tokens as highlighted in the autocomplete row.
211 * @type {boolean}
212 * @private
213 */
214 this.highlightAllTokens_ = false;
215
216 /**
217 * Determines if the autocomplete will always be right aligned
218 * @type {boolean}
219 * @private
220 */
221 this.rightAlign_ = !!opt_rightAlign;
222
223 /**
224 * Whether to align with top of target field
225 * @type {boolean}
226 * @private
227 */
228 this.topAlign_ = false;
229
230 /**
231 * Duration (in msec) of fade animation when menu is shown/hidden.
232 * Setting to 0 (default) disables animation entirely.
233 * @type {number}
234 * @private
235 */
236 this.menuFadeDuration_ = 0;
237
238 /**
239 * Whether we should limit the dropdown from extending past the bottom of the
240 * screen and instead show a scrollbar on the dropdown.
241 * @type {boolean}
242 * @private
243 */
244 this.showScrollbarsIfTooLarge_ = false;
245
246 /**
247 * Animation in progress, if any.
248 * @type {goog.fx.Animation|undefined}
249 */
250 this.animation_;
251 };
252 goog.inherits(goog.ui.ac.Renderer, goog.events.EventTarget);
253
254
255 /**
256 * The anchor element to position the rendered autocompleter against.
257 * @type {Element}
258 * @private
259 */
260 goog.ui.ac.Renderer.prototype.anchorElement_;
261
262
263 /**
264 * The anchor element to position the rendered autocompleter against.
265 * @protected {Element|undefined}
266 */
267 goog.ui.ac.Renderer.prototype.target_;
268
269
270 /**
271 * The element on which to base the width of the autocomplete.
272 * @protected {Node}
273 */
274 goog.ui.ac.Renderer.prototype.widthProvider_;
275
276
277 /**
278 * The border width of the autocomplete dropdown, only used in calculating the
279 * dropdown width.
280 * @private {number}
281 */
282 goog.ui.ac.Renderer.prototype.borderWidth_ = 0;
283
284
285 /**
286 * A flag used to make sure we highlight only one match in the rendered row.
287 * @private {boolean}
288 */
289 goog.ui.ac.Renderer.prototype.wasHighlightedAtLeastOnce_;
290
291
292 /**
293 * The delay before mouseover events are registered, in milliseconds
294 * @type {number}
295 * @const
296 */
297 goog.ui.ac.Renderer.DELAY_BEFORE_MOUSEOVER = 300;
298
299
300 /**
301 * Gets the renderer's element.
302 * @return {Element} The main element that controls the rendered autocomplete.
303 */
304 goog.ui.ac.Renderer.prototype.getElement = function() {
305 return this.element_;
306 };
307
308
309 /**
310 * Sets the width provider element. The provider is only used on redraw and as
311 * such will not automatically update on resize.
312 * @param {Node} widthProvider The element whose width should be mirrored.
313 * @param {number=} opt_borderWidth The with of the border of the autocomplete,
314 * which will be subtracted from the width of the autocomplete dropdown.
315 */
316 goog.ui.ac.Renderer.prototype.setWidthProvider = function(
317 widthProvider, opt_borderWidth) {
318 this.widthProvider_ = widthProvider;
319 if (opt_borderWidth) {
320 this.borderWidth_ = opt_borderWidth;
321 }
322 };
323
324
325 /**
326 * Set whether to align autocomplete to top of target element
327 * @param {boolean} align If true, align to top.
328 */
329 goog.ui.ac.Renderer.prototype.setTopAlign = function(align) {
330 this.topAlign_ = align;
331 };
332
333
334 /**
335 * @return {boolean} Whether we should be aligning to the top of
336 * the target element.
337 */
338 goog.ui.ac.Renderer.prototype.getTopAlign = function() {
339 return this.topAlign_;
340 };
341
342
343 /**
344 * Set whether to align autocomplete to the right of the target element.
345 * @param {boolean} align If true, align to right.
346 */
347 goog.ui.ac.Renderer.prototype.setRightAlign = function(align) {
348 this.rightAlign_ = align;
349 };
350
351
352 /**
353 * @return {boolean} Whether the autocomplete menu should be right aligned.
354 */
355 goog.ui.ac.Renderer.prototype.getRightAlign = function() {
356 return this.rightAlign_;
357 };
358
359
360 /**
361 * @param {boolean} show Whether we should limit the dropdown from extending
362 * past the bottom of the screen and instead show a scrollbar on the
363 * dropdown.
364 */
365 goog.ui.ac.Renderer.prototype.setShowScrollbarsIfTooLarge = function(show) {
366 this.showScrollbarsIfTooLarge_ = show;
367 };
368
369
370 /**
371 * Set whether or not standard highlighting should be used when rendering rows.
372 * @param {boolean} useStandardHighlighting true if standard highlighting used.
373 */
374 goog.ui.ac.Renderer.prototype.setUseStandardHighlighting = function(
375 useStandardHighlighting) {
376 this.useStandardHighlighting_ = useStandardHighlighting;
377 };
378
379
380 /**
381 * @param {boolean} matchWordBoundary Determines whether matches should be
382 * higlighted only when the token matches text at a whole-word boundary.
383 * True by default.
384 */
385 goog.ui.ac.Renderer.prototype.setMatchWordBoundary = function(
386 matchWordBoundary) {
387 this.matchWordBoundary_ = matchWordBoundary;
388 };
389
390
391 /**
392 * Set whether or not to highlight all matching tokens rather than just the
393 * first.
394 * @param {boolean} highlightAllTokens Whether to highlight all matching tokens
395 * rather than just the first.
396 */
397 goog.ui.ac.Renderer.prototype.setHighlightAllTokens = function(
398 highlightAllTokens) {
399 this.highlightAllTokens_ = highlightAllTokens;
400 };
401
402
403 /**
404 * Sets the duration (in msec) of the fade animation when menu is shown/hidden.
405 * Setting to 0 (default) disables animation entirely.
406 * @param {number} duration Duration (in msec) of the fade animation (or 0 for
407 * no animation).
408 */
409 goog.ui.ac.Renderer.prototype.setMenuFadeDuration = function(duration) {
410 this.menuFadeDuration_ = duration;
411 };
412
413
414 /**
415 * Sets the anchor element for the subsequent call to renderRows.
416 * @param {Element} anchor The anchor element.
417 */
418 goog.ui.ac.Renderer.prototype.setAnchorElement = function(anchor) {
419 this.anchorElement_ = anchor;
420 };
421
422
423 /**
424 * @return {Element} The anchor element.
425 * @protected
426 */
427 goog.ui.ac.Renderer.prototype.getAnchorElement = function() {
428 return this.anchorElement_;
429 };
430
431
432 /**
433 * Render the autocomplete UI
434 *
435 * @param {Array<!Object>} rows Matching UI rows.
436 * @param {string} token Token we are currently matching against.
437 * @param {Element=} opt_target Current HTML node, will position popup beneath
438 * this node.
439 */
440 goog.ui.ac.Renderer.prototype.renderRows = function(rows, token, opt_target) {
441 this.token_ = token;
442 this.rows_ = rows;
443 this.hilitedRow_ = -1;
444 this.startRenderingRows_ = goog.now();
445 this.target_ = opt_target;
446 this.rowDivs_ = [];
447 this.redraw();
448 };
449
450
451 /**
452 * Hide the object.
453 */
454 goog.ui.ac.Renderer.prototype.dismiss = function() {
455 if (this.visible_) {
456 this.visible_ = false;
457 this.toggleAriaMarkup_(false /* isShown */);
458
459 if (this.menuFadeDuration_ > 0) {
460 goog.dispose(this.animation_);
461 this.animation_ =
462 new goog.fx.dom.FadeOutAndHide(this.element_, this.menuFadeDuration_);
463 this.animation_.play();
464 } else {
465 goog.style.setElementShown(this.element_, false);
466 }
467 }
468 };
469
470
471 /**
472 * Show the object.
473 */
474 goog.ui.ac.Renderer.prototype.show = function() {
475 if (!this.visible_) {
476 this.visible_ = true;
477 this.toggleAriaMarkup_(true /* isShown */);
478
479 if (this.menuFadeDuration_ > 0) {
480 goog.dispose(this.animation_);
481 this.animation_ =
482 new goog.fx.dom.FadeInAndShow(this.element_, this.menuFadeDuration_);
483 this.animation_.play();
484 } else {
485 goog.style.setElementShown(this.element_, true);
486 }
487 }
488 };
489
490
491 /**
492 * Toggle the ARIA markup to add popup semantics when the target is shown and
493 * to remove them when it is hidden.
494 * @param {boolean} isShown Whether the menu is being shown.
495 * @private
496 */
497 goog.ui.ac.Renderer.prototype.toggleAriaMarkup_ = function(isShown) {
498 if (!this.target_) {
499 return;
500 }
501
502 goog.a11y.aria.setState(this.target_, goog.a11y.aria.State.HASPOPUP, isShown);
503 goog.a11y.aria.setState(
504 goog.asserts.assert(this.element_), goog.a11y.aria.State.EXPANDED,
505 isShown);
506 goog.a11y.aria.setState(this.target_, goog.a11y.aria.State.EXPANDED, isShown);
507 if (isShown) {
508 goog.a11y.aria.setState(
509 this.target_, goog.a11y.aria.State.OWNS, this.element_.id);
510 } else {
511 goog.a11y.aria.removeState(this.target_, goog.a11y.aria.State.OWNS);
512 goog.a11y.aria.setActiveDescendant(this.target_, null);
513 }
514 };
515
516
517 /**
518 * @return {boolean} True if the object is visible.
519 */
520 goog.ui.ac.Renderer.prototype.isVisible = function() {
521 return this.visible_;
522 };
523
524
525 /**
526 * Sets the 'active' class of the nth item.
527 * @param {number} index Index of the item to highlight.
528 */
529 goog.ui.ac.Renderer.prototype.hiliteRow = function(index) {
530 var row =
531 index >= 0 && index < this.rows_.length ? this.rows_[index] : undefined;
532 var rowDiv = index >= 0 && index < this.rowDivs_.length ?
533 this.rowDivs_[index] :
534 undefined;
535
536 var evtObj = /** @lends {goog.events.Event.prototype} */ ({
537 type: goog.ui.ac.AutoComplete.EventType.ROW_HILITE,
538 rowNode: rowDiv,
539 row: row ? row.data : null
540 });
541 if (this.dispatchEvent(evtObj)) {
542 this.hiliteNone();
543 this.hilitedRow_ = index;
544 if (rowDiv) {
545 goog.dom.classlist.addAll(
546 rowDiv, [this.activeClassName, this.legacyActiveClassName_]);
547 if (this.target_) {
548 goog.a11y.aria.setActiveDescendant(this.target_, rowDiv);
549 }
550 goog.style.scrollIntoContainerView(rowDiv, this.element_);
551 }
552 }
553 };
554
555
556 /**
557 * Removes the 'active' class from the currently selected row.
558 */
559 goog.ui.ac.Renderer.prototype.hiliteNone = function() {
560 if (this.hilitedRow_ >= 0) {
561 goog.dom.classlist.removeAll(
562 goog.asserts.assert(this.rowDivs_[this.hilitedRow_]),
563 [this.activeClassName, this.legacyActiveClassName_]);
564 }
565 };
566
567
568 /**
569 * Sets the 'active' class of the item with a given id.
570 * @param {number} id Id of the row to hilight. If id is -1 then no rows get
571 * hilited.
572 */
573 goog.ui.ac.Renderer.prototype.hiliteId = function(id) {
574 if (id == -1) {
575 this.hiliteRow(-1);
576 } else {
577 for (var i = 0; i < this.rows_.length; i++) {
578 if (this.rows_[i].id == id) {
579 this.hiliteRow(i);
580 return;
581 }
582 }
583 }
584 };
585
586
587 /**
588 * Sets CSS classes on autocomplete conatainer element.
589 *
590 * @param {Element} elem The container element.
591 * @private
592 */
593 goog.ui.ac.Renderer.prototype.setMenuClasses_ = function(elem) {
594 goog.asserts.assert(elem);
595 // Legacy clients may set the renderer's className to a space-separated list
596 // or even have a trailing space.
597 goog.dom.classlist.addAll(elem, goog.string.trim(this.className).split(' '));
598 };
599
600
601 /**
602 * If the main HTML element hasn't been made yet, creates it and appends it
603 * to the parent.
604 * @private
605 */
606 goog.ui.ac.Renderer.prototype.maybeCreateElement_ = function() {
607 if (!this.element_) {
608 // Make element and add it to the parent
609 var el = this.dom_.createDom(goog.dom.TagName.DIV, {style: 'display:none'});
610 if (this.showScrollbarsIfTooLarge_) {
611 // Make sure that the dropdown will get scrollbars if it isn't large
612 // enough to show all rows.
613 el.style.overflowY = 'auto';
614 }
615 this.element_ = el;
616 this.setMenuClasses_(el);
617 goog.a11y.aria.setRole(el, goog.a11y.aria.Role.LISTBOX);
618
619 el.id = goog.ui.IdGenerator.getInstance().getNextUniqueId();
620
621 this.dom_.appendChild(this.parent_, el);
622
623 // Add this object as an event handler
624 goog.events.listen(
625 el, goog.events.EventType.CLICK, this.handleClick_, false, this);
626 goog.events.listen(
627 el, goog.events.EventType.MOUSEDOWN, this.handleMouseDown_, false,
628 this);
629 goog.events.listen(
630 el, goog.events.EventType.MOUSEOVER, this.handleMouseOver_, false,
631 this);
632 }
633 };
634
635
636 /**
637 * Redraw (or draw if this is the first call) the rendered auto-complete drop
638 * down.
639 */
640 goog.ui.ac.Renderer.prototype.redraw = function() {
641 // Create the element if it doesn't yet exist
642 this.maybeCreateElement_();
643
644 // For top aligned with target (= bottom aligned element),
645 // we need to hide and then add elements while hidden to prevent
646 // visible repositioning
647 if (this.topAlign_) {
648 this.element_.style.visibility = 'hidden';
649 }
650
651 if (this.widthProvider_) {
652 var width = this.widthProvider_.clientWidth - this.borderWidth_ + 'px';
653 this.element_.style.minWidth = width;
654 }
655
656 // Remove the current child nodes
657 this.rowDivs_.length = 0;
658 this.dom_.removeChildren(this.element_);
659
660 // Generate the new rows (use forEach so we can change rows_ from an
661 // array to a different datastructure if required)
662 if (this.customRenderer_ && this.customRenderer_.render) {
663 this.customRenderer_.render(this, this.element_, this.rows_, this.token_);
664 } else {
665 var curRow = null;
666 goog.array.forEach(this.rows_, function(row) {
667 row = this.renderRowHtml(row, this.token_);
668 if (this.topAlign_) {
669 // Aligned with top of target = best match at bottom
670 this.element_.insertBefore(row, curRow);
671 } else {
672 this.dom_.appendChild(this.element_, row);
673 }
674 curRow = row;
675 }, this);
676 }
677
678 // Don't show empty result sets
679 if (this.rows_.length == 0) {
680 this.dismiss();
681 return;
682 } else {
683 this.show();
684 }
685
686 this.reposition();
687
688 // Make the autocompleter unselectable, so that it
689 // doesn't steal focus from the input field when clicked.
690 goog.style.setUnselectable(this.element_, true);
691 };
692
693
694 /**
695 * @return {goog.positioning.Corner} The anchor corner to position the popup at.
696 * @protected
697 */
698 goog.ui.ac.Renderer.prototype.getAnchorCorner = function() {
699 var anchorCorner = this.rightAlign_ ? goog.positioning.Corner.BOTTOM_RIGHT :
700 goog.positioning.Corner.BOTTOM_LEFT;
701 if (this.topAlign_) {
702 anchorCorner = goog.positioning.flipCornerVertical(anchorCorner);
703 }
704 return anchorCorner;
705 };
706
707
708 /**
709 * Repositions the auto complete popup relative to the location node, if it
710 * exists and the auto position has been set.
711 */
712 goog.ui.ac.Renderer.prototype.reposition = function() {
713 if (this.target_ && this.reposition_) {
714 var anchorElement = this.anchorElement_ || this.target_;
715 var anchorCorner = this.getAnchorCorner();
716
717 var overflowMode = goog.positioning.Overflow.ADJUST_X_EXCEPT_OFFSCREEN;
718 if (this.showScrollbarsIfTooLarge_) {
719 // positionAtAnchor will set the height of this.element_ when it runs
720 // (because of RESIZE_HEIGHT), and it will never increase it relative to
721 // its current value when it runs again. But if the user scrolls their
722 // page, then we might actually want a bigger height when the dropdown is
723 // displayed next time. So we clear the height before calling
724 // positionAtAnchor, so it is free to set the height as large as it
725 // chooses.
726 this.element_.style.height = '';
727 overflowMode |= goog.positioning.Overflow.RESIZE_HEIGHT;
728 }
729
730 goog.positioning.positionAtAnchor(
731 anchorElement, anchorCorner, this.element_,
732 goog.positioning.flipCornerVertical(anchorCorner), null, null,
733 overflowMode);
734
735 if (this.topAlign_) {
736 // This flickers, but is better than the alternative of positioning
737 // in the wrong place and then moving.
738 this.element_.style.visibility = 'visible';
739 }
740 }
741 };
742
743
744 /**
745 * Sets whether the renderer should try to determine where to position the
746 * drop down.
747 * @param {boolean} auto Whether to autoposition the drop down.
748 */
749 goog.ui.ac.Renderer.prototype.setAutoPosition = function(auto) {
750 this.reposition_ = auto;
751 };
752
753
754 /**
755 * @return {boolean} Whether the drop down will be autopositioned.
756 * @protected
757 */
758 goog.ui.ac.Renderer.prototype.getAutoPosition = function() {
759 return this.reposition_;
760 };
761
762
763 /**
764 * @return {Element} The target element.
765 * @protected
766 */
767 goog.ui.ac.Renderer.prototype.getTarget = function() {
768 return this.target_ || null;
769 };
770
771
772 /**
773 * Disposes of the renderer and its associated HTML.
774 * @override
775 * @protected
776 */
777 goog.ui.ac.Renderer.prototype.disposeInternal = function() {
778 if (this.element_) {
779 goog.events.unlisten(
780 this.element_, goog.events.EventType.CLICK, this.handleClick_, false,
781 this);
782 goog.events.unlisten(
783 this.element_, goog.events.EventType.MOUSEDOWN, this.handleMouseDown_,
784 false, this);
785 goog.events.unlisten(
786 this.element_, goog.events.EventType.MOUSEOVER, this.handleMouseOver_,
787 false, this);
788 this.dom_.removeNode(this.element_);
789 this.element_ = null;
790 this.visible_ = false;
791 }
792
793 goog.dispose(this.animation_);
794 this.parent_ = null;
795
796 goog.ui.ac.Renderer.base(this, 'disposeInternal');
797 };
798
799
800 /**
801 * Generic function that takes a row and renders a DOM structure for that row.
802 *
803 * Normally this will only be matching a maximum of 20 or so items. Even with
804 * 40 rows, DOM this building is fine.
805 *
806 * @param {Object} row Object representing row.
807 * @param {string} token Token to highlight.
808 * @param {Node} node The node to render into.
809 * @private
810 */
811 goog.ui.ac.Renderer.prototype.renderRowContents_ = function(row, token, node) {
812 goog.dom.setTextContent(node, row.data.toString());
813 };
814
815
816 /**
817 * Goes through a node and all of its child nodes, replacing HTML text that
818 * matches a token with <b>token</b>.
819 * The replacement will happen on the first match or all matches depending on
820 * this.highlightAllTokens_ value.
821 *
822 * @param {Node} node Node to match.
823 * @param {string|Array<string>} tokenOrArray Token to match or array of tokens
824 * to match. By default, only the first match will be highlighted. If
825 * highlightAllTokens is set, then all tokens appearing at the start of a
826 * word, in whatever order and however many times, will be highlighted.
827 * @private
828 */
829 goog.ui.ac.Renderer.prototype.startHiliteMatchingText_ = function(
830 node, tokenOrArray) {
831 this.wasHighlightedAtLeastOnce_ = false;
832 this.hiliteMatchingText_(node, tokenOrArray);
833 };
834
835
836 /**
837 * @param {Node} node Node to match.
838 * @param {string|Array<string>} tokenOrArray Token to match or array of tokens
839 * to match.
840 * @private
841 */
842 goog.ui.ac.Renderer.prototype.hiliteMatchingText_ = function(
843 node, tokenOrArray) {
844 if (!this.highlightAllTokens_ && this.wasHighlightedAtLeastOnce_) {
845 return;
846 }
847
848 if (node.nodeType == goog.dom.NodeType.TEXT) {
849 var rest = null;
850 if (goog.isArray(tokenOrArray) && tokenOrArray.length > 1 &&
851 !this.highlightAllTokens_) {
852 rest = goog.array.slice(tokenOrArray, 1);
853 }
854
855 var token = this.getTokenRegExp_(tokenOrArray);
856 if (token.length == 0) return;
857
858 var text = node.nodeValue;
859
860 // Create a regular expression to match a token at the beginning of a line
861 // or preceded by non-alpha-numeric characters. Note: token could have |
862 // operators in it, so we need to parenthesise it before adding \b to it.
863 // or preceded by non-alpha-numeric characters
864 //
865 // NOTE(user): When using word matches, this used to have
866 // a (^|\\W+) clause where it now has \\b but it caused various
867 // browsers to hang on really long strings. The (^|\\W+) matcher was also
868 // unnecessary, because \b already checks that the character before the
869 // is a non-word character, and ^ matches the start of the line or following
870 // a line terminator character, which is also \W. The regexp also used to
871 // have a capturing match before the \\b, which would capture the
872 // non-highlighted content, but that caused the regexp matching to run much
873 // slower than the current version.
874 var re = this.matchWordBoundary_ ?
875 new RegExp('\\b(?:' + token + ')', 'gi') :
876 new RegExp(token, 'gi');
877 var textNodes = [];
878 var lastIndex = 0;
879
880 // Find all matches
881 // Note: text.split(re) has inconsistencies between IE and FF, so
882 // manually recreated the logic
883 var match = re.exec(text);
884 var numMatches = 0;
885 while (match) {
886 numMatches++;
887 textNodes.push(text.substring(lastIndex, match.index));
888 textNodes.push(text.substring(match.index, re.lastIndex));
889 lastIndex = re.lastIndex;
890 match = re.exec(text);
891 }
892 textNodes.push(text.substring(lastIndex));
893
894 // Replace the tokens with bolded text. Each pair of textNodes
895 // (starting at index idx) includes a node of text before the bolded
896 // token, and a node (at idx + 1) consisting of what should be
897 // enclosed in bold tags.
898 if (textNodes.length > 1) {
899 var maxNumToBold = !this.highlightAllTokens_ ? 1 : numMatches;
900 for (var i = 0; i < maxNumToBold; i++) {
901 var idx = 2 * i;
902
903 node.nodeValue = textNodes[idx];
904 var boldTag = this.dom_.createElement(goog.dom.TagName.B);
905 boldTag.className = this.highlightedClassName;
906 this.dom_.appendChild(
907 boldTag, this.dom_.createTextNode(textNodes[idx + 1]));
908 boldTag = node.parentNode.insertBefore(boldTag, node.nextSibling);
909 node.parentNode.insertBefore(
910 this.dom_.createTextNode(''), boldTag.nextSibling);
911 node = boldTag.nextSibling;
912 }
913
914 // Append the remaining text nodes to the end.
915 var remainingTextNodes = goog.array.slice(textNodes, maxNumToBold * 2);
916 node.nodeValue = remainingTextNodes.join('');
917
918 this.wasHighlightedAtLeastOnce_ = true;
919 } else if (rest) {
920 this.hiliteMatchingText_(node, rest);
921 }
922 } else {
923 var child = node.firstChild;
924 while (child) {
925 var nextChild = child.nextSibling;
926 this.hiliteMatchingText_(child, tokenOrArray);
927 child = nextChild;
928 }
929 }
930 };
931
932
933 /**
934 * Transforms a token into a string ready to be put into the regular expression
935 * in hiliteMatchingText_.
936 * @param {string|Array<string>} tokenOrArray The token or array to get the
937 * regex string from.
938 * @return {string} The regex-ready token.
939 * @private
940 */
941 goog.ui.ac.Renderer.prototype.getTokenRegExp_ = function(tokenOrArray) {
942 var token = '';
943
944 if (!tokenOrArray) {
945 return token;
946 }
947
948 if (goog.isArray(tokenOrArray)) {
949 // Remove invalid tokens from the array, which may leave us with nothing.
950 tokenOrArray = goog.array.filter(tokenOrArray, function(str) {
951 return !goog.string.isEmptyOrWhitespace(goog.string.makeSafe(str));
952 });
953 }
954
955 // If highlighting all tokens, join them with '|' so the regular expression
956 // will match on any of them.
957 if (this.highlightAllTokens_) {
958 if (goog.isArray(tokenOrArray)) {
959 var tokenArray = goog.array.map(tokenOrArray, goog.string.regExpEscape);
960 token = tokenArray.join('|');
961 } else {
962 // Remove excess whitespace from the string so bars will separate valid
963 // tokens in the regular expression.
964 token = goog.string.collapseWhitespace(tokenOrArray);
965
966 token = goog.string.regExpEscape(token);
967 token = token.replace(/ /g, '|');
968 }
969 } else {
970 // Not highlighting all matching tokens. If tokenOrArray is a string, use
971 // that as the token. If it is an array, use the first element in the
972 // array.
973 // TODO(user): why is this this way?. We should match against all
974 // tokens in the array, but only accept the first match.
975 if (goog.isArray(tokenOrArray)) {
976 token = tokenOrArray.length > 0 ?
977 goog.string.regExpEscape(tokenOrArray[0]) :
978 '';
979 } else {
980 // For the single-match string token, we refuse to match anything if
981 // the string begins with a non-word character, as matches by definition
982 // can only occur at the start of a word. (This also handles the
983 // goog.string.isEmptyOrWhitespace(goog.string.makeSafe(tokenOrArray))
984 // case.)
985 if (!/^\W/.test(tokenOrArray)) {
986 token = goog.string.regExpEscape(tokenOrArray);
987 }
988 }
989 }
990
991 return token;
992 };
993
994
995 /**
996 * Render a row by creating a div and then calling row rendering callback or
997 * default row handler
998 *
999 * @param {Object} row Object representing row.
1000 * @param {string} token Token to highlight.
1001 * @return {!Element} An element with the rendered HTML.
1002 */
1003 goog.ui.ac.Renderer.prototype.renderRowHtml = function(row, token) {
1004 // Create and return the element.
1005 var elem = this.dom_.createDom(goog.dom.TagName.DIV, {
1006 className: this.rowClassName,
1007 id: goog.ui.IdGenerator.getInstance().getNextUniqueId()
1008 });
1009 goog.a11y.aria.setRole(elem, goog.a11y.aria.Role.OPTION);
1010 if (this.customRenderer_ && this.customRenderer_.renderRow) {
1011 this.customRenderer_.renderRow(row, token, elem);
1012 } else {
1013 this.renderRowContents_(row, token, elem);
1014 }
1015
1016 if (token && this.useStandardHighlighting_) {
1017 this.startHiliteMatchingText_(elem, token);
1018 }
1019
1020 goog.dom.classlist.add(elem, this.rowClassName);
1021 this.rowDivs_.push(elem);
1022 return elem;
1023 };
1024
1025
1026 /**
1027 * Given an event target looks up through the parents till it finds a div. Once
1028 * found it will then look to see if that is one of the childnodes, if it is
1029 * then the index is returned, otherwise -1 is returned.
1030 * @param {Element} et HtmlElement.
1031 * @return {number} Index corresponding to event target.
1032 * @private
1033 */
1034 goog.ui.ac.Renderer.prototype.getRowFromEventTarget_ = function(et) {
1035 while (et && et != this.element_ &&
1036 !goog.dom.classlist.contains(et, this.rowClassName)) {
1037 et = /** @type {Element} */ (et.parentNode);
1038 }
1039 return et ? goog.array.indexOf(this.rowDivs_, et) : -1;
1040 };
1041
1042
1043 /**
1044 * Handle the click events. These are redirected to the AutoComplete object
1045 * which then makes a callback to select the correct row.
1046 * @param {goog.events.Event} e Browser event object.
1047 * @private
1048 */
1049 goog.ui.ac.Renderer.prototype.handleClick_ = function(e) {
1050 var index = this.getRowFromEventTarget_(/** @type {Element} */ (e.target));
1051 if (index >= 0) {
1052 this.dispatchEvent(/** @lends {goog.events.Event.prototype} */ ({
1053 type: goog.ui.ac.AutoComplete.EventType.SELECT,
1054 row: this.rows_[index].id
1055 }));
1056 }
1057 e.stopPropagation();
1058 };
1059
1060
1061 /**
1062 * Handle the mousedown event and prevent the AC from losing focus.
1063 * @param {goog.events.Event} e Browser event object.
1064 * @private
1065 */
1066 goog.ui.ac.Renderer.prototype.handleMouseDown_ = function(e) {
1067 e.stopPropagation();
1068 e.preventDefault();
1069 };
1070
1071
1072 /**
1073 * Handle the mousing events. These are redirected to the AutoComplete object
1074 * which then makes a callback to set the correctly highlighted row. This is
1075 * because the AutoComplete can move the focus as well, and there is no sense
1076 * duplicating the code
1077 * @param {goog.events.Event} e Browser event object.
1078 * @private
1079 */
1080 goog.ui.ac.Renderer.prototype.handleMouseOver_ = function(e) {
1081 var index = this.getRowFromEventTarget_(/** @type {Element} */ (e.target));
1082 if (index >= 0) {
1083 if ((goog.now() - this.startRenderingRows_) <
1084 goog.ui.ac.Renderer.DELAY_BEFORE_MOUSEOVER) {
1085 return;
1086 }
1087
1088 this.dispatchEvent({
1089 type: goog.ui.ac.AutoComplete.EventType.HILITE,
1090 row: this.rows_[index].id
1091 });
1092 }
1093 };
1094
1095
1096
1097 /**
1098 * Class allowing different implementations to custom render the autocomplete.
1099 * Extending classes should override the render function.
1100 * @constructor
1101 */
1102 goog.ui.ac.Renderer.CustomRenderer = function() {};
1103
1104
1105 /**
1106 * Renders the autocomplete box. May be set to null.
1107 *
1108 * Because of the type, this function cannot be documented with param JSDoc.
1109 *
1110 * The function expects the following parameters:
1111 *
1112 * renderer, goog.ui.ac.Renderer: The autocomplete renderer.
1113 * element, Element: The main element that controls the rendered autocomplete.
1114 * rows, Array: The current set of rows being displayed.
1115 * token, string: The current token that has been entered. *
1116 *
1117 * @type {function(goog.ui.ac.Renderer, Element, Array, string)|
1118 * null|undefined}
1119 */
1120 goog.ui.ac.Renderer.CustomRenderer.prototype.render = function(
1121 renderer, element, rows, token) {};
1122
1123
1124 /**
1125 * Generic function that takes a row and renders a DOM structure for that row.
1126 * @param {Object} row Object representing row.
1127 * @param {string} token Token to highlight.
1128 * @param {Node} node The node to render into.
1129 */
1130 goog.ui.ac.Renderer.CustomRenderer.prototype.renderRow = function(
1131 row, token, node) {};