Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(252)

Side by Side Diff: chrome/browser/resources/local_omnibox_popup/local_omnibox_popup.js

Issue 13375003: Fixing iframe jank in the local omnibox popup. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Adding unit tests. Created 7 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright 2012 The Chromium Authors. All rights reserved. 1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 /** 5 /**
6 * @fileoverview Support for omnibox behavior in offline mode or when API 6 * @fileoverview Support for omnibox behavior in offline mode or when API
7 * features are not supported on the server. 7 * features are not supported on the server.
8 */ 8 */
9 9
10 // ========================================================== 10 (function() {
11 // Enums.
12 // ==========================================================
13
14 /** 11 /**
15 * Possible behaviors for navigateContentWindow. 12 * Possible behaviors for navigateContentWindow.
16 * @enum {number} 13 * @enum {number}
17 */ 14 */
18 var WindowOpenDisposition = { 15 var WindowOpenDisposition = {
19 CURRENT_TAB: 1, 16 CURRENT_TAB: 1,
20 NEW_BACKGROUND_TAB: 2 17 NEW_BACKGROUND_TAB: 2
21 }; 18 };
22 19
23 /** 20 /**
24 * The JavaScript button event value for a middle click. 21 * The JavaScript button event value for a middle click.
25 * @type {number} 22 * @type {number}
26 * @const 23 * @const
27 */ 24 */
28 var MIDDLE_MOUSE_BUTTON = 1; 25 var MIDDLE_MOUSE_BUTTON = 1;
29 26
30 // =============================================================================
31 // Util functions
32 // =============================================================================
33
34 /** 27 /**
35 * The maximum number of suggestions to show. 28 * The maximum number of suggestions to show.
36 * @type {number} 29 * @type {number}
37 * @const 30 * @const
38 */ 31 */
39 var MAX_SUGGESTIONS_TO_SHOW = 5; 32 var MAX_SUGGESTIONS_TO_SHOW = 5;
40 33
41 /** 34 /**
42 * Assume any native suggestion with a score higher than this value has been 35 * Assume any native suggestion with a score higher than this value has been
43 * inlined by the browser. 36 * inlined by the browser.
44 * @type {number} 37 * @type {number}
45 * @const 38 * @const
46 */ 39 */
47 var INLINE_SUGGESTION_THRESHOLD = 1200; 40 var INLINE_SUGGESTION_THRESHOLD = 1200;
48 41
49 /** 42 /**
43 * The color code for a query.
44 * @type {number}
45 * @const
46 */
47 var QUERY_COLOR = 0x000000;
48
49 /**
50 * The color code for a display URL.
51 * @type {number}
52 * @const
53 */
54 var URL_COLOR = 0x009933;
55
56 /**
57 * The color code for a suggestion title.
58 * @type {number}
59 * @const
60 */
61 var TITLE_COLOR = 0x666666;
62
63 /**
64 * A top position which is off-screen.
65 * @type {string}
66 * @const
67 */
68 var OFF_SCREEN = '-1000px';
69
70 /**
71 * The expected origin of a suggestion iframe.
72 * @type {string}
73 * @const
74 */
75 var SUGGESTION_ORIGIN = 'chrome-search://suggestion';
76
77 /**
50 * Suggestion provider type corresponding to a verbatim URL suggestion. 78 * Suggestion provider type corresponding to a verbatim URL suggestion.
51 * @type {string} 79 * @type {string}
52 * @const 80 * @const
53 */ 81 */
54 var VERBATIM_URL_TYPE = 'url-what-you-typed'; 82 var VERBATIM_URL_TYPE = 'url-what-you-typed';
55 83
56 /** 84 /**
57 * Suggestion provider type corresponding to a verbatim search suggestion. 85 * Suggestion provider type corresponding to a verbatim search suggestion.
58 * @type {string} 86 * @type {string}
59 * @const 87 * @const
60 */ 88 */
61 var VERBATIM_SEARCH_TYPE = 'search-what-you-typed'; 89 var VERBATIM_SEARCH_TYPE = 'search-what-you-typed';
62 90
63 /** 91 /**
64 * The omnibox input value during the last onnativesuggestions event. 92 * "Up" arrow keycode.
65 * @type {string} 93 * @type {number}
94 * @const
66 */ 95 */
67 var lastInputValue = ''; 96 var KEY_UP_ARROW = 38;
68 97
69 /** 98 /**
70 * The ordered restricted ids of the currently displayed suggestions. Since the 99 * "Down" arrow keycode.
71 * suggestions contain the user's personal data (browser history) the searchBox 100 * @type {number}
72 * API embeds the content of the suggestion in a shadow dom, and assigns a 101 * @const
73 * random restricted id to each suggestion which is accessible to the JS.
74 * @type {Array.<number>}
75 */ 102 */
76 103 var KEY_DOWN_ARROW = 40;
77 var restrictedIds = [];
78 104
79 /** 105 /**
80 * The index of the currently selected suggestion or -1 if none are selected. 106 * Pixels of padding inside a suggestion div for displaying its icon.
107 * @type {number}
108 * @const
109 */
110 var SUGGESTION_ICON_PADDING = 26;
111
112 /**
113 * Pixels by which iframes should be moved down relative to their wrapping
114 * suggestion div.
115 */
116 var SUGGESTION_TOP_OFFSET = 4;
117
118 /**
119 * The displayed suggestions.
120 * @type {SuggestionsBox}
121 */
122 var activeBox;
123
124 /**
125 * The suggestions being rendered.
126 * @type {SuggestionsBox}
127 */
128 var pendingBox;
129
130 /**
131 * A pool of iframes to display suggestions.
132 * @type {IframePool}
133 */
134 var iframePool;
135
136 /**
137 * A serial number for the next suggestions rendered.
81 * @type {number} 138 * @type {number}
82 */ 139 */
83 var selectedIndex = -1; 140 var nextRequestId = 0;
84 141
85 /** 142 /**
86 * Shortcut for document.getElementById. 143 * Shortcut for document.querySelector.
87 * @param {string} id of the element. 144 * @param {string} selector A selector to query the desired element.
88 * @return {HTMLElement} with the id. 145 * @return {HTMLElement} The first element to match |selector| or null.
89 */ 146 */
90 function $(id) { 147 function $qs(selector) {
91 return document.getElementById(id); 148 return document.querySelector(selector);
92 } 149 }
93 150
94 /** 151 /**
95 * Displays a suggestion. 152 * Simple common assertion API (copied from ui/webui/resources/js/util.js).
96 * @param {Object} suggestion The suggestion to render. 153 * @param {*} condition The condition to test. Note that this may be used to
97 * @param {HTMLElement} box The html element to add the suggestion to. 154 * test whether a value is defined or not, and we don't want to force a
98 * @param {boolean} select True to select the selection. 155 * cast to Boolean.
156 * @param {string=} opt_message A message to use in any error.
99 */ 157 */
100 function addSuggestionToBox(suggestion, box, select) { 158 function assert(condition, opt_message) {
Dan Beam 2013/04/08 16:46:58 move this to a file and include it from here and u
Jered 2013/04/08 21:43:16 Done.
101 var suggestionDiv = document.createElement('div'); 159 'use strict';
102 suggestionDiv.classList.add('suggestion'); 160 if (!condition) {
103 suggestionDiv.classList.toggle('selected', select); 161 var msg = 'Assertion failed';
104 suggestionDiv.classList.toggle('search', suggestion.is_search); 162 if (opt_message)
105 163 msg = msg + ': ' + opt_message;
106 if (suggestion.destination_url) { // iframes. 164 throw new Error(msg);
107 var suggestionIframe = document.createElement('iframe');
108 suggestionIframe.className = 'contents';
109 suggestionIframe.src = suggestion.destination_url;
110 suggestionIframe.id = suggestion.rid;
111 suggestionDiv.appendChild(suggestionIframe);
112 } else {
113 var contentsContainer = document.createElement('div');
114 var contents = suggestion.combinedNode;
115 contents.classList.add('contents');
116 contentsContainer.appendChild(contents);
117 suggestionDiv.appendChild(contentsContainer);
118 suggestionDiv.onclick = function(event) {
119 handleSuggestionClick(suggestion.rid, event.button);
120 };
121 }
122
123 restrictedIds.push(suggestion.rid);
124 box.appendChild(suggestionDiv);
125 }
126
127 /**
128 * Renders the input suggestions.
129 * @param {Array} nativeSuggestions An array of native suggestions to render.
130 */
131 function renderSuggestions(nativeSuggestions) {
132 var box = document.createElement('div');
133 box.id = 'suggestionsBox';
134 $('suggestions-box-container').appendChild(box);
135
136 for (var i = 0, length = nativeSuggestions.length;
137 i < Math.min(MAX_SUGGESTIONS_TO_SHOW, length); ++i) {
138 addSuggestionToBox(nativeSuggestions[i], box, i == selectedIndex);
139 } 165 }
140 } 166 }
141 167
142 /** 168 /**
143 * Clears the suggestions being displayed.
144 */
145 function clearSuggestions() {
146 $('suggestions-box-container').innerHTML = '';
147 restrictedIds = [];
148 selectedIndex = -1;
149 }
150
151 /**
152 * @return {number} The height of the dropdown.
153 */
154 function getDropdownHeight() {
155 return $('suggestions-box-container').offsetHeight;
156 }
157
158 /**
159 * @param {Object} suggestion A suggestion. 169 * @param {Object} suggestion A suggestion.
160 * @param {boolean} inVerbatimMode Are we in verbatim mode? 170 * @param {boolean} inVerbatimMode Are we in verbatim mode?
161 * @return {boolean} True if the suggestion should be selected. 171 * @return {boolean} True if the suggestion should be selected.
162 */ 172 */
163 function shouldSelectSuggestion(suggestion, inVerbatimMode) { 173 function shouldSelectSuggestion(suggestion, inVerbatimMode) {
164 var isVerbatimUrl = suggestion.type == VERBATIM_URL_TYPE; 174 var isVerbatimUrl = suggestion.type == VERBATIM_URL_TYPE;
165 var inlinableSuggestion = suggestion.type != VERBATIM_SEARCH_TYPE && 175 var inlineableSuggestion = suggestion.type != VERBATIM_SEARCH_TYPE &&
166 suggestion.rankingData.relevance > INLINE_SUGGESTION_THRESHOLD; 176 suggestion.rankingData.relevance > INLINE_SUGGESTION_THRESHOLD;
167 // Verbatim URLs should always be selected. Otherwise, select suggestions 177 // Verbatim URLs should always be selected. Otherwise, select suggestions
168 // with a high enough score unless we are in verbatim mode (e.g. backspacing 178 // with a high enough score unless we are in verbatim mode (e.g. backspacing
169 // away). 179 // away).
170 return isVerbatimUrl || (!inVerbatimMode && inlinableSuggestion); 180 return isVerbatimUrl || (!inVerbatimMode && inlineableSuggestion);
171 } 181 }
172 182
173 /** 183 /**
174 * Updates selectedIndex, bounding it between -1 and the total number of 184 * Extract the desired navigation behavior from a click button.
175 * of suggestions - 1 (looping as necessary), and selects the corresponding 185 * @param {number} button The Event#button property of a click event.
176 * suggestion. 186 * @return {WindowOpenDisposition} The desired behavior for
177 * @param {boolean} increment True to increment the selected suggestion, false 187 * navigateContentWindow.
178 * to decrement. 188 */
179 */ 189 function getDispositionFromClickButton(button) {
180 function updateSelectedSuggestion(increment) { 190 if (button == MIDDLE_MOUSE_BUTTON)
181 var numSuggestions = restrictedIds.length; 191 return WindowOpenDisposition.NEW_BACKGROUND_TAB;
182 if (!numSuggestions) 192 return WindowOpenDisposition.CURRENT_TAB;
183 return; 193 }
184 194
185 var oldSelection = $('suggestionsBox').querySelector('.selected'); 195
186 if (oldSelection) 196 /**
187 oldSelection.classList.remove('selected'); 197 * Manages a pool of chrome-search suggestion result iframes.
188 198 * @constructor
189 if (increment) 199 */
190 selectedIndex = ++selectedIndex > numSuggestions - 1 ? -1 : selectedIndex; 200 function IframePool() {
191 else 201 }
192 selectedIndex = --selectedIndex < -1 ? numSuggestions - 1 : selectedIndex; 202
193 var apiHandle = getApiObjectHandle(); 203 IframePool.prototype = {
194 if (selectedIndex == -1) { 204 /**
195 apiHandle.setValue(lastInputValue); 205 * HTML iframe elements.
206 * @type {Array.<Element>}
207 * @private
208 */
209 iframes_: [],
210
211 /**
212 * Initializes the pool with blank result template iframes, positioned off
213 * screen.
214 */
215 init: function() {
216 for (var i = 0; i < 2 * MAX_SUGGESTIONS_TO_SHOW; ++i) {
217 var iframe = document.createElement('iframe');
218 iframe.className = 'contents';
219 iframe.id = 'suggestion-text-' + i;
220 iframe.src = 'chrome-search://suggestion/result.html';
221 iframe.style.top = OFF_SCREEN;
222 iframe.addEventListener('mouseover', function(e) {
223 if (activeBox)
224 activeBox.hover(e.currentTarget.id);
225 }, false);
226 iframe.addEventListener('mouseout', function(e) {
227 if (activeBox)
228 activeBox.unhover(e.currentTarget.id);
229 }, false);
230 document.body.appendChild(iframe);
231 this.iframes_.push(iframe);
232 }
233 },
234
235 /**
236 * Reserves a free suggestion iframe from the pool.
237 * @return {Element} An iframe suitable for holding a suggestion.
238 */
239 reserve: function() {
240 return this.iframes_.pop();
241 },
242
243 /**
244 * Releases a suggestion iframe back into the pool.
245 * @param {Element} iframe The iframe to return to the pool.
246 */
247 release: function(iframe) {
248 this.iframes_.push(iframe);
249 iframe.style.top = OFF_SCREEN;
250 },
251 };
252
253
254 /**
255 * An individual suggestion.
256 * @param {!Object} data Autocomplete fields for this suggestion.
257 * @constructor
258 */
259 function Suggestion(data) {
260 assert(data);
261 /**
262 * Autocomplete fields for this suggestion.
263 * @type {!Object}
264 * @private
265 */
266 this.data_ = data;
267 }
268
269 Suggestion.prototype = {
270 /**
271 * Releases the iframe reserved for this suggestion.
272 */
273 destroy: function() {
274 if (this.iframe_)
275 iframePool.release(this.iframe_);
276 },
277
278 /**
279 * Creates and appends the placeholder div for this suggestion to box.
280 * @param {Element} box A suggestions box.
281 * @param {boolean} selected True if the suggestion should be drawn as
282 * selected and false otherwise.
283 */
284 appendToBox: function(box, selected) {
285 var div = document.createElement('div');
286 div.classList.add('suggestion');
287 div.classList.toggle('selected', selected);
288 div.classList.toggle('search', this.data_.is_search);
289 box.appendChild(div);
290 this.div_ = div;
291 },
292
293 /**
294 * Repositions the suggestion iframe to align with its expected dropdown
295 * position.
296 * @param {boolean} isRtl True if rendering right-to-left and false if not.
297 * @param {number} startMargin Leading space before suggestion.
298 * @param {number} totalMargin Total non-content space on suggestion line.
299 */
300 reposition: function(isRtl, startMargin, totalMargin) {
301 // Add in the expected parent offset and the top margin.
302 this.iframe_.style.top = this.div_.offsetTop + SUGGESTION_TOP_OFFSET + 'px';
303 // Call parseInt to enforce that startMargin and totalMargin are really
304 // numbers since we're interpolating CSS.
305 startMargin = parseInt(startMargin, 10);
306 totalMargin = parseInt(totalMargin, 10);
307 if (isFinite(startMargin) && isFinite(totalMargin)) {
308 this.iframe_.style[isRtl ? 'right' : 'left'] = startMargin + 'px';
309 this.iframe_.style.width = '-webkit-calc(100% - ' +
310 (totalMargin + SUGGESTION_ICON_PADDING) + 'px)';
311 }
312 },
313
314 /**
315 * Updates the suggestion selection state.
316 * @param {boolean} selected True if drawn selected or false if not.
317 */
318 select: function(selected) {
319 this.div_.classList.toggle('selected', selected);
320 },
321
322 /**
323 * Updates the suggestion hover state.
324 * @param {boolean} hovered True if drawn hovered or false if not.
325 */
326 hover: function(hovered) {
327 this.div_.classList.toggle('hovered', hovered);
328 },
329
330 /**
331 * @param {Window} iframeWindow The content window of an iframe.
332 * @return {boolean} True if this suggestion's iframe has the specified
333 * window and false if not.
334 */
335 hasIframeWindow: function(iframeWindow) {
336 return this.iframe_.contentWindow == iframeWindow;
337 },
338
339 /**
340 * @param {string} id An element id.
341 * @return {boolean} True if this suggestion's iframe has the specified id
342 * and false if not.
343 */
344 hasIframeId: function(id) {
345 return this.iframe_.id == id;
346 },
347
348 /**
349 * The iframe element for this suggestion.
350 * @type {Element}
351 */
352 set iframe(iframe) {
353 this.iframe_ = iframe;
354 },
355
356 /**
357 * The restricted id associated with this suggestion.
358 * @type {number}
359 */
360 get restrictedId() {
361 return this.data_.rid;
362 },
363 };
364
365
366 /**
367 * Displays a suggestions box.
368 * @param {string} inputValue The user text that prompted these suggestions.
369 * @param {!Array.<!Object>} suggestionData Suggestion data to display.
370 * @param {number} selectedIndex The index of the suggestion selected.
371 * @constructor
372 */
373 function SuggestionsBox(inputValue, suggestionData, selectedIndex) {
374 /**
375 * The user text that prompted these suggestions.
376 * @type {string}
377 * @private
378 */
379 this.inputValue_ = inputValue;
380
381 /**
382 * The index of the suggestion currently selected, whether by default or
383 * because the user arrowed down to it.
384 * @type {number}
385 * @private
386 */
387 this.selectedIndex_ = selectedIndex;
388
389 /**
390 * The index of the suggestion currently under the mouse pointer.
391 * @type {number}
392 * @private
393 */
394 this.hoveredIndex_ = -1;
395
396 /**
397 * A stamp to distinguish this suggestions box from others.
398 * @type {number}
399 * @private
400 */
401 this.requestId_ = nextRequestId++;
402
403 /**
404 * The ordered suggestions this box is displaying.
405 * @type {Array.<Suggestion>}
406 * @private
407 */
408 this.suggestions_ = [];
409 for (var i = 0; i < suggestionData.length; ++i) {
410 this.suggestions_.push(new Suggestion(suggestionData[i]));
411 }
412
413 /**
414 * An embedded search API handle.
415 * @type {Object}
416 * @private
417 */
418 this.apiHandle_ = getApiObjectHandle();
419
420 /**
421 * The container for this suggestions box. div.pending-container if inactive
422 * and div.active-container if active.
423 * @type {Element}
424 * @private
425 */
426 this.container_ = $qs('.pending-container');
427 assert(this.container_);
428 }
429
430 SuggestionsBox.prototype = {
431 /**
432 * Releases suggestion iframes and ignores any load done message for the
433 * current suggestions.
434 */
435 destroy: function() {
436 while (this.suggestions_.length > 0) {
437 this.suggestions_.pop().destroy();
438 }
439 this.responseId = -1;
440 },
441
442 /**
443 * Starts rendering new suggestions.
444 */
445 loadSuggestions: function() {
446 // Create a placeholder DOM in the invisible container.
447 this.container_.innerHTML = '';
448
449 var box = document.createElement('div');
450 box.className = 'suggestions-box';
451 this.container_.appendChild(box);
452
453 var iframesToLoad = {};
454 for (var i = 0; i < this.suggestions_.length; ++i) {
455 var suggestion = this.suggestions_[i];
456 suggestion.appendToBox(box, i == this.selectedIndex_);
457 var iframe = iframePool.reserve();
458 suggestion.iframe = iframe;
459 iframesToLoad[iframe.id] = suggestion.restrictedId;
460 }
461
462 // Ask the loader iframe to populate the iframes just reserved.
463 var loadRequest = {
464 load: iframesToLoad,
465 requestId: this.requestId_,
466 style: {
467 queryColor: QUERY_COLOR,
468 urlColor: URL_COLOR,
469 titleColor: TITLE_COLOR
470 }
471 };
472 $qs('#suggestion-loader').contentWindow.postMessage(loadRequest,
473 SUGGESTION_ORIGIN);
474 },
475
476 /**
477 * @param {number} responseId The id of a request that just finished
478 * rendering.
479 * @return {boolean} Whether the request is for the suggestions in this box.
480 */
481 isResponseCurrent: function(responseId) {
482 return responseId == this.requestId_;
483 },
484
485 /**
486 * Moves suggestion iframes into position.
487 */
488 repositionSuggestions: function() {
489 // Note: This may be called before margins are ready. In that case,
490 // suggestion iframes will initially be too large and then size down
491 // onresize.
492 var startMargin = this.apiHandle_.startMargin;
493 var totalMargin = window.innerWidth - this.apiHandle_.width;
494 var isRtl = this.apiHandle_.isRtl;
495 for (var i = 0; i < this.suggestions_.length; ++i) {
496 this.suggestions_[i].reposition(isRtl, startMargin, totalMargin);
497 }
498 },
499
500 /**
501 * Selects the suggestion before the current selection.
502 */
503 selectPrevious: function() {
504 this.changeSelection_(this.selectedIndex_ - 1);
505 },
506
507 /**
508 * Selects the suggestion after the current selection.
509 */
510 selectNext: function() {
511 this.changeSelection_(this.selectedIndex_ + 1);
512 },
513
514 /**
515 * Changes the current selected suggestion index.
516 * @param {number} index The new selection to suggest.
517 * @private
518 */
519 changeSelection_: function(index) {
520 var numSuggestions = this.suggestions_.length;
521 this.selectedIndex_ = Math.min(numSuggestions - 1, Math.max(-1, index));
522
523 this.redrawSelection_();
524 this.redrawHover_();
525 },
526
527 /**
528 * Redraws the selected suggestion.
529 * @private
530 */
531 redrawSelection_: function() {
532 var oldSelection = this.container_.querySelector('.selected');
533 if (oldSelection)
534 oldSelection.classList.remove('selected');
535 if (this.selectedIndex_ == -1) {
536 this.apiHandle_.setValue(this.inputValue_);
537 } else {
538 this.suggestions_[this.selectedIndex_].select(true);
539 this.apiHandle_.setRestrictedValue(
540 this.suggestions_[this.selectedIndex_].restrcitedId);
541 }
542 },
543
544 /**
545 * Returns the restricted id of the iframe clicked.
546 * @param {!Window} iframeWindow The window of the iframe that was clicked.
547 * @return {?number} The restricted id clicked or null if none.
548 */
549 getClickTarget: function(iframeWindow) {
550 for (var i = 0; i < this.suggestions_.length; ++i) {
551 if (this.suggestions_[i].hasIframeWindow(iframeWindow))
552 return this.suggestions_[i].restrictedId;
553 }
554 return null;
555 },
556
557 /**
558 * Called when the user hovers on the specified iframe.
559 * @param {string} iframeId The id of the iframe hovered.
560 */
561 hover: function(iframeId) {
562 this.hoveredIndex_ = -1;
563 for (var i = 0; i < this.suggestions_.length; ++i) {
564 if (this.suggestions_[i].hasIframeId(iframeId)) {
565 this.hoveredIndex_ = i;
566 break;
567 }
568 }
569 this.redrawHover_();
570 },
571
572 /**
573 * Called when the user unhovers the specified iframe.
574 * @param {string} iframeId The id of the iframe hovered.
575 */
576 unhover: function(iframeId) {
577 if (this.suggestions_[this.hoveredIndex_] &&
578 this.suggestions_[this.hoveredIndex_].hasIframeId(iframeId)) {
579 this.clearHover();
580 }
581 },
582
583 /**
584 * Clears the current hover.
585 */
586 clearHover: function() {
587 this.hoveredIndex_ = -1;
588 this.redrawHover_();
589 },
590
591 /**
592 * Redraws the mouse hover background.
593 * @private
594 */
595 redrawHover_: function() {
596 var oldHover = this.container_.querySelector('.hovered');
597 if (oldHover)
598 oldHover.classList.remove('hovered');
599 if (this.hoveredIndex_ != -1 && this.hoveredIndex_ != this.selectedIndex_)
600 this.suggestions_[this.hoveredIndex_].hover(true);
601 },
602
603 /**
604 * Marks the suggestions container as active.
605 */
606 activate: function() {
607 this.container_.className = 'active-container';
608 },
609
610 /**
611 * Marks the suggestions container as inactive.
612 */
613 deactivate: function() {
614 this.container_.className = 'pending-container';
615 this.container_.innerHTML = '';
616 },
617
618 /**
619 * The height of the suggestions container.
620 * @type {number}
621 */
622 get height() {
623 return this.container_.offsetHeight;
624 },
625 };
626
627
628 /**
629 * Clears the currently active suggestions and shows pending suggestions.
630 */
631 function makePendingSuggestionsActive() {
632 if (activeBox) {
633 activeBox.deactivate();
634 activeBox.destroy();
196 } else { 635 } else {
197 var newSelection = $('suggestionsBox').querySelector( 636 // Initially there will be no active suggestions, but we still want to use
198 '.suggestion:nth-of-type(' + (selectedIndex + 1) + ')'); 637 // div.active-container to load the next suggestions.
199 newSelection.classList.add('selected'); 638 $qs('.active-container').className = 'pending-container';
200 apiHandle.setRestrictedValue(restrictedIds[selectedIndex]);
201 } 639 }
202 } 640 pendingBox.activate();
203 641 activeBox = pendingBox;
204 // ============================================================================= 642 pendingBox = null;
205 // Handlers / API stuff 643 activeBox.repositionSuggestions();
206 // ============================================================================= 644 getApiObjectHandle().showOverlay(activeBox.height);
645 }
646
647 /**
648 * Hides the active suggestions box.
649 */
650 function hideActiveSuggestions() {
651 getApiObjectHandle().showOverlay(0);
652 if (activeBox) {
653 $qs('.active-container').innerHTML = '';
654 activeBox.destroy();
655 }
656 activeBox = null;
657 }
207 658
208 /** 659 /**
209 * @return {Object} the handle to the searchBox API. 660 * @return {Object} the handle to the searchBox API.
210 */ 661 */
211 function getApiObjectHandle() { 662 function getApiObjectHandle() {
212 if (window.cideb) 663 if (window.cideb)
213 return window.cideb; 664 return window.cideb;
214 if (window.navigator && window.navigator.embeddedSearch && 665 if (window.navigator && window.navigator.embeddedSearch &&
215 window.navigator.embeddedSearch.searchBox) 666 window.navigator.embeddedSearch.searchBox)
216 return window.navigator.embeddedSearch.searchBox; 667 return window.navigator.embeddedSearch.searchBox;
217 if (window.chrome && window.chrome.embeddedSearch && 668 if (window.chrome && window.chrome.embeddedSearch &&
218 window.chrome.embeddedSearch.searchBox) 669 window.chrome.embeddedSearch.searchBox)
219 return window.chrome.embeddedSearch.searchBox; 670 return window.chrome.embeddedSearch.searchBox;
220 return null; 671 return null;
221 } 672 }
222 673
223 /** 674 /**
224 * Updates suggestions in response to a onchange or onnativesuggestions call. 675 * Updates suggestions in response to a onchange or onnativesuggestions call.
225 */ 676 */
226 function updateSuggestions() { 677 function updateSuggestions() {
678 if (pendingBox)
679 pendingBox.destroy();
680 pendingBox = null;
227 var apiHandle = getApiObjectHandle(); 681 var apiHandle = getApiObjectHandle();
228 lastInputValue = apiHandle.value; 682 var inputValue = apiHandle.value;
229 683 var suggestions = apiHandle.nativeSuggestions;
230 clearSuggestions(); 684 if (!inputValue || !suggestions.length) {
231 var nativeSuggestions = apiHandle.nativeSuggestions; 685 hideActiveSuggestions();
232 if (nativeSuggestions.length) { 686 return;
233 nativeSuggestions.sort(function(a, b) { 687 }
688 if (suggestions.length) {
689 suggestions.sort(function(a, b) {
234 return b.rankingData.relevance - a.rankingData.relevance; 690 return b.rankingData.relevance - a.rankingData.relevance;
235 }); 691 });
236 if (shouldSelectSuggestion(nativeSuggestions[0], apiHandle.verbatim)) 692 var selectedIndex = -1;
693 if (shouldSelectSuggestion(suggestions[0], apiHandle.verbatim))
237 selectedIndex = 0; 694 selectedIndex = 0;
238 renderSuggestions(nativeSuggestions); 695 pendingBox = new SuggestionsBox(inputValue,
696 suggestions.slice(0, MAX_SUGGESTIONS_TO_SHOW), selectedIndex);
697 pendingBox.loadSuggestions();
239 } 698 }
240
241 var height = getDropdownHeight();
242 apiHandle.showOverlay(height);
243 } 699 }
244 700
245 /** 701 /**
246 * Appends a style node for suggestion properties that depend on apiHandle. 702 * Appends a style node for suggestion properties that depend on apiHandle.
247 */ 703 */
248 function appendSuggestionStyles() { 704 function appendSuggestionStyles() {
249 var apiHandle = getApiObjectHandle(); 705 var apiHandle = getApiObjectHandle();
250 var isRtl = apiHandle.rtl; 706 var isRtl = apiHandle.rtl;
251 var startMargin = apiHandle.startMargin; 707 var startMargin = apiHandle.startMargin;
252 var style = document.createElement('style'); 708 var style = document.createElement('style');
253 style.type = 'text/css'; 709 style.type = 'text/css';
254 style.id = 'suggestionStyle'; 710 style.id = 'suggestionStyle';
255 style.textContent = 711 style.textContent =
256 '.suggestion, ' + 712 '.suggestion, ' +
257 '.suggestion.search {' + 713 '.suggestion.search {' +
258 ' background-position: ' + 714 ' background-position: ' +
259 (isRtl ? '-webkit-calc(100% - 5px)' : '5px') + ' 4px;' + 715 (isRtl ? '-webkit-calc(100% - 5px)' : '5px') + ' 4px;' +
260 ' -webkit-margin-start: ' + startMargin + 'px;' + 716 ' -webkit-margin-start: ' + startMargin + 'px;' +
261 ' -webkit-margin-end: ' + 717 ' -webkit-margin-end: ' +
262 (window.innerWidth - apiHandle.width - startMargin) + 'px;' + 718 (window.innerWidth - apiHandle.width - startMargin) + 'px;' +
263 ' font: ' + apiHandle.fontSize + 'px "' + apiHandle.font + '";' + 719 ' font: ' + apiHandle.fontSize + 'px "' + apiHandle.font + '";' +
264 '}'; 720 '}';
265 document.querySelector('head').appendChild(style); 721 $qs('head').appendChild(style);
722 if (activeBox)
723 activeBox.repositionSuggestions();
266 window.removeEventListener('resize', appendSuggestionStyles); 724 window.removeEventListener('resize', appendSuggestionStyles);
267 } 725 }
268 726
269 /** 727 /**
270 * Extract the desired navigation behavior from a click button. 728 * Makes keys navigate through suggestions.
271 * @param {number} button The Event#button property of a click event.
272 * @return {WindowOpenDisposition} The desired behavior for
273 * navigateContentWindow.
274 */
275 function getDispositionFromClickButton(button) {
276 if (button == MIDDLE_MOUSE_BUTTON)
277 return WindowOpenDisposition.NEW_BACKGROUND_TAB;
278 return WindowOpenDisposition.CURRENT_TAB;
279 }
280
281 /**
282 * Handles suggestion clicks.
283 * @param {number} restrictedId The restricted id of the suggestion being
284 * clicked.
285 * @param {number} button The Event#button property of a click event.
286 *
287 */
288 function handleSuggestionClick(restrictedId, button) {
289 clearSuggestions();
290 getApiObjectHandle().navigateContentWindow(
291 restrictedId, getDispositionFromClickButton(button));
292 }
293
294 /**
295 * chrome.searchBox.onkeypress implementation.
296 * @param {Object} e The key being pressed. 729 * @param {Object} e The key being pressed.
297 */ 730 */
298 function handleKeyPress(e) { 731 function handleKeyPress(e) {
732 if (!activeBox)
733 return;
734
299 switch (e.keyCode) { 735 switch (e.keyCode) {
300 case 38: // Up arrow 736 case KEY_UP_ARROW:
301 updateSelectedSuggestion(false); 737 activeBox.selectPrevious();
302 break; 738 break;
303 case 40: // Down arrow 739 case KEY_DOWN_ARROW:
304 updateSelectedSuggestion(true); 740 activeBox.selectNext();
305 break; 741 break;
306 } 742 }
307 } 743 }
308 744
309 /** 745 /**
310 * Handles the postMessage calls from the result iframes. 746 * Handles postMessage calls from suggestion iframes.
311 * @param {Object} message The message containing details of clicks the iframes. 747 * @param {Object} message A notification that all iframes are done loading or
748 * that an iframe was clicked.
312 */ 749 */
313 function handleMessage(message) { 750 function handleMessage(message) {
314 if (message.origin != 'null' || !message.data || 751 if (message.origin != SUGGESTION_ORIGIN)
315 message.data.eventType != 'click') {
316 return; 752 return;
317 }
318 753
319 var iframes = document.getElementsByClassName('contents'); 754 if ('loaded' in message.data) {
320 for (var i = 0; i < iframes.length; ++i) { 755 if (pendingBox && pendingBox.isResponseCurrent(message.data.loaded)) {
Dan Beam 2013/04/08 16:46:58 no curlies
Jered 2013/04/08 21:43:16 Done.
321 if (iframes[i].contentWindow == message.source) { 756 makePendingSuggestionsActive();
322 handleSuggestionClick(parseInt(iframes[i].id, 10), 757 }
323 message.data.button); 758 } else if ('click' in message.data) {
324 break; 759 if (activeBox) {
760 var restrictedId = activeBox.getClickTarget(message.source);
761 if (restrictedId != null) {
762 hideActiveSuggestions();
763 getApiObjectHandle().navigateContentWindow(restrictedId,
764 getDispositionFromClickButton(message.data.click));
765 }
325 } 766 }
326 } 767 }
327 } 768 }
328 769
329 /** 770 /**
330 * chrome.searchBox.embeddedSearch.onsubmit implementation. 771 * Sets up the embedded search API and creates suggestion iframes.
331 */ 772 */
332 function onSubmit() { 773 function init() {
333 } 774 iframePool = new IframePool();
334 775 iframePool.init();
335 /**
336 * Sets up the searchBox API.
337 */
338 function setUpApi() {
339 var apiHandle = getApiObjectHandle(); 776 var apiHandle = getApiObjectHandle();
340 apiHandle.onnativesuggestions = updateSuggestions; 777 apiHandle.onnativesuggestions = updateSuggestions;
341 apiHandle.onchange = updateSuggestions; 778 apiHandle.onchange = updateSuggestions;
342 apiHandle.onkeypress = handleKeyPress; 779 apiHandle.onkeypress = handleKeyPress;
343 apiHandle.onsubmit = onSubmit; 780 // Instant checks for this handler to be bound.
344 $('suggestions-box-container').dir = apiHandle.rtl ? 'rtl' : 'ltr'; 781 apiHandle.onsubmit = function() {};
782 $qs('.active-container').dir = apiHandle.rtl ? 'rtl' : 'ltr';
783 $qs('.pending-container').dir = apiHandle.rtl ? 'rtl' : 'ltr';
345 // Delay adding these styles until the window width is available. 784 // Delay adding these styles until the window width is available.
346 window.addEventListener('resize', appendSuggestionStyles); 785 window.addEventListener('resize', appendSuggestionStyles);
347 if (apiHandle.nativeSuggestions.length) 786 if (apiHandle.nativeSuggestions.length)
348 handleNativeSuggestions(); 787 updateSuggestions();
349 } 788 }
350 789
351 document.addEventListener('DOMContentLoaded', setUpApi); 790 document.addEventListener('DOMContentLoaded', init);
352 window.addEventListener('message', handleMessage, false); 791 window.addEventListener('message', handleMessage, false);
792 window.addEventListener('blur', function() {
793 if (activeBox)
794 activeBox.clearHover();
795 }, false);
796 })();
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698