Give names to all utility processes.
[chromium-blink-merge.git] / chrome / browser / resources / local_ntp / most_visited_single.js
blob8590dca1fa174462c9bcac6e96c8ec4492db88e3
1 /* Copyright 2015 The Chromium Authors. All rights reserved.
2 * Use of this source code is governed by a BSD-style license that can be
3 * found in the LICENSE file. */
5 // Single iframe for NTP tiles.
6 (function() {
7 'use strict';
10 /**
11 * The different types of events that are logged from the NTP. This enum is
12 * used to transfer information from the NTP JavaScript to the renderer and is
13 * not used as a UMA enum histogram's logged value.
14 * Note: Keep in sync with common/ntp_logging_events.h
15 * @enum {number}
16 * @const
18 var LOG_TYPE = {
19 // The suggestion is coming from the server. Unused here.
20 NTP_SERVER_SIDE_SUGGESTION: 0,
21 // The suggestion is coming from the client.
22 NTP_CLIENT_SIDE_SUGGESTION: 1,
23 // Indicates a tile was rendered, no matter if it's a thumbnail, a gray tile
24 // or an external tile.
25 NTP_TILE: 2,
26 // The tile uses a local thumbnail image.
27 NTP_THUMBNAIL_TILE: 3,
28 // Used when no thumbnail is specified and a gray tile with the domain is used
29 // as the main tile. Unused here.
30 NTP_GRAY_TILE: 4,
31 // The visuals of that tile are handled externally by the page itself.
32 // Unused here.
33 NTP_EXTERNAL_TILE: 5,
34 // There was an error in loading both the thumbnail image and the fallback
35 // (if it was provided), resulting in a gray tile.
36 NTP_THUMBNAIL_ERROR: 6,
37 // Used a gray tile with the domain as the fallback for a failed thumbnail.
38 // Unused here.
39 NTP_GRAY_TILE_FALLBACK: 7,
40 // The visuals of that tile's fallback are handled externally. Unused here.
41 NTP_EXTERNAL_TILE_FALLBACK: 8,
42 // The user moused over an NTP tile.
43 NTP_MOUSEOVER: 9,
44 // A NTP Tile has finished loading (successfully or failing).
45 NTP_TILE_LOADED: 10,
49 /**
50 * Total number of tiles to show at any time. If the host page doesn't send
51 * enough tiles, we fill them blank.
52 * @const {number}
54 var NUMBER_OF_TILES = 8;
57 /**
58 * Whether to use icons instead of thumbnails.
59 * @type {boolean}
61 var USE_ICONS = false;
64 /**
65 * Number of lines to display in titles.
66 * @type {number}
68 var NUM_TITLE_LINES = 1;
71 /**
72 * The origin of this request.
73 * @const {string}
75 var DOMAIN_ORIGIN = '{{ORIGIN}}';
78 /**
79 * Counter for DOM elements that we are waiting to finish loading.
80 * @type {number}
82 var loadedCounter = 1;
85 /**
86 * DOM element containing the tiles we are going to present next.
87 * Works as a double-buffer that is shown when we receive a "show" postMessage.
88 * @type {Element}
90 var tiles = null;
93 /**
94 * List of parameters passed by query args.
95 * @type {Object}
97 var queryArgs = {};
101 * Log an event on the NTP.
102 * @param {number} eventType Event from LOG_TYPE.
104 var logEvent = function(eventType) {
105 chrome.embeddedSearch.newTabPage.logEvent(eventType);
110 * Down counts the DOM elements that we are waiting for the page to load.
111 * When we get to 0, we send a message to the parent window.
112 * This is usually used as an EventListener of onload/onerror.
114 var countLoad = function() {
115 loadedCounter -= 1;
116 if (loadedCounter <= 0) {
117 logEvent(LOG_TYPE.NTP_TILE_LOADED);
118 window.parent.postMessage({cmd: 'loaded'}, DOMAIN_ORIGIN);
119 loadedCounter = 1;
125 * Handles postMessages coming from the host page to the iframe.
126 * Mostly, it dispatches every command to handleCommand.
128 var handlePostMessage = function(event) {
129 if (event.data instanceof Array) {
130 for (var i = 0; i < event.data.length; ++i) {
131 handleCommand(event.data[i]);
133 } else {
134 handleCommand(event.data);
140 * Handles a single command coming from the host page to the iframe.
141 * We try to keep the logic here to a minimum and just dispatch to the relevant
142 * functions.
144 var handleCommand = function(data) {
145 var cmd = data.cmd;
147 if (cmd == 'tile') {
148 addTile(data);
149 } else if (cmd == 'show') {
150 showTiles();
151 hideOverflowTiles(data);
152 countLoad();
153 } else if (cmd == 'updateTheme') {
154 updateTheme(data);
155 } else if (cmd == 'tilesVisible') {
156 hideOverflowTiles(data);
157 } else {
158 console.error('Unknown command: ' + JSON.stringify(data));
163 var updateTheme = function(info) {
164 var themeStyle = [];
166 if (info.tileBorderColor) {
167 themeStyle.push('.thumb-ntp .mv-tile {' +
168 'border: 1px solid ' + info.tileBorderColor + '; }');
170 if (info.tileHoverBorderColor) {
171 themeStyle.push('.thumb-ntp .mv-tile:hover {' +
172 'border-color: ' + info.tileHoverBorderColor + '; }');
174 if (info.isThemeDark) {
175 themeStyle.push('.thumb-ntp .mv-tile, .thumb-ntp .mv-empty-tile { ' +
176 'background: rgb(51,51,51); }');
177 themeStyle.push('.thumb-ntp .mv-thumb.failed-img { ' +
178 'background-color: #555; }');
179 themeStyle.push('.thumb-ntp .mv-thumb.failed-img::after { ' +
180 'border-color: #333; }');
181 themeStyle.push('.thumb-ntp .mv-x { ' +
182 'background: linear-gradient(to left, ' +
183 'rgb(51,51,51) 60%, transparent); }');
184 themeStyle.push('html[dir=rtl] .thumb-ntp .mv-x { ' +
185 'background: linear-gradient(to right, ' +
186 'rgb(51,51,51) 60%, transparent); }');
187 themeStyle.push('.thumb-ntp .mv-x::after { ' +
188 'background-color: rgba(255,255,255,0.7); }');
189 themeStyle.push('.thumb-ntp .mv-x:hover::after { ' +
190 'background-color: #fff; }');
191 themeStyle.push('.thumb-ntp .mv-x:active::after { ' +
192 'background-color: rgba(255,255,255,0.5); }');
193 themeStyle.push('.icon-ntp .mv-tile:focus { ' +
194 'background: rgba(255,255,255,0.2); }');
196 if (info.tileTitleColor) {
197 themeStyle.push('body { color: ' + info.tileTitleColor + '; }');
200 document.querySelector('#custom-theme').textContent = themeStyle.join('\n');
205 * Hides extra tiles that don't fit on screen.
207 var hideOverflowTiles = function(data) {
208 var tileAndEmptyTileList = document.querySelectorAll(
209 '#mv-tiles .mv-tile,#mv-tiles .mv-empty-tile');
210 for (var i = 0; i < tileAndEmptyTileList.length; ++i) {
211 tileAndEmptyTileList[i].classList.toggle('hidden', i >= data.maxVisible);
217 * Removes all old instances of #mv-tiles that are pending for deletion.
219 var removeAllOldTiles = function() {
220 var parent = document.querySelector('#most-visited');
221 var oldList = parent.querySelectorAll('.mv-tiles-old');
222 for (var i = 0; i < oldList.length; ++i) {
223 parent.removeChild(oldList[i]);
229 * Called when the host page has finished sending us tile information and
230 * we are ready to show the new tiles and drop the old ones.
232 var showTiles = function() {
233 removeAllOldTiles();
235 // Store the tiles on the current closure.
236 var cur = tiles;
238 // Create empty tiles until we have NUMBER_OF_TILES.
239 while (cur.childNodes.length < NUMBER_OF_TILES) {
240 addTile({});
243 var parent = document.querySelector('#most-visited');
245 // Mark old tile DIV for removal after the transition animation is done.
246 var old = parent.querySelector('#mv-tiles');
247 if (old) {
248 old.removeAttribute('id');
249 old.classList.add('mv-tiles-old');
250 cur.addEventListener('webkitTransitionEnd', function(ev) {
251 if (ev.target === cur) {
252 removeAllOldTiles();
257 // Add new tileset.
258 cur.id = 'mv-tiles';
259 parent.appendChild(cur);
260 // We want the CSS transition to trigger, so need to add to the DOM before
261 // setting the style.
262 setTimeout(function() {
263 cur.style.opacity = 1.0;
264 }, 0);
266 // Make sure the tiles variable contain the next tileset we may use.
267 tiles = document.createElement('div');
272 * Called when the host page wants to add a suggestion tile.
273 * For Most Visited, it grabs the data from Chrome and pass on.
274 * For host page generated it just passes the data.
275 * @param {object} args Data for the tile to be rendered.
277 var addTile = function(args) {
278 if (args.rid) {
279 var data = chrome.embeddedSearch.searchBox.getMostVisitedItemData(args.rid);
280 data.tid = data.rid;
281 data.faviconUrl = 'chrome-search://favicon/size/16@' +
282 window.devicePixelRatio + 'x/' + data.renderViewId + '/' + data.tid;
283 tiles.appendChild(renderTile(data));
284 logEvent(LOG_TYPE.NTP_CLIENT_SIDE_SUGGESTION);
285 } else if (args.id) {
286 tiles.appendChild(renderTile(args));
287 logEvent(LOG_TYPE.NTP_SERVER_SIDE_SUGGESTION);
288 } else {
289 tiles.appendChild(renderTile(null));
295 * Called when the user decided to add a tile to the blacklist.
296 * It sets of the animation for the blacklist and sends the blacklisted id
297 * to the host page.
298 * @param {Element} tile DOM node of the tile we want to remove.
300 var blacklistTile = function(tile) {
301 tile.classList.add('blacklisted');
302 tile.addEventListener('webkitTransitionEnd', function(ev) {
303 if (ev.propertyName != 'width') return;
305 window.parent.postMessage({cmd: 'tileBlacklisted',
306 tid: Number(tile.getAttribute('data-tid'))},
307 DOMAIN_ORIGIN);
313 * Renders a MostVisited tile to the DOM.
314 * @param {object} data Object containing rid, url, title, favicon, thumbnail.
315 * data is null if you want to construct an empty tile.
317 var renderTile = function(data) {
318 var tile = document.createElement('a');
320 if (data == null) {
321 tile.className = 'mv-empty-tile';
322 return tile;
325 logEvent(LOG_TYPE.NTP_TILE);
327 tile.className = 'mv-tile';
328 tile.setAttribute('data-tid', data.tid);
329 var tooltip = queryArgs['removeTooltip'] || '';
330 var html = [];
331 if (!USE_ICONS) {
332 html.push('<div class="mv-favicon"></div>');
334 html.push('<div class="mv-title"></div><div class="mv-thumb"></div>');
335 html.push('<div title="' + tooltip + '" class="mv-x"></div>');
336 tile.innerHTML = html.join('');
338 tile.href = data.url;
339 tile.title = data.title;
340 tile.addEventListener('keypress', function(ev) {
341 if (ev.keyCode == 127) { // DELETE
342 blacklistTile(tile);
343 ev.stopPropagation();
344 return false;
347 // TODO(fserb): remove this or at least change to mouseenter.
348 tile.addEventListener('mouseover', function() {
349 logEvent(LOG_TYPE.NTP_MOUSEOVER);
352 var title = tile.querySelector('.mv-title');
353 title.innerText = data.title;
354 title.style.direction = data.direction || 'ltr';
355 if (NUM_TITLE_LINES > 1) {
356 title.classList.add('multiline');
359 var hasIcon = USE_ICONS && data.largeIconUrl;
360 var hasThumb = !USE_ICONS && data.thumbnailUrl;
361 var thumb = tile.querySelector('.mv-thumb');
362 if (hasIcon || hasThumb) {
363 var img = document.createElement('img');
364 img.title = data.title;
365 if (hasIcon) {
366 img.src = data.largeIconUrl;
367 img.classList.add('large-icon');
368 } else { // hasThumb
369 img.src = data.thumbnailUrl;
370 img.classList.add('thumbnail');
372 loadedCounter += 1;
373 img.addEventListener('load', countLoad);
374 if (data.largeIconUrl) {
375 img.addEventListener('load', function(ev) {
376 thumb.classList.add('large-icon-outer');
379 img.addEventListener('error', countLoad);
380 img.addEventListener('error', function(ev) {
381 thumb.classList.add('failed-img');
382 thumb.removeChild(img);
383 logEvent(LOG_TYPE.NTP_THUMBNAIL_ERROR);
385 thumb.appendChild(img);
386 logEvent(LOG_TYPE.NTP_THUMBNAIL_TILE);
387 } else {
388 thumb.classList.add('failed-img');
391 if (!USE_ICONS) {
392 var favicon = tile.querySelector('.mv-favicon');
393 if (data.faviconUrl) {
394 var fi = document.createElement('img');
395 fi.src = data.faviconUrl;
396 // Set the title to empty so screen readers won't say the image name.
397 fi.title = '';
398 loadedCounter += 1;
399 fi.addEventListener('load', countLoad);
400 fi.addEventListener('error', countLoad);
401 fi.addEventListener('error', function(ev) {
402 favicon.classList.add('failed-favicon');
404 favicon.appendChild(fi);
405 } else {
406 favicon.classList.add('failed-favicon');
410 var mvx = tile.querySelector('.mv-x');
411 mvx.addEventListener('click', function(ev) {
412 removeAllOldTiles();
413 blacklistTile(tile);
414 ev.preventDefault();
415 ev.stopPropagation();
418 return tile;
423 * Do some initialization and parses the query arguments passed to the iframe.
425 var init = function() {
426 // Creates a new DOM element to hold the tiles.
427 tiles = document.createElement('div');
429 // Parse query arguments.
430 var query = window.location.search.substring(1).split('&');
431 queryArgs = {};
432 for (var i = 0; i < query.length; ++i) {
433 var val = query[i].split('=');
434 if (val[0] == '') continue;
435 queryArgs[decodeURIComponent(val[0])] = decodeURIComponent(val[1]);
438 // Apply class for icon NTP, if specified.
439 USE_ICONS = queryArgs['icons'] == '1';
440 if ('ntl' in queryArgs) {
441 var ntl = parseInt(queryArgs['ntl'], 10);
442 if (isFinite(ntl))
443 NUM_TITLE_LINES = ntl;
446 // Duplicating NTP_DESIGN.mainClass.
447 document.querySelector('#most-visited').classList.add(
448 USE_ICONS ? 'icon-ntp' : 'thumb-ntp');
450 // Enable RTL.
451 if (queryArgs['rtl'] == '1') {
452 var html = document.querySelector('html');
453 html.dir = 'rtl';
456 window.addEventListener('message', handlePostMessage);
460 window.addEventListener('DOMContentLoaded', init);
461 })();