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

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

Issue 13905008: Merge local_omnibox_popup into local_ntp. Render the Google logo and fakebox if Google is the sear… (Closed) Base URL: https://git.chromium.org/chromium/src.git@master
Patch Set: 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
OLDNEW
1 // Copyright 2013 The Chromium Authors. All rights reserved. 1 // Copyright 2013 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 (function() { 5 (function() {
6
7 /**
8 * True if this a Google page and not some other search provider. Used to
9 * determine whether to show the logo and fakebox.
10 * TODO(jeremycho): Pull this from a CGI parameter.
11 * @type {boolean}
12 */
13 var isGooglePage = false;
samarth 2013/04/15 19:01:34 See http://git.chromium.org/gitweb/?p=chromium/chr
jeremycho 2013/04/16 01:42:37 Done.
14
15 // ==========================================================
16 // Enums
17 // ==========================================================
18
19 /**
20 * Enum for classnames.
21 * @enum {string}
22 * @const
23 */
24 var CLASSES = {
25 BLACKLIST: 'mv-blacklist', // triggers tile blacklist animation
26 BLACKLIST_BUTTON: 'mv-x',
27 DELAYED_HIDE_NOTIFICATION: 'mv-notice-delayed-hide',
28 DOMAIN: 'mv-domain',
29 FAKEBOX_ANIMATE: 'fakebox-animate', // triggers fakebox animation
30 FAKEBOX_FOCUS: 'fakebox-focused', // Applies focus styles to the fakebox
31 FAVICON: 'mv-favicon',
32 FILLER: 'mv-filler', // filler tiles
33 GOOGLE_PAGE: 'google-page', // shows the Google logo and fakebox
34 HIDE_BLACKLIST_BUTTON: 'mv-x-hide', // hides blacklist button during animation
35 HIDE_NOTIFICATION: 'mv-notice-hide',
36 HIDE_TILE: 'mv-tile-hide', // hides tiles on small browser width
37 PAGE: 'mv-page', // page tiles
38 THUMBNAIL: 'mv-thumb',
39 TILE: 'mv-tile',
40 TITLE: 'mv-title'
41 };
42
43 /**
44 * Enum for HTML element ids.
45 * @enum {string}
46 * @const
47 */
48 var IDS = {
49 ATTRIBUTION: 'attribution',
50 CURSOR: 'cursor',
51 FAKEBOX: 'fakebox',
52 NOTIFICATION: 'mv-notice',
53 NOTIFICATION_CLOSE_BUTTON: 'mv-notice-x',
54 NOTIFICATION_MESSAGE: 'mv-msg',
55 NTP_CONTENTS: 'ntp-contents',
56 RESTORE_ALL_LINK: 'mv-restore',
57 SUGGESTIONS_BOX: 'suggestions-box',
58 SUGGESTIONS_CONTAINER: 'suggestions-box-container',
59 TILES: 'mv-tiles',
60 TOP_MARGIN: 'mv-top-margin',
61 UNDO_LINK: 'mv-undo'
62 };
63
64 // =============================================================================
65 // NTP implementation
66 // =============================================================================
67
6 /** 68 /**
7 * The element used to vertically position the most visited section on 69 * The element used to vertically position the most visited section on
8 * window resize. 70 * window resize.
9 * @type {Element} 71 * @type {Element}
10 */ 72 */
11 var topMarginElement; 73 var topMarginElement;
12 74
13 /** 75 /**
14 * The container for the tile elements. 76 * The container for the tile elements.
15 * @type {Element} 77 * @type {Element}
16 */ 78 */
17 var tilesContainer; 79 var tilesContainer;
18 80
19 /** 81 /**
20 * The notification displayed when a page is blacklisted. 82 * The notification displayed when a page is blacklisted.
21 * @type {Element} 83 * @type {Element}
22 */ 84 */
23 var notification; 85 var notification;
24 86
25 /** 87 /**
26 * The container for the theme attribution. 88 * The container for the theme attribution.
27 * @type {Element} 89 * @type {Element}
28 */ 90 */
29 var attribution; 91 var attribution;
30 92
31 /** 93 /**
94 * The fakebox.
samarth 2013/04/15 19:01:34 Please add comments explaining what a "fakebox" is
jeremycho 2013/04/16 01:42:37 Done.
95 * @type {Element}
96 */
97 var fakebox;
98
99 /**
32 * The array of rendered tiles, ordered by appearance. 100 * The array of rendered tiles, ordered by appearance.
33 * @type {Array.<Tile>} 101 * @type {Array.<Tile>}
34 */ 102 */
35 var tiles = []; 103 var tiles = [];
36 104
37 /** 105 /**
38 * The last blacklisted tile if any, which by definition should not be filler. 106 * The last blacklisted tile if any, which by definition should not be filler.
39 * @type {?Tile} 107 * @type {?Tile}
40 */ 108 */
41 var lastBlacklistedTile = null; 109 var lastBlacklistedTile = null;
(...skipping 24 matching lines...) Expand all
66 /** 134 /**
67 * Current number of tiles shown based on the window width, including filler. 135 * Current number of tiles shown based on the window width, including filler.
68 * @type {number} 136 * @type {number}
69 */ 137 */
70 var numTilesShown = 0; 138 var numTilesShown = 0;
71 139
72 /** 140 /**
73 * The browser embeddedSearch.newTabPage object. 141 * The browser embeddedSearch.newTabPage object.
74 * @type {Object} 142 * @type {Object}
75 */ 143 */
76 var apiHandle; 144 var ntpApiHandle;
77 145
78 /** 146 /**
79 * Possible background-colors of a non-custom theme. Used to determine whether 147 * Possible background-colors of a non-custom theme. Used to determine whether
80 * the homepage should be updated to support custom or non-custom themes. 148 * the homepage should be updated to support custom or non-custom themes.
81 * @type {!Array.<string>} 149 * @type {!Array.<string>}
82 * @const 150 * @const
83 */ 151 */
84 var WHITE = ['rgba(255,255,255,1)', 'rgba(0,0,0,0)']; 152 var WHITE = ['rgba(255,255,255,1)', 'rgba(0,0,0,0)'];
85 153
86 /** 154 /**
(...skipping 18 matching lines...) Expand all
105 173
106 /** 174 /**
107 * Minimum total padding to give to the left and right of the most visited 175 * Minimum total padding to give to the left and right of the most visited
108 * section. Used to determine how many tiles to show. 176 * section. Used to determine how many tiles to show.
109 * @type {number} 177 * @type {number}
110 * @const 178 * @const
111 */ 179 */
112 var MIN_TOTAL_HORIZONTAL_PADDING = 188; 180 var MIN_TOTAL_HORIZONTAL_PADDING = 188;
113 181
114 /** 182 /**
115 * Enum for classnames.
116 * @enum {string}
117 * @const
118 */
119 var CLASSES = {
120 BLACKLIST: 'mv-blacklist', // triggers tile blacklist animation
121 BLACKLIST_BUTTON: 'mv-x',
122 DELAYED_HIDE_NOTIFICATION: 'mv-notice-delayed-hide',
123 DOMAIN: 'mv-domain',
124 FAVICON: 'mv-favicon',
125 FILLER: 'mv-filler', // filler tiles
126 HIDE_BLACKLIST_BUTTON: 'mv-x-hide', // hides blacklist button during animation
127 HIDE_NOTIFICATION: 'mv-notice-hide',
128 HIDE_TILE: 'mv-tile-hide', // hides tiles on small browser width
129 PAGE: 'mv-page', // page tiles
130 THUMBNAIL: 'mv-thumb',
131 TILE: 'mv-tile',
132 TITLE: 'mv-title'
133 };
134
135 /**
136 * Enum for HTML element ids.
137 * @enum {string}
138 * @const
139 */
140 var IDS = {
141 ATTRIBUTION: 'attribution',
142 NOTIFICATION: 'mv-notice',
143 NOTIFICATION_CLOSE_BUTTON: 'mv-notice-x',
144 NOTIFICATION_MESSAGE: 'mv-msg',
145 RESTORE_ALL_LINK: 'mv-restore',
146 TILES: 'mv-tiles',
147 TOP_MARGIN: 'mv-top-margin',
148 UNDO_LINK: 'mv-undo'
149 };
150
151 /**
152 * A Tile is either a rendering of a Most Visited page or "filler" used to 183 * A Tile is either a rendering of a Most Visited page or "filler" used to
153 * pad out the section when not enough pages exist. 184 * pad out the section when not enough pages exist.
154 * 185 *
155 * @param {Element} elem The element for rendering the tile. 186 * @param {Element} elem The element for rendering the tile.
156 * @param {number=} opt_rid The RID for the corresponding Most Visited page. 187 * @param {number=} opt_rid The RID for the corresponding Most Visited page.
157 * Should only be left unspecified when creating a filler tile. 188 * Should only be left unspecified when creating a filler tile.
158 * @constructor 189 * @constructor
159 */ 190 */
160 function Tile(elem, opt_rid) { 191 function Tile(elem, opt_rid) {
161 /** @type {Element} */ 192 /** @type {Element} */
162 this.elem = elem; 193 this.elem = elem;
163 194
164 /** @type {number|undefined} */ 195 /** @type {number|undefined} */
165 this.rid = opt_rid; 196 this.rid = opt_rid;
166 } 197 }
167 198
168 /** 199 /**
169 * Updates the NTP based on the current theme. 200 * Updates the NTP based on the current theme.
170 * @private 201 * @private
171 */ 202 */
172 function onThemeChange() { 203 function onThemeChange() {
173 var info = apiHandle.themeBackgroundInfo; 204 if (!isNtpVisible())
205 return;
206
207 var info = ntpApiHandle.themeBackgroundInfo;
174 if (!info) 208 if (!info)
175 return; 209 return;
176 var background = [info.colorRgba, 210 var background = [info.colorRgba,
177 info.imageUrl, 211 info.imageUrl,
178 info.imageTiling, 212 info.imageTiling,
179 info.imageHorizontalAlignment, 213 info.imageHorizontalAlignment,
180 info.imageVerticalAlignment].join(' ').trim(); 214 info.imageVerticalAlignment].join(' ').trim();
181 document.body.style.background = background; 215 document.body.style.background = background;
182 var isCustom = !!background && WHITE.indexOf(background) == -1; 216 var isCustom = !!background && WHITE.indexOf(background) == -1;
183 document.body.classList.toggle('custom-theme', isCustom); 217 document.body.classList.toggle('custom-theme', isCustom);
(...skipping 22 matching lines...) Expand all
206 attributionImage.onerror = function() { 240 attributionImage.onerror = function() {
207 attribution.hidden = true; 241 attribution.hidden = true;
208 }; 242 };
209 attributionImage.src = url; 243 attributionImage.src = url;
210 } 244 }
211 245
212 /** 246 /**
213 * Handles a new set of Most Visited page data. 247 * Handles a new set of Most Visited page data.
214 */ 248 */
215 function onMostVisitedChange() { 249 function onMostVisitedChange() {
216 var pages = apiHandle.mostVisited; 250 var pages = ntpApiHandle.mostVisited;
217 251
218 if (isBlacklisting) { 252 if (isBlacklisting) {
219 // If this was called as a result of a blacklist, add a new replacement 253 // If this was called as a result of a blacklist, add a new replacement
220 // (possibly filler) tile at the end and trigger the blacklist animation. 254 // (possibly filler) tile at the end and trigger the blacklist animation.
221 var replacementTile = createTile(pages[MAX_NUM_TILES_TO_SHOW - 1]); 255 var replacementTile = createTile(pages[MAX_NUM_TILES_TO_SHOW - 1]);
222 256
223 tiles.push(replacementTile); 257 tiles.push(replacementTile);
224 tilesContainer.appendChild(replacementTile.elem); 258 tilesContainer.appendChild(replacementTile.elem);
225 259
226 var lastBlacklistedTileElement = lastBlacklistedTile.elem; 260 var lastBlacklistedTileElement = lastBlacklistedTile.elem;
(...skipping 47 matching lines...) Expand 10 before | Expand all | Expand 10 after
274 function createTile(page) { 308 function createTile(page) {
275 var tileElement = document.createElement('div'); 309 var tileElement = document.createElement('div');
276 tileElement.classList.add(CLASSES.TILE); 310 tileElement.classList.add(CLASSES.TILE);
277 311
278 if (page) { 312 if (page) {
279 var rid = page.rid; 313 var rid = page.rid;
280 tileElement.classList.add(CLASSES.PAGE); 314 tileElement.classList.add(CLASSES.PAGE);
281 315
282 // The click handler for navigating to the page identified by the RID. 316 // The click handler for navigating to the page identified by the RID.
283 tileElement.addEventListener('click', function() { 317 tileElement.addEventListener('click', function() {
284 apiHandle.navigateContentWindow(rid); 318 ntpApiHandle.navigateContentWindow(rid);
285 }); 319 });
286 320
287 // The shadow DOM which renders the page title. 321 // The shadow DOM which renders the page title.
288 var titleElement = page.titleElement; 322 var titleElement = page.titleElement;
289 if (titleElement) { 323 if (titleElement) {
290 titleElement.classList.add(CLASSES.TITLE); 324 titleElement.classList.add(CLASSES.TITLE);
291 tileElement.appendChild(titleElement); 325 tileElement.appendChild(titleElement);
292 } 326 }
293 327
294 // Render the thumbnail if present. Otherwise, fall back to a shadow DOM 328 // Render the thumbnail if present. Otherwise, fall back to a shadow DOM
(...skipping 53 matching lines...) Expand 10 before | Expand all | Expand 10 after
348 function generateBlacklistFunction(rid) { 382 function generateBlacklistFunction(rid) {
349 return function(e) { 383 return function(e) {
350 // Prevent navigation when the page is being blacklisted. 384 // Prevent navigation when the page is being blacklisted.
351 e.stopPropagation(); 385 e.stopPropagation();
352 386
353 showNotification(); 387 showNotification();
354 isBlacklisting = true; 388 isBlacklisting = true;
355 tilesContainer.classList.add(CLASSES.HIDE_BLACKLIST_BUTTON); 389 tilesContainer.classList.add(CLASSES.HIDE_BLACKLIST_BUTTON);
356 lastBlacklistedTile = getTileByRid(rid); 390 lastBlacklistedTile = getTileByRid(rid);
357 lastBlacklistedIndex = tiles.indexOf(lastBlacklistedTile); 391 lastBlacklistedIndex = tiles.indexOf(lastBlacklistedTile);
358 apiHandle.deleteMostVisitedItem(rid); 392 ntpApiHandle.deleteMostVisitedItem(rid);
359 }; 393 };
360 } 394 }
361 395
362 /** 396 /**
363 * Shows the blacklist notification and triggers a delay to hide it. 397 * Shows the blacklist notification and triggers a delay to hide it.
364 */ 398 */
365 function showNotification() { 399 function showNotification() {
366 notification.classList.remove(CLASSES.HIDE_NOTIFICATION); 400 notification.classList.remove(CLASSES.HIDE_NOTIFICATION);
367 notification.classList.remove(CLASSES.DELAYED_HIDE_NOTIFICATION); 401 notification.classList.remove(CLASSES.DELAYED_HIDE_NOTIFICATION);
368 notification.scrollTop; 402 notification.scrollTop;
(...skipping 22 matching lines...) Expand all
391 425
392 /** 426 /**
393 * Handles a click on the notification undo link by hiding the notification and 427 * Handles a click on the notification undo link by hiding the notification and
394 * informing Chrome. 428 * informing Chrome.
395 */ 429 */
396 function onUndo() { 430 function onUndo() {
397 hideNotification(); 431 hideNotification();
398 var lastBlacklistedRID = lastBlacklistedTile.rid; 432 var lastBlacklistedRID = lastBlacklistedTile.rid;
399 if (typeof lastBlacklistedRID != 'undefined') { 433 if (typeof lastBlacklistedRID != 'undefined') {
400 isUndoing = true; 434 isUndoing = true;
401 apiHandle.undoMostVisitedDeletion(lastBlacklistedRID); 435 ntpApiHandle.undoMostVisitedDeletion(lastBlacklistedRID);
402 } 436 }
403 } 437 }
404 438
405 /** 439 /**
406 * Handles the end of the undo animation by removing the extraneous end tile. 440 * Handles the end of the undo animation by removing the extraneous end tile.
407 */ 441 */
408 function undoAnimationDone() { 442 function undoAnimationDone() {
409 isUndoing = false; 443 isUndoing = false;
410 tiles.splice(tiles.length - 1, 1); 444 tiles.splice(tiles.length - 1, 1);
411 removeNode(tilesContainer.lastElementChild); 445 removeNode(tilesContainer.lastElementChild);
412 updateTileVisibility(numTilesShown); 446 updateTileVisibility(numTilesShown);
413 lastBlacklistedTile.elem.removeEventListener( 447 lastBlacklistedTile.elem.removeEventListener(
414 'webkitTransitionEnd', undoAnimationDone); 448 'webkitTransitionEnd', undoAnimationDone);
415 } 449 }
416 450
417 /** 451 /**
418 * Handles a click on the restore all notification link by hiding the 452 * Handles a click on the restore all notification link by hiding the
419 * notification and informing Chrome. 453 * notification and informing Chrome.
420 */ 454 */
421 function onRestoreAll() { 455 function onRestoreAll() {
422 hideNotification(); 456 hideNotification();
423 apiHandle.undoAllMostVisitedDeletions(); 457 ntpApiHandle.undoAllMostVisitedDeletions();
424 } 458 }
425 459
426 /** 460 /**
427 * Handles a resize by vertically centering the most visited section 461 * Handles a resize by vertically centering the most visited section
428 * and triggering the tile show/hide animation if necessary. 462 * and triggering the tile show/hide animation if necessary.
429 */ 463 */
430 function onResize() { 464 function onResize() {
431 var clientHeight = document.documentElement.clientHeight; 465 // The Google page uses a fixed layout instead.
samarth 2013/04/15 19:01:34 Can we use the same basic layout for both modes, f
jeremycho 2013/04/16 01:42:37 That makes sense to me - will discuss on the bug t
432 topMarginElement.style.marginTop = 466 if (!isGooglePage) {
433 Math.max(0, (clientHeight - MOST_VISITED_HEIGHT) / 2) + 'px'; 467 var clientHeight = document.documentElement.clientHeight;
434 468 topMarginElement.style.marginTop =
469 Math.max(0, (clientHeight - MOST_VISITED_HEIGHT) / 2) + 'px';
470 }
435 var clientWidth = document.documentElement.clientWidth; 471 var clientWidth = document.documentElement.clientWidth;
436 var numTilesToShow = Math.floor( 472 var numTilesToShow = Math.floor(
437 (clientWidth - MIN_TOTAL_HORIZONTAL_PADDING) / TILE_WIDTH); 473 (clientWidth - MIN_TOTAL_HORIZONTAL_PADDING) / TILE_WIDTH);
438 numTilesToShow = Math.max(MIN_NUM_TILES_TO_SHOW, numTilesToShow); 474 numTilesToShow = Math.max(MIN_NUM_TILES_TO_SHOW, numTilesToShow);
439 if (numTilesToShow != numTilesShown) { 475 if (numTilesToShow != numTilesShown) {
440 updateTileVisibility(numTilesToShow); 476 updateTileVisibility(numTilesToShow);
441 numTilesShown = numTilesToShow; 477 numTilesShown = numTilesToShow;
442 } 478 }
443 } 479 }
444 480
(...skipping 16 matching lines...) Expand all
461 function getTileByRid(rid) { 497 function getTileByRid(rid) {
462 for (var i = 0, length = tiles.length; i < length; ++i) { 498 for (var i = 0, length = tiles.length; i < length; ++i) {
463 var tile = tiles[i]; 499 var tile = tiles[i];
464 if (tile.rid == rid) 500 if (tile.rid == rid)
465 return tile; 501 return tile;
466 } 502 }
467 return null; 503 return null;
468 } 504 }
469 505
470 /** 506 /**
507 * @param {boolean} show True to show the NTP.
samarth 2013/04/15 19:01:34 How about |visible| instead of |show|.
jeremycho 2013/04/16 01:42:37 Done.
508 */
509 function updateNtpVisibility(show) {
510 if (show && !isNtpVisible()) {
511 // Stop any fakebox animation animation in progress and restore the NTP.
512 fakebox.removeEventListener('webkitTransitionEnd', fakeboxAnimationDone);
513 document.body.classList.remove(CLASSES.FAKEBOX_ANIMATE);
514 $(IDS.NTP_CONTENTS).hidden = false;
515 onThemeChange();
516 } else if (!show && isNtpVisible()) {
517 if (isFakeboxFocused()) {
518 // The user has typed in the fakebox - initiate the fakebox animation,
519 // which upon termination will hide the NTP.
520 document.body.classList.remove(CLASSES.FAKEBOX_FOCUS);
521 // Don't show the suggestions until the animation termintes.
522 $(IDS.SUGGESTIONS_CONTAINER).hidden = true;
523 fakebox.addEventListener('webkitTransitionEnd', fakeboxAnimationDone);
524 document.body.classList.add(CLASSES.FAKEBOX_ANIMATE);
525 } else if (!document.body.classList.contains(CLASSES.FAKEBOX_ANIMATE)) {
526 // The user has typed in the omnibox - hide the NTP immediately.
527 $(IDS.NTP_CONTENTS).hidden = true;
528 clearCustomTheme();
529 }
530 }
531 }
532
533 /**
534 * Clears the custom theme (if any).
535 */
536 function clearCustomTheme() {
537 document.body.style.background = '';
538 document.body.classList.remove('custom-theme');
539 }
540
541 /**
542 * @return {boolean} True if the NTP is visible.
543 */
544 function isNtpVisible() {
545 return !$(IDS.NTP_CONTENTS).hidden;
546 }
547
548 /**
549 * @return {boolean} True if the fakebox has focus.
550 */
551 function isFakeboxFocused() {
552 return document.body.classList.contains(CLASSES.FAKEBOX_FOCUS);
553 }
554
555 /**
556 * @param {Event} event The click event.
557 * @return {boolean} True if the click occurred in the fakebox.
558 */
559 function isFakeboxClick(event) {
560 var element = event.target;
561 while (element) {
562 if (element == fakebox)
563 return true;
564 element = element.parentNode;
565 }
566 return false;
567 }
568
569 /**
570 * Cleans up the fakebox animation, hides the NTP, and shows suggestions.
571 */
572 function fakeboxAnimationDone() {
573 $(IDS.NTP_CONTENTS).hidden = true;
574 $(IDS.SUGGESTIONS_CONTAINER).hidden = false;
575 clearCustomTheme();
576 document.body.classList.remove(CLASSES.FAKEBOX_ANIMATE);
577 fakebox.removeEventListener('webkitTransitionEnd', fakeboxAnimationDone);
578 }
579
580 // =============================================================================
581 // Suggestion Implementation
samarth 2013/04/15 19:01:34 s/Suggestion/Dropdown/
jeremycho 2013/04/16 01:42:37 Done.
582 // =============================================================================
583
584 /**
585 * Possible behaviors for navigateContentWindow.
586 * @enum {number}
587 */
588 var WindowOpenDisposition = {
589 CURRENT_TAB: 1,
590 NEW_BACKGROUND_TAB: 2
591 };
592
593 /**
594 * The JavaScript button event value for a middle click.
595 * @type {number}
596 * @const
597 */
598 var MIDDLE_MOUSE_BUTTON = 1;
599
600 /**
601 * The maximum number of suggestions to show.
602 * @type {number}
603 * @const
604 */
605 var MAX_SUGGESTIONS_TO_SHOW = 5;
606
607 /**
608 * Assume any native suggestion with a score higher than this value has been
609 * inlined by the browser.
610 * @type {number}
611 * @const
612 */
613 var INLINE_SUGGESTION_THRESHOLD = 1200;
614
615 /**
616 * Suggestion provider type corresponding to a verbatim URL suggestion.
617 * @type {string}
618 * @const
619 */
620 var VERBATIM_URL_TYPE = 'url-what-you-typed';
621
622 /**
623 * Suggestion provider type corresponding to a verbatim search suggestion.
624 * @type {string}
625 * @const
626 */
627 var VERBATIM_SEARCH_TYPE = 'search-what-you-typed';
628
629 /**
630 * The omnibox input value during the last onnativesuggestions event.
631 * @type {string}
632 */
633 var lastInputValue = '';
634
635 /**
636 * The ordered restricted ids of the currently displayed suggestions. Since the
637 * suggestions contain the user's personal data (browser history) the searchBox
638 * API embeds the content of the suggestion in a shadow dom, and assigns a
639 * random restricted id to each suggestion which is accessible to the JS.
640 * @type {Array.<number>}
641 */
642
643 var restrictedIds = [];
644
645 /**
646 * The index of the currently selected suggestion or -1 if none are selected.
647 * @type {number}
648 */
649 var selectedIndex = -1;
650
651 /**
652 * The browser embeddedSearch.searchBox object.
653 * @type {Object}
654 */
655 var searchboxApiHandle;
656
657 /**
658 * Displays a suggestion.
659 * @param {Object} suggestion The suggestion to render.
660 * @param {HTMLElement} box The html element to add the suggestion to.
661 * @param {boolean} select True to select the selection.
662 */
663 function addSuggestionToBox(suggestion, box, select) {
664 var suggestionDiv = document.createElement('div');
665 suggestionDiv.classList.add('suggestion');
666 suggestionDiv.classList.toggle('selected', select);
667 suggestionDiv.classList.toggle('search', suggestion.is_search);
668
669 if (suggestion.destination_url) { // iframes.
670 var suggestionIframe = document.createElement('iframe');
671 suggestionIframe.className = 'contents';
672 suggestionIframe.src = suggestion.destination_url;
673 suggestionIframe.id = suggestion.rid;
674 suggestionDiv.appendChild(suggestionIframe);
675 } else {
676 var contentsContainer = document.createElement('div');
677 var contents = suggestion.combinedNode;
678 contents.classList.add('contents');
679 contentsContainer.appendChild(contents);
680 suggestionDiv.appendChild(contentsContainer);
681 suggestionDiv.onclick = function(event) {
682 handleSuggestionClick(suggestion.rid, event.button);
683 };
684 }
685
686 restrictedIds.push(suggestion.rid);
687 box.appendChild(suggestionDiv);
688 }
689
690 /**
691 * Renders the input suggestions.
692 * @param {Array} nativeSuggestions An array of native suggestions to render.
693 */
694 function renderSuggestions(nativeSuggestions) {
695 var box = document.createElement('div');
696 box.id = IDS.SUGGESTIONS_BOX;
697 $(IDS.SUGGESTIONS_CONTAINER).appendChild(box);
698
699 for (var i = 0, length = nativeSuggestions.length;
700 i < Math.min(MAX_SUGGESTIONS_TO_SHOW, length); ++i) {
701 // Don't add the search-what-you-typed suggestion if it's the top match.
702 if (i > 0 || nativeSuggestions[i].type != VERBATIM_SEARCH_TYPE)
703 addSuggestionToBox(nativeSuggestions[i], box, i == selectedIndex);
704 }
705 }
706
707 /**
708 * Clears the suggestions being displayed.
709 */
710 function clearSuggestions() {
711 $(IDS.SUGGESTIONS_CONTAINER).innerHTML = '';
712 restrictedIds = [];
713 selectedIndex = -1;
714 }
715
716 /**
717 * @return {number} The height of the dropdown.
718 */
719 function getDropdownHeight() {
720 return $(IDS.SUGGESTIONS_CONTAINER).offsetHeight;
721 }
722
723 /**
724 * @param {Object} suggestion A suggestion.
725 * @param {boolean} inVerbatimMode Are we in verbatim mode?
726 * @return {boolean} True if the suggestion should be selected.
727 */
728 function shouldSelectSuggestion(suggestion, inVerbatimMode) {
729 var isVerbatimUrl = suggestion.type == VERBATIM_URL_TYPE;
730 var inlinableSuggestion = suggestion.type != VERBATIM_SEARCH_TYPE &&
731 suggestion.rankingData.relevance > INLINE_SUGGESTION_THRESHOLD;
732 // Verbatim URLs should always be selected. Otherwise, select suggestions
733 // with a high enough score unless we are in verbatim mode (e.g. backspacing
734 // away).
735 return isVerbatimUrl || (!inVerbatimMode && inlinableSuggestion);
736 }
737
738 /**
739 * Updates selectedIndex, bounding it between -1 and the total number of
740 * of suggestions - 1 (looping as necessary), and selects the corresponding
741 * suggestion.
742 * @param {boolean} increment True to increment the selected suggestion, false
743 * to decrement.
744 */
745 function updateSelectedSuggestion(increment) {
746 var numSuggestions = restrictedIds.length;
747 if (!numSuggestions)
748 return;
749
750 var oldSelection = $(IDS.SUGGESTIONS_BOX).querySelector('.selected');
751 if (oldSelection)
752 oldSelection.classList.remove('selected');
753
754 if (increment)
755 selectedIndex = ++selectedIndex > numSuggestions - 1 ? -1 : selectedIndex;
756 else
757 selectedIndex = --selectedIndex < -1 ? numSuggestions - 1 : selectedIndex;
758 if (selectedIndex == -1) {
759 searchboxApiHandle.setValue(lastInputValue);
760 } else {
761 var newSelection = $(IDS.SUGGESTIONS_BOX).querySelector(
762 '.suggestion:nth-of-type(' + (selectedIndex + 1) + ')');
763 newSelection.classList.add('selected');
764 searchboxApiHandle.setRestrictedValue(restrictedIds[selectedIndex]);
765 }
766 }
767
768 /**
769 * Updates suggestions in response to a onchange or onnativesuggestions call.
770 */
771 function updateSuggestions() {
772 appendSuggestionStyles();
773 lastInputValue = searchboxApiHandle.value;
774
775 // Hide the NTP if input has made it into the omnibox.
776 var show = lastInputValue == '';
777 updateNtpVisibility(show);
778
779 clearSuggestions();
780 if (show)
781 return;
782
783 var nativeSuggestions = searchboxApiHandle.nativeSuggestions;
784 if (nativeSuggestions.length) {
785 nativeSuggestions.sort(function(a, b) {
786 return b.rankingData.relevance - a.rankingData.relevance;
787 });
788 if (shouldSelectSuggestion(
789 nativeSuggestions[0], searchboxApiHandle.verbatim))
790 selectedIndex = 0;
791 renderSuggestions(nativeSuggestions);
792 }
793
794 var height = getDropdownHeight();
795 searchboxApiHandle.showOverlay(height);
796 }
797
798 /**
799 * Appends a style node for suggestion properties that depend on apiHandle.
800 */
801 function appendSuggestionStyles() {
802 if ($('suggestionStyle'))
803 return;
804
805 var isRtl = searchboxApiHandle.rtl;
806 var startMargin = searchboxApiHandle.startMargin;
807 var style = document.createElement('style');
808 style.type = 'text/css';
809 style.id = 'suggestionStyle';
810 style.textContent =
811 '.suggestion, ' +
812 '.suggestion.search {' +
813 ' background-position: ' +
814 (isRtl ? '-webkit-calc(100% - 5px)' : '5px') + ' 4px;' +
815 ' -webkit-margin-start: ' + startMargin + 'px;' +
816 ' -webkit-margin-end: ' +
817 (window.innerWidth - searchboxApiHandle.width - startMargin) + 'px;' +
818 ' font: ' + searchboxApiHandle.fontSize + 'px "' +
819 searchboxApiHandle.font + '";' +
820 '}';
821 document.querySelector('head').appendChild(style);
822 }
823
824 /**
825 * Extract the desired navigation behavior from a click button.
826 * @param {number} button The Event#button property of a click event.
827 * @return {WindowOpenDisposition} The desired behavior for
828 * navigateContentWindow.
829 */
830 function getDispositionFromClickButton(button) {
831 if (button == MIDDLE_MOUSE_BUTTON)
832 return WindowOpenDisposition.NEW_BACKGROUND_TAB;
833 return WindowOpenDisposition.CURRENT_TAB;
834 }
835
836 /**
837 * Handles suggestion clicks.
838 * @param {number} restrictedId The restricted id of the suggestion being
839 * clicked.
840 * @param {number} button The Event#button property of a click event.
841 *
842 */
843 function handleSuggestionClick(restrictedId, button) {
844 clearSuggestions();
845 searchboxApiHandle.navigateContentWindow(
846 restrictedId, getDispositionFromClickButton(button));
847 }
848
849 /**
850 * chrome.searchBox.onkeypress implementation.
851 * @param {Object} e The key being pressed.
852 */
853 function handleKeyPress(e) {
854 switch (e.keyCode) {
855 case 38: // Up arrow
856 updateSelectedSuggestion(false);
857 break;
858 case 40: // Down arrow
859 updateSelectedSuggestion(true);
860 break;
861 }
862 }
863
864 /**
865 * Handles the postMessage calls from the result iframes.
866 * @param {Object} message The message containing details of clicks the iframes.
867 */
868 function handleMessage(message) {
869 if (message.origin != 'null' || !message.data ||
870 message.data.eventType != 'click') {
871 return;
872 }
873
874 var iframes = document.getElementsByClassName('contents');
875 for (var i = 0; i < iframes.length; ++i) {
876 if (iframes[i].contentWindow == message.source) {
877 handleSuggestionClick(parseInt(iframes[i].id, 10),
878 message.data.button);
879 break;
880 }
881 }
882 }
883
884 // =============================================================================
885 // Utils
886 // =============================================================================
887
888 /**
889 * Shortcut for document.getElementById.
890 * @param {string} id of the element.
891 * @return {HTMLElement} with the id.
892 */
893 function $(id) {
894 return document.getElementById(id);
895 }
896
897 /**
471 * Utility function which creates an element with an optional classname and 898 * Utility function which creates an element with an optional classname and
472 * appends it to the specified parent. 899 * appends it to the specified parent.
473 * @param {Element} parent The parent to append the new element. 900 * @param {Element} parent The parent to append the new element.
474 * @param {string} name The name of the new element. 901 * @param {string} name The name of the new element.
475 * @param {string=} opt_class The optional classname of the new element. 902 * @param {string=} opt_class The optional classname of the new element.
476 * @return {Element} The new element. 903 * @return {Element} The new element.
477 */ 904 */
478 function createAndAppendElement(parent, name, opt_class) { 905 function createAndAppendElement(parent, name, opt_class) {
479 var child = document.createElement(name); 906 var child = document.createElement(name);
480 if (opt_class) 907 if (opt_class)
(...skipping 22 matching lines...) Expand all
503 * @return {Object} the handle to the embeddedSearch API. 930 * @return {Object} the handle to the embeddedSearch API.
504 */ 931 */
505 function getEmbeddedSearchApiHandle() { 932 function getEmbeddedSearchApiHandle() {
506 if (window.cideb) 933 if (window.cideb)
507 return window.cideb; 934 return window.cideb;
508 if (window.chrome && window.chrome.embeddedSearch) 935 if (window.chrome && window.chrome.embeddedSearch)
509 return window.chrome.embeddedSearch; 936 return window.chrome.embeddedSearch;
510 return null; 937 return null;
511 } 938 }
512 939
940 // =============================================================================
941 // Initialization
942 // =============================================================================
943
513 /** 944 /**
514 * Prepares the New Tab Page by adding listeners, rendering the current 945 * Prepares the New Tab Page by adding listeners, rendering the current
515 * theme, and the most visited pages section. 946 * theme, and the most visited pages section.
516 */ 947 */
517 function init() { 948 function init() {
518 topMarginElement = document.getElementById(IDS.TOP_MARGIN); 949 if (isGooglePage)
519 tilesContainer = document.getElementById(IDS.TILES); 950 document.body.classList.add(CLASSES.GOOGLE_PAGE);
520 notification = document.getElementById(IDS.NOTIFICATION); 951
521 attribution = document.getElementById(IDS.ATTRIBUTION); 952 topMarginElement = $(IDS.TOP_MARGIN);
953 tilesContainer = $(IDS.TILES);
954 notification = $(IDS.NOTIFICATION);
955 attribution = $(IDS.ATTRIBUTION);
956 fakebox = $(IDS.FAKEBOX);
522 957
523 // TODO(jeremycho): i18n. 958 // TODO(jeremycho): i18n.
524 var notificationMessage = document.getElementById(IDS.NOTIFICATION_MESSAGE); 959 var notificationMessage = $(IDS.NOTIFICATION_MESSAGE);
525 notificationMessage.innerText = 'Thumbnail removed.'; 960 notificationMessage.innerText = 'Thumbnail removed.';
526 var undoLink = document.getElementById(IDS.UNDO_LINK); 961 var undoLink = $(IDS.UNDO_LINK);
527 undoLink.addEventListener('click', onUndo); 962 undoLink.addEventListener('click', onUndo);
528 undoLink.innerText = 'Undo'; 963 undoLink.innerText = 'Undo';
529 var restoreAllLink = document.getElementById(IDS.RESTORE_ALL_LINK); 964 var restoreAllLink = $(IDS.RESTORE_ALL_LINK);
530 restoreAllLink.addEventListener('click', onRestoreAll); 965 restoreAllLink.addEventListener('click', onRestoreAll);
531 restoreAllLink.innerText = 'Restore all'; 966 restoreAllLink.innerText = 'Restore all';
532 attribution.innerText = 'Theme created by'; 967 attribution.innerText = 'Theme created by';
533 968
534 var notificationCloseButton = 969 var notificationCloseButton = $(IDS.NOTIFICATION_CLOSE_BUTTON);
535 document.getElementById(IDS.NOTIFICATION_CLOSE_BUTTON);
536 notificationCloseButton.addEventListener('click', hideNotification); 970 notificationCloseButton.addEventListener('click', hideNotification);
537 971
538 window.addEventListener('resize', onResize); 972 window.addEventListener('resize', onResize);
539 onResize(); 973 onResize();
540 974
541 var topLevelHandle = getEmbeddedSearchApiHandle(); 975 var topLevelHandle = getEmbeddedSearchApiHandle();
542 // This is to inform Chrome that the NTP is instant-extended capable i.e.
543 // it should fire events like onmostvisitedchange.
544 topLevelHandle.searchBox.onsubmit = function() {};
545 976
546 apiHandle = topLevelHandle.newTabPage; 977 ntpApiHandle = topLevelHandle.newTabPage;
547 apiHandle.onthemechange = onThemeChange; 978 ntpApiHandle.onthemechange = onThemeChange;
548 apiHandle.onmostvisitedchange = onMostVisitedChange; 979 ntpApiHandle.onmostvisitedchange = onMostVisitedChange;
549 980
550 onThemeChange(); 981 onThemeChange();
551 onMostVisitedChange(); 982 onMostVisitedChange();
983
984 searchboxApiHandle = topLevelHandle.searchBox;
985 searchboxApiHandle.onnativesuggestions = updateSuggestions;
986 searchboxApiHandle.onchange = updateSuggestions;
987 searchboxApiHandle.onkeypress = handleKeyPress;
988 searchboxApiHandle.onsubmit = function() {
989 var value = searchboxApiHandle.value;
990 if (!value) {
991 // Interpret onsubmit with an empty query as an ESC key press.
992 clearSuggestions();
993 updateNtpVisibility(true);
994 }
995 };
996
997 $(IDS.SUGGESTIONS_CONTAINER).dir = searchboxApiHandle.rtl ? 'rtl' : 'ltr';
998 if (searchboxApiHandle.nativeSuggestions.length)
999 updateSuggestions();
1000
1001 if (!document.webkitHidden)
1002 window.addEventListener('resize', addDelayedTransitions);
1003 else
1004 document.addEventListener('webkitvisibilitychange', addDelayedTransitions);
1005
1006
1007 if (isGooglePage) {
samarth 2013/04/15 19:01:34 More robust to check for the existence of the fake
jeremycho 2013/04/16 01:42:37 Done.
1008 // Listener for updating the fakebox focus.
1009 document.body.onclick = function(event) {
1010 if (isFakeboxClick(event)) {
1011 document.body.classList.add(CLASSES.FAKEBOX_FOCUS);
1012 searchboxApiHandle.startCapturingKeyStrokes();
1013 } else {
1014 document.body.classList.remove(CLASSES.FAKEBOX_FOCUS);
1015 searchboxApiHandle.stopCapturingKeyStrokes();
1016 }
1017 };
1018
1019 // Set the cursor alignment based on language directionality.
1020 $(IDS.CURSOR).style[searchboxApiHandle.rtl ? 'right' : 'left'] = '9px';
1021 }
1022 }
1023
1024 /**
1025 * Applies webkit transitions to NTP elements which need to be delayed until
1026 * after the page is made visible and any initial resize has occurred. This is
1027 * to prevent animations from triggering when the NTP is shown.
1028 */
1029 function addDelayedTransitions() {
1030 fakebox.style.webkitTransition =
1031 '-webkit-transform 100ms linear, width 200ms ease';
1032 tilesContainer.style.webkitTransition = 'width 200ms';
1033 window.removeEventListener(
samarth 2013/04/15 19:01:34 nit: fits one line?
jeremycho 2013/04/16 01:42:37 Done.
1034 'resize', addDelayedTransitions);
1035 document.removeEventListener(
1036 'webkitvisibilitychange', addDelayedTransitions);
552 } 1037 }
553 1038
554 document.addEventListener('DOMContentLoaded', init); 1039 document.addEventListener('DOMContentLoaded', init);
1040 window.addEventListener('message', handleMessage, false);
555 })(); 1041 })();
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698