Debian Codegraph @

closure-library/closure/goog/ui/combobox.js

raw
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 /**
16 * @fileoverview A combo box control that allows user input with
17 * auto-suggestion from a limited set of options.
18 *
19 * @see ../demos/combobox.html
20 */
21
22 goog.provide('goog.ui.ComboBox');
23 goog.provide('goog.ui.ComboBoxItem');
24
25 goog.require('goog.Timer');
26 goog.require('goog.asserts');
27 goog.require('goog.dom');
28 goog.require('goog.dom.InputType');
29 goog.require('goog.dom.TagName');
30 goog.require('goog.dom.classlist');
31 goog.require('goog.events.EventType');
32 goog.require('goog.events.InputHandler');
33 goog.require('goog.events.KeyCodes');
34 goog.require('goog.events.KeyHandler');
35 goog.require('goog.log');
36 goog.require('goog.positioning.Corner');
37 goog.require('goog.positioning.MenuAnchoredPosition');
38 goog.require('goog.string');
39 goog.require('goog.style');
40 goog.require('goog.ui.Component');
41 goog.require('goog.ui.ItemEvent');
42 goog.require('goog.ui.LabelInput');
43 goog.require('goog.ui.Menu');
44 goog.require('goog.ui.MenuItem');
45 goog.require('goog.ui.MenuSeparator');
46 goog.require('goog.ui.registry');
47 goog.require('goog.userAgent');
48
49
50
51 /**
52 * A ComboBox control.
53 * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
54 * @param {goog.ui.Menu=} opt_menu Optional menu component.
55 * This menu is disposed of by this control.
56 * @param {goog.ui.LabelInput=} opt_labelInput Optional label input.
57 * This label input is disposed of by this control.
58 * @extends {goog.ui.Component}
59 * @constructor
60 */
61 goog.ui.ComboBox = function(opt_domHelper, opt_menu, opt_labelInput) {
62 goog.ui.Component.call(this, opt_domHelper);
63
64 this.labelInput_ = opt_labelInput || new goog.ui.LabelInput();
65 this.enabled_ = true;
66
67 // TODO(user): Allow lazy creation of menus/menu items
68 this.menu_ = opt_menu || new goog.ui.Menu(this.getDomHelper());
69 this.setupMenu_();
70 };
71 goog.inherits(goog.ui.ComboBox, goog.ui.Component);
72 goog.tagUnsealableClass(goog.ui.ComboBox);
73
74
75 /**
76 * Number of milliseconds to wait before dismissing combobox after blur.
77 * @type {number}
78 */
79 goog.ui.ComboBox.BLUR_DISMISS_TIMER_MS = 250;
80
81
82 /**
83 * A logger to help debugging of combo box behavior.
84 * @type {goog.log.Logger}
85 * @private
86 */
87 goog.ui.ComboBox.prototype.logger_ = goog.log.getLogger('goog.ui.ComboBox');
88
89
90 /**
91 * Whether the combo box is enabled.
92 * @type {boolean}
93 * @private
94 */
95 goog.ui.ComboBox.prototype.enabled_;
96
97
98 /**
99 * Keyboard event handler to manage key events dispatched by the input element.
100 * @type {goog.events.KeyHandler}
101 * @private
102 */
103 goog.ui.ComboBox.prototype.keyHandler_;
104
105
106 /**
107 * Input handler to take care of firing events when the user inputs text in
108 * the input.
109 * @type {goog.events.InputHandler?}
110 * @private
111 */
112 goog.ui.ComboBox.prototype.inputHandler_ = null;
113
114
115 /**
116 * The last input token.
117 * @type {?string}
118 * @private
119 */
120 goog.ui.ComboBox.prototype.lastToken_ = null;
121
122
123 /**
124 * A LabelInput control that manages the focus/blur state of the input box.
125 * @type {goog.ui.LabelInput?}
126 * @private
127 */
128 goog.ui.ComboBox.prototype.labelInput_ = null;
129
130
131 /**
132 * Drop down menu for the combo box. Will be created at construction time.
133 * @type {goog.ui.Menu?}
134 * @private
135 */
136 goog.ui.ComboBox.prototype.menu_ = null;
137
138
139 /**
140 * The cached visible count.
141 * @type {number}
142 * @private
143 */
144 goog.ui.ComboBox.prototype.visibleCount_ = -1;
145
146
147 /**
148 * The input element.
149 * @type {Element}
150 * @private
151 */
152 goog.ui.ComboBox.prototype.input_ = null;
153
154
155 /**
156 * The match function. The first argument for the match function will be
157 * a MenuItem's caption and the second will be the token to evaluate.
158 * @type {Function}
159 * @private
160 */
161 goog.ui.ComboBox.prototype.matchFunction_ = goog.string.startsWith;
162
163
164 /**
165 * Element used as the combo boxes button.
166 * @type {Element}
167 * @private
168 */
169 goog.ui.ComboBox.prototype.button_ = null;
170
171
172 /**
173 * Default text content for the input box when it is unchanged and unfocussed.
174 * @type {string}
175 * @private
176 */
177 goog.ui.ComboBox.prototype.defaultText_ = '';
178
179
180 /**
181 * Name for the input box created
182 * @type {string}
183 * @private
184 */
185 goog.ui.ComboBox.prototype.fieldName_ = '';
186
187
188 /**
189 * Timer identifier for delaying the dismissal of the combo menu.
190 * @type {?number}
191 * @private
192 */
193 goog.ui.ComboBox.prototype.dismissTimer_ = null;
194
195
196 /**
197 * True if the unicode inverted triangle should be displayed in the dropdown
198 * button. Defaults to false.
199 * @type {boolean} useDropdownArrow
200 * @private
201 */
202 goog.ui.ComboBox.prototype.useDropdownArrow_ = false;
203
204
205 /**
206 * Create the DOM objects needed for the combo box. A span and text input.
207 * @override
208 */
209 goog.ui.ComboBox.prototype.createDom = function() {
210 this.input_ = this.getDomHelper().createDom(goog.dom.TagName.INPUT, {
211 name: this.fieldName_,
212 type: goog.dom.InputType.TEXT,
213 autocomplete: 'off'
214 });
215 this.button_ = this.getDomHelper().createDom(
216 goog.dom.TagName.SPAN, goog.getCssName('goog-combobox-button'));
217 this.setElementInternal(
218 this.getDomHelper().createDom(
219 goog.dom.TagName.SPAN, goog.getCssName('goog-combobox'), this.input_,
220 this.button_));
221 if (this.useDropdownArrow_) {
222 goog.dom.setTextContent(this.button_, '\u25BC');
223 goog.style.setUnselectable(this.button_, true /* unselectable */);
224 }
225 this.input_.setAttribute('label', this.defaultText_);
226 this.labelInput_.decorate(this.input_);
227 this.menu_.setFocusable(false);
228 if (!this.menu_.isInDocument()) {
229 this.addChild(this.menu_, true);
230 }
231 };
232
233
234 /**
235 * Enables/Disables the combo box.
236 * @param {boolean} enabled Whether to enable (true) or disable (false) the
237 * combo box.
238 */
239 goog.ui.ComboBox.prototype.setEnabled = function(enabled) {
240 this.enabled_ = enabled;
241 this.labelInput_.setEnabled(enabled);
242 goog.dom.classlist.enable(
243 goog.asserts.assert(this.getElement()),
244 goog.getCssName('goog-combobox-disabled'), !enabled);
245 };
246
247
248 /**
249 * @return {boolean} Whether the menu item is enabled.
250 */
251 goog.ui.ComboBox.prototype.isEnabled = function() {
252 return this.enabled_;
253 };
254
255
256 /** @override */
257 goog.ui.ComboBox.prototype.enterDocument = function() {
258 goog.ui.ComboBox.superClass_.enterDocument.call(this);
259
260 var handler = this.getHandler();
261 handler.listen(
262 this.getElement(), goog.events.EventType.MOUSEDOWN,
263 this.onComboMouseDown_);
264 handler.listen(
265 this.getDomHelper().getDocument(), goog.events.EventType.MOUSEDOWN,
266 this.onDocClicked_);
267
268 handler.listen(this.input_, goog.events.EventType.BLUR, this.onInputBlur_);
269
270 this.keyHandler_ = new goog.events.KeyHandler(this.input_);
271 handler.listen(
272 this.keyHandler_, goog.events.KeyHandler.EventType.KEY,
273 this.handleKeyEvent);
274
275 this.inputHandler_ = new goog.events.InputHandler(this.input_);
276 handler.listen(
277 this.inputHandler_, goog.events.InputHandler.EventType.INPUT,
278 this.onInputEvent_);
279
280 handler.listen(
281 this.menu_, goog.ui.Component.EventType.ACTION, this.onMenuSelected_);
282 };
283
284
285 /** @override */
286 goog.ui.ComboBox.prototype.exitDocument = function() {
287 this.keyHandler_.dispose();
288 delete this.keyHandler_;
289 this.inputHandler_.dispose();
290 this.inputHandler_ = null;
291 goog.ui.ComboBox.superClass_.exitDocument.call(this);
292 };
293
294
295 /**
296 * Combo box currently can't decorate elements.
297 * @return {boolean} The value false.
298 * @override
299 */
300 goog.ui.ComboBox.prototype.canDecorate = function() {
301 return false;
302 };
303
304
305 /** @override */
306 goog.ui.ComboBox.prototype.disposeInternal = function() {
307 goog.ui.ComboBox.superClass_.disposeInternal.call(this);
308
309 this.clearDismissTimer_();
310
311 this.labelInput_.dispose();
312 this.menu_.dispose();
313
314 this.labelInput_ = null;
315 this.menu_ = null;
316 this.input_ = null;
317 this.button_ = null;
318 };
319
320
321 /**
322 * Dismisses the menu and resets the value of the edit field.
323 */
324 goog.ui.ComboBox.prototype.dismiss = function() {
325 this.clearDismissTimer_();
326 this.hideMenu_();
327 this.menu_.setHighlightedIndex(-1);
328 };
329
330
331 /**
332 * Adds a new menu item at the end of the menu.
333 * @param {goog.ui.MenuItem} item Menu item to add to the menu.
334 */
335 goog.ui.ComboBox.prototype.addItem = function(item) {
336 this.menu_.addChild(item, true);
337 this.visibleCount_ = -1;
338 };
339
340
341 /**
342 * Adds a new menu item at a specific index in the menu.
343 * @param {goog.ui.MenuItem} item Menu item to add to the menu.
344 * @param {number} n Index at which to insert the menu item.
345 */
346 goog.ui.ComboBox.prototype.addItemAt = function(item, n) {
347 this.menu_.addChildAt(item, n, true);
348 this.visibleCount_ = -1;
349 };
350
351
352 /**
353 * Removes an item from the menu and disposes it.
354 * @param {goog.ui.MenuItem} item The menu item to remove.
355 */
356 goog.ui.ComboBox.prototype.removeItem = function(item) {
357 var child = this.menu_.removeChild(item, true);
358 if (child) {
359 child.dispose();
360 this.visibleCount_ = -1;
361 }
362 };
363
364
365 /**
366 * Remove all of the items from the ComboBox menu
367 */
368 goog.ui.ComboBox.prototype.removeAllItems = function() {
369 for (var i = this.getItemCount() - 1; i >= 0; --i) {
370 this.removeItem(this.getItemAt(i));
371 }
372 };
373
374
375 /**
376 * Removes a menu item at a given index in the menu.
377 * @param {number} n Index of item.
378 */
379 goog.ui.ComboBox.prototype.removeItemAt = function(n) {
380 var child = this.menu_.removeChildAt(n, true);
381 if (child) {
382 child.dispose();
383 this.visibleCount_ = -1;
384 }
385 };
386
387
388 /**
389 * Returns a reference to the menu item at a given index.
390 * @param {number} n Index of menu item.
391 * @return {goog.ui.MenuItem?} Reference to the menu item.
392 */
393 goog.ui.ComboBox.prototype.getItemAt = function(n) {
394 return /** @type {goog.ui.MenuItem?} */ (this.menu_.getChildAt(n));
395 };
396
397
398 /**
399 * Returns the number of items in the list, including non-visible items,
400 * such as separators.
401 * @return {number} Number of items in the menu for this combobox.
402 */
403 goog.ui.ComboBox.prototype.getItemCount = function() {
404 return this.menu_.getChildCount();
405 };
406
407
408 /**
409 * @return {goog.ui.Menu} The menu that pops up.
410 */
411 goog.ui.ComboBox.prototype.getMenu = function() {
412 return this.menu_;
413 };
414
415
416 /**
417 * @return {Element} The input element.
418 */
419 goog.ui.ComboBox.prototype.getInputElement = function() {
420 return this.input_;
421 };
422
423
424 /**
425 * @return {goog.ui.LabelInput} A LabelInput control that manages the
426 * focus/blur state of the input box.
427 */
428 goog.ui.ComboBox.prototype.getLabelInput = function() {
429 return this.labelInput_;
430 };
431
432
433 /**
434 * @return {number} The number of visible items in the menu.
435 * @private
436 */
437 goog.ui.ComboBox.prototype.getNumberOfVisibleItems_ = function() {
438 if (this.visibleCount_ == -1) {
439 var count = 0;
440 for (var i = 0, n = this.menu_.getChildCount(); i < n; i++) {
441 var item = this.menu_.getChildAt(i);
442 if (!(item instanceof goog.ui.MenuSeparator) && item.isVisible()) {
443 count++;
444 }
445 }
446 this.visibleCount_ = count;
447 }
448
449 return this.visibleCount_;
450 };
451
452
453 /**
454 * Sets the match function to be used when filtering the combo box menu.
455 * @param {Function} matchFunction The match function to be used when filtering
456 * the combo box menu.
457 */
458 goog.ui.ComboBox.prototype.setMatchFunction = function(matchFunction) {
459 this.matchFunction_ = matchFunction;
460 };
461
462
463 /**
464 * @return {Function} The match function for the combox box.
465 */
466 goog.ui.ComboBox.prototype.getMatchFunction = function() {
467 return this.matchFunction_;
468 };
469
470
471 /**
472 * Sets the default text for the combo box.
473 * @param {string} text The default text for the combo box.
474 */
475 goog.ui.ComboBox.prototype.setDefaultText = function(text) {
476 this.defaultText_ = text;
477 if (this.labelInput_) {
478 this.labelInput_.setLabel(this.defaultText_);
479 }
480 };
481
482
483 /**
484 * @return {string} text The default text for the combox box.
485 */
486 goog.ui.ComboBox.prototype.getDefaultText = function() {
487 return this.defaultText_;
488 };
489
490
491 /**
492 * Sets the field name for the combo box.
493 * @param {string} fieldName The field name for the combo box.
494 */
495 goog.ui.ComboBox.prototype.setFieldName = function(fieldName) {
496 this.fieldName_ = fieldName;
497 };
498
499
500 /**
501 * @return {string} The field name for the combo box.
502 */
503 goog.ui.ComboBox.prototype.getFieldName = function() {
504 return this.fieldName_;
505 };
506
507
508 /**
509 * Set to true if a unicode inverted triangle should be displayed in the
510 * dropdown button.
511 * This option defaults to false for backwards compatibility.
512 * @param {boolean} useDropdownArrow True to use the dropdown arrow.
513 */
514 goog.ui.ComboBox.prototype.setUseDropdownArrow = function(useDropdownArrow) {
515 this.useDropdownArrow_ = !!useDropdownArrow;
516 };
517
518
519 /**
520 * Sets the current value of the combo box.
521 * @param {string} value The new value.
522 */
523 goog.ui.ComboBox.prototype.setValue = function(value) {
524 if (this.labelInput_.getValue() != value) {
525 this.labelInput_.setValue(value);
526 this.handleInputChange_();
527 }
528 };
529
530
531 /**
532 * @return {string} The current value of the combo box.
533 */
534 goog.ui.ComboBox.prototype.getValue = function() {
535 return this.labelInput_.getValue();
536 };
537
538
539 /**
540 * @return {string} HTML escaped token.
541 */
542 goog.ui.ComboBox.prototype.getToken = function() {
543 // TODO(user): Remove HTML escaping and fix the existing calls.
544 return goog.string.htmlEscape(this.getTokenText_());
545 };
546
547
548 /**
549 * @return {string} The token for the current cursor position in the
550 * input box, when multi-input is disabled it will be the full input value.
551 * @private
552 */
553 goog.ui.ComboBox.prototype.getTokenText_ = function() {
554 // TODO(user): Implement multi-input such that getToken returns a substring
555 // of the whole input delimited by commas.
556 return goog.string.trim(this.labelInput_.getValue().toLowerCase());
557 };
558
559
560 /**
561 * @private
562 */
563 goog.ui.ComboBox.prototype.setupMenu_ = function() {
564 var sm = this.menu_;
565 sm.setVisible(false);
566 sm.setAllowAutoFocus(false);
567 sm.setAllowHighlightDisabled(true);
568 };
569
570
571 /**
572 * Shows the menu if it isn't already showing. Also positions the menu
573 * correctly, resets the menu item visibilities and highlights the relevant
574 * item.
575 * @param {boolean} showAll Whether to show all items, with the first matching
576 * item highlighted.
577 * @private
578 */
579 goog.ui.ComboBox.prototype.maybeShowMenu_ = function(showAll) {
580 var isVisible = this.menu_.isVisible();
581 var numVisibleItems = this.getNumberOfVisibleItems_();
582
583 if (isVisible && numVisibleItems == 0) {
584 goog.log.fine(this.logger_, 'no matching items, hiding');
585 this.hideMenu_();
586
587 } else if (!isVisible && numVisibleItems > 0) {
588 if (showAll) {
589 goog.log.fine(this.logger_, 'showing menu');
590 this.setItemVisibilityFromToken_('');
591 this.setItemHighlightFromToken_(this.getTokenText_());
592 }
593 // In Safari 2.0, when clicking on the combox box, the blur event is
594 // received after the click event that invokes this function. Since we want
595 // to cancel the dismissal after the blur event is processed, we have to
596 // wait for all event processing to happen.
597 goog.Timer.callOnce(this.clearDismissTimer_, 1, this);
598
599 this.showMenu_();
600 }
601
602 this.positionMenu();
603 };
604
605
606 /**
607 * Positions the menu.
608 * @protected
609 */
610 goog.ui.ComboBox.prototype.positionMenu = function() {
611 if (this.menu_ && this.menu_.isVisible()) {
612 var position = new goog.positioning.MenuAnchoredPosition(
613 this.getElement(), goog.positioning.Corner.BOTTOM_START, true);
614 position.reposition(
615 this.menu_.getElement(), goog.positioning.Corner.TOP_START);
616 }
617 };
618
619
620 /**
621 * Show the menu and add an active class to the combo box's element.
622 * @private
623 */
624 goog.ui.ComboBox.prototype.showMenu_ = function() {
625 this.menu_.setVisible(true);
626 goog.dom.classlist.add(
627 goog.asserts.assert(this.getElement()),
628 goog.getCssName('goog-combobox-active'));
629 };
630
631
632 /**
633 * Hide the menu and remove the active class from the combo box's element.
634 * @private
635 */
636 goog.ui.ComboBox.prototype.hideMenu_ = function() {
637 this.menu_.setVisible(false);
638 goog.dom.classlist.remove(
639 goog.asserts.assert(this.getElement()),
640 goog.getCssName('goog-combobox-active'));
641 };
642
643
644 /**
645 * Clears the dismiss timer if it's active.
646 * @private
647 */
648 goog.ui.ComboBox.prototype.clearDismissTimer_ = function() {
649 if (this.dismissTimer_) {
650 goog.Timer.clear(this.dismissTimer_);
651 this.dismissTimer_ = null;
652 }
653 };
654
655
656 /**
657 * Event handler for when the combo box area has been clicked.
658 * @param {goog.events.BrowserEvent} e The browser event.
659 * @private
660 */
661 goog.ui.ComboBox.prototype.onComboMouseDown_ = function(e) {
662 // We only want this event on the element itself or the input or the button.
663 if (this.enabled_ &&
664 (e.target == this.getElement() || e.target == this.input_ ||
665 goog.dom.contains(this.button_, /** @type {Node} */ (e.target)))) {
666 if (this.menu_.isVisible()) {
667 goog.log.fine(this.logger_, 'Menu is visible, dismissing');
668 this.dismiss();
669 } else {
670 goog.log.fine(this.logger_, 'Opening dropdown');
671 this.maybeShowMenu_(true);
672 if (goog.userAgent.OPERA) {
673 // select() doesn't focus <input> elements in Opera.
674 this.input_.focus();
675 }
676 this.input_.select();
677 this.menu_.setMouseButtonPressed(true);
678 // Stop the click event from stealing focus
679 e.preventDefault();
680 }
681 }
682 // Stop the event from propagating outside of the combo box
683 e.stopPropagation();
684 };
685
686
687 /**
688 * Event handler for when the document is clicked.
689 * @param {goog.events.BrowserEvent} e The browser event.
690 * @private
691 */
692 goog.ui.ComboBox.prototype.onDocClicked_ = function(e) {
693 if (!goog.dom.contains(
694 this.menu_.getElement(), /** @type {Node} */ (e.target))) {
695 this.dismiss();
696 }
697 };
698
699
700 /**
701 * Handle the menu's select event.
702 * @param {goog.events.Event} e The event.
703 * @private
704 */
705 goog.ui.ComboBox.prototype.onMenuSelected_ = function(e) {
706 var item = /** @type {!goog.ui.MenuItem} */ (e.target);
707 // Stop propagation of the original event and redispatch to allow the menu
708 // select to be cancelled at this level. i.e. if a menu item should cause
709 // some behavior such as a user prompt instead of assigning the caption as
710 // the value.
711 if (this.dispatchEvent(
712 new goog.ui.ItemEvent(
713 goog.ui.Component.EventType.ACTION, this, item))) {
714 var caption = item.getCaption();
715 goog.log.fine(
716 this.logger_, 'Menu selection: ' + caption + '. Dismissing menu');
717 if (this.labelInput_.getValue() != caption) {
718 this.labelInput_.setValue(caption);
719 this.dispatchEvent(goog.ui.Component.EventType.CHANGE);
720 }
721 this.dismiss();
722 }
723 e.stopPropagation();
724 };
725
726
727 /**
728 * Event handler for when the input box looses focus -- hide the menu
729 * @param {goog.events.BrowserEvent} e The browser event.
730 * @private
731 */
732 goog.ui.ComboBox.prototype.onInputBlur_ = function(e) {
733 this.clearDismissTimer_();
734 this.dismissTimer_ = goog.Timer.callOnce(
735 this.dismiss, goog.ui.ComboBox.BLUR_DISMISS_TIMER_MS, this);
736 };
737
738
739 /**
740 * Handles keyboard events from the input box. Returns true if the combo box
741 * was able to handle the event, false otherwise.
742 * @param {goog.events.KeyEvent} e Key event to handle.
743 * @return {boolean} Whether the event was handled by the combo box.
744 * @protected
745 * @suppress {visibility} performActionInternal
746 */
747 goog.ui.ComboBox.prototype.handleKeyEvent = function(e) {
748 var isMenuVisible = this.menu_.isVisible();
749
750 // Give the menu a chance to handle the event.
751 if (isMenuVisible && this.menu_.handleKeyEvent(e)) {
752 return true;
753 }
754
755 // The menu is either hidden or didn't handle the event.
756 var handled = false;
757 switch (e.keyCode) {
758 case goog.events.KeyCodes.ESC:
759 // If the menu is visible and the user hit Esc, dismiss the menu.
760 if (isMenuVisible) {
761 goog.log.fine(
762 this.logger_, 'Dismiss on Esc: ' + this.labelInput_.getValue());
763 this.dismiss();
764 handled = true;
765 }
766 break;
767 case goog.events.KeyCodes.TAB:
768 // If the menu is open and an option is highlighted, activate it.
769 if (isMenuVisible) {
770 var highlighted = this.menu_.getHighlighted();
771 if (highlighted) {
772 goog.log.fine(
773 this.logger_, 'Select on Tab: ' + this.labelInput_.getValue());
774 highlighted.performActionInternal(e);
775 handled = true;
776 }
777 }
778 break;
779 case goog.events.KeyCodes.UP:
780 case goog.events.KeyCodes.DOWN:
781 // If the menu is hidden and the user hit the up/down arrow, show it.
782 if (!isMenuVisible) {
783 goog.log.fine(this.logger_, 'Up/Down - maybe show menu');
784 this.maybeShowMenu_(true);
785 handled = true;
786 }
787 break;
788 }
789
790 if (handled) {
791 e.preventDefault();
792 }
793
794 return handled;
795 };
796
797
798 /**
799 * Handles the content of the input box changing.
800 * @param {goog.events.Event} e The INPUT event to handle.
801 * @private
802 */
803 goog.ui.ComboBox.prototype.onInputEvent_ = function(e) {
804 // If the key event is text-modifying, update the menu.
805 goog.log.fine(
806 this.logger_, 'Key is modifying: ' + this.labelInput_.getValue());
807 this.handleInputChange_();
808 };
809
810
811 /**
812 * Handles the content of the input box changing, either because of user
813 * interaction or programmatic changes.
814 * @private
815 */
816 goog.ui.ComboBox.prototype.handleInputChange_ = function() {
817 var token = this.getTokenText_();
818 this.setItemVisibilityFromToken_(token);
819 if (goog.dom.getActiveElement(this.getDomHelper().getDocument()) ==
820 this.input_) {
821 // Do not alter menu visibility unless the user focus is currently on the
822 // combobox (otherwise programmatic changes may cause the menu to become
823 // visible).
824 this.maybeShowMenu_(false);
825 }
826 var highlighted = this.menu_.getHighlighted();
827 if (token == '' || !highlighted || !highlighted.isVisible()) {
828 this.setItemHighlightFromToken_(token);
829 }
830 this.lastToken_ = token;
831 this.dispatchEvent(goog.ui.Component.EventType.CHANGE);
832 };
833
834
835 /**
836 * Loops through all menu items setting their visibility according to a token.
837 * @param {string} token The token.
838 * @private
839 */
840 goog.ui.ComboBox.prototype.setItemVisibilityFromToken_ = function(token) {
841 var isVisibleItem = false;
842 var count = 0;
843 var recheckHidden = !this.matchFunction_(token, this.lastToken_);
844
845 for (var i = 0, n = this.menu_.getChildCount(); i < n; i++) {
846 var item = this.menu_.getChildAt(i);
847 if (item instanceof goog.ui.MenuSeparator) {
848 // Ensure that separators are only shown if there is at least one visible
849 // item before them.
850 item.setVisible(isVisibleItem);
851 isVisibleItem = false;
852 } else if (item instanceof goog.ui.MenuItem) {
853 if (!item.isVisible() && !recheckHidden) continue;
854
855 var caption = item.getCaption();
856 var visible = this.isItemSticky_(item) ||
857 caption && this.matchFunction_(caption.toLowerCase(), token);
858 if (typeof item.setFormatFromToken == 'function') {
859 item.setFormatFromToken(token);
860 }
861 item.setVisible(!!visible);
862 isVisibleItem = visible || isVisibleItem;
863
864 } else {
865 // Assume all other items are correctly using their visibility.
866 isVisibleItem = item.isVisible() || isVisibleItem;
867 }
868
869 if (!(item instanceof goog.ui.MenuSeparator) && item.isVisible()) {
870 count++;
871 }
872 }
873
874 this.visibleCount_ = count;
875 };
876
877
878 /**
879 * Highlights the first token that matches the given token.
880 * @param {string} token The token.
881 * @private
882 */
883 goog.ui.ComboBox.prototype.setItemHighlightFromToken_ = function(token) {
884 if (token == '') {
885 this.menu_.setHighlightedIndex(-1);
886 return;
887 }
888
889 for (var i = 0, n = this.menu_.getChildCount(); i < n; i++) {
890 var item = this.menu_.getChildAt(i);
891 var caption = item.getCaption();
892 if (caption && this.matchFunction_(caption.toLowerCase(), token)) {
893 this.menu_.setHighlightedIndex(i);
894 if (item.setFormatFromToken) {
895 item.setFormatFromToken(token);
896 }
897 return;
898 }
899 }
900 this.menu_.setHighlightedIndex(-1);
901 };
902
903
904 /**
905 * Returns true if the item has an isSticky method and the method returns true.
906 * @param {goog.ui.MenuItem} item The item.
907 * @return {boolean} Whether the item has an isSticky method and the method
908 * returns true.
909 * @private
910 */
911 goog.ui.ComboBox.prototype.isItemSticky_ = function(item) {
912 return typeof item.isSticky == 'function' && item.isSticky();
913 };
914
915
916
917 /**
918 * Class for combo box items.
919 * @param {goog.ui.ControlContent} content Text caption or DOM structure to
920 * display as the content of the item (use to add icons or styling to
921 * menus).
922 * @param {*=} opt_data Identifying data for the menu item.
923 * @param {goog.dom.DomHelper=} opt_domHelper Optional dom helper used for dom
924 * interactions.
925 * @param {goog.ui.MenuItemRenderer=} opt_renderer Optional renderer.
926 * @constructor
927 * @extends {goog.ui.MenuItem}
928 */
929 goog.ui.ComboBoxItem = function(
930 content, opt_data, opt_domHelper, opt_renderer) {
931 goog.ui.ComboBoxItem.base(
932 this, 'constructor', content, opt_data, opt_domHelper, opt_renderer);
933 };
934 goog.inherits(goog.ui.ComboBoxItem, goog.ui.MenuItem);
935 goog.tagUnsealableClass(goog.ui.ComboBoxItem);
936
937
938 // Register a decorator factory function for goog.ui.ComboBoxItems.
939 goog.ui.registry.setDecoratorByClassName(
940 goog.getCssName('goog-combobox-item'), function() {
941 // ComboBoxItem defaults to using MenuItemRenderer.
942 return new goog.ui.ComboBoxItem(null);
943 });
944
945
946 /**
947 * Whether the menu item is sticky, non-sticky items will be hidden as the
948 * user types.
949 * @type {boolean}
950 * @private
951 */
952 goog.ui.ComboBoxItem.prototype.isSticky_ = false;
953
954
955 /**
956 * Sets the menu item to be sticky or not sticky.
957 * @param {boolean} sticky Whether the menu item should be sticky.
958 */
959 goog.ui.ComboBoxItem.prototype.setSticky = function(sticky) {
960 this.isSticky_ = sticky;
961 };
962
963
964 /**
965 * @return {boolean} Whether the menu item is sticky.
966 */
967 goog.ui.ComboBoxItem.prototype.isSticky = function() {
968 return this.isSticky_;
969 };
970
971
972 /**
973 * Sets the format for a menu item based on a token, bolding the token.
974 * @param {string} token The token.
975 */
976 goog.ui.ComboBoxItem.prototype.setFormatFromToken = function(token) {
977 if (this.isEnabled()) {
978 var caption = this.getCaption();
979 var index = caption.toLowerCase().indexOf(token);
980 if (index >= 0) {
981 var domHelper = this.getDomHelper();
982 this.setContent([
983 domHelper.createTextNode(caption.substr(0, index)),
984 domHelper.createDom(
985 goog.dom.TagName.B, null, caption.substr(index, token.length)),
986 domHelper.createTextNode(caption.substr(index + token.length))
987 ]);
988 }
989 }
990 };