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

Side by Side Diff: chrome/browser/resources/ntp_search/thumbnail_page.js

Issue 10829131: Refactoring NTP5: new implementation of TilePage and MostVisitedPage (which now inherits from Thumb… (Closed) Base URL: http://git.chromium.org/chromium/src.git@master
Patch Set: Fixing error during initialization Created 8 years, 4 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 (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 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 cr.define('ntp', function() { 5 cr.define('ntp', function() {
6 'use strict'; 6 'use strict';
7 7
8 var TilePage = ntp.TilePage; 8 var Tile = ntp.Tile2;
9 var TilePage = ntp.TilePage2;
9 10
10 /** 11 /**
11 * A counter for generating unique tile IDs. 12 * A counter for generating unique tile IDs.
12 */ 13 */
13 var tileID = 0; 14 var tileID = 0;
14 15
15 /** 16 /**
16 * Creates a new Most Visited object for tiling. 17 * Creates a new Thumbnail object for tiling.
17 * @constructor 18 * @constructor
19 * @extends {Tile}
18 * @extends {HTMLAnchorElement} 20 * @extends {HTMLAnchorElement}
21 * @param {Object} gridValues Tile page configuration object.
19 */ 22 */
20 function MostVisited() { 23 function Thumbnail(gridValues) {
21 var el = cr.doc.createElement('a'); 24 var el = cr.doc.createElement('a');
22 el.__proto__ = MostVisited.prototype; 25 el.__proto__ = Thumbnail.prototype;
23 el.initialize(); 26 el.initialize(gridValues);
24 27
25 return el; 28 return el;
26 } 29 }
27 30
28 MostVisited.prototype = { 31 Thumbnail.prototype = Tile.subclass({
29 __proto__: HTMLAnchorElement.prototype, 32 __proto__: HTMLAnchorElement.prototype,
30 33
31 initialize: function() { 34 // TODO(pedrosimonetti): remove this property here. move to most visited.
35 isRemovable: true,
36
37 initialize: function(gridValues) {
38 Tile.prototype.initialize.apply(this, arguments);
32 this.reset(); 39 this.reset();
33
34 this.addEventListener('click', this.handleClick_);
35 this.addEventListener('keydown', this.handleKeyDown_);
36 },
37
38 get index() {
39 assert(this.tile);
40 return this.tile.index;
41 }, 40 },
42 41
43 get data() { 42 get data() {
44 return this.data_; 43 return this.data_;
45 }, 44 },
46 45
47 /** 46 /**
48 * Clears the DOM hierarchy for this node, setting it back to the default 47 * Clears the DOM hierarchy for this node, setting it back to the default
49 * for a blank thumbnail. 48 * for a blank thumbnail.
50 */ 49 */
51 reset: function() { 50 reset: function() {
52 this.className = 'most-visited filler real'; 51 this.className = this.baseClassName;
53 this.innerHTML = 52 this.innerHTML =
54 '<span class="thumbnail-wrapper fills-parent">' + 53 '<span class="thumbnail-wrapper">' +
55 '<div class="close-button"></div>' + 54 (this.isRemovable ? '<div class="close-button"></div>' : '') +
56 '<span class="thumbnail fills-parent">' + 55 '<span class="thumbnail-image">' +
57 // thumbnail-shield provides a gradient fade effect.
58 '<div class="thumbnail-shield fills-parent"></div>' +
59 '</span>' + 56 '</span>' +
60 '<span class="favicon"></span>' +
61 '</span>' + 57 '</span>' +
62 '<div class="color-stripe"></div>' +
63 '<span class="title"></span>'; 58 '<span class="title"></span>';
64 59
65 this.querySelector('.close-button').title = 60 if (this.isRemovable) {
66 loadTimeData.getString('removethumbnailtooltip'); 61 this.querySelector('.close-button').title =
62 loadTimeData.getString('removethumbnailtooltip');
63 }
67 64
68 this.tabIndex = -1; 65 this.tabIndex = -1;
69 this.data_ = null; 66 this.data_ = null;
70 this.removeAttribute('id'); 67 this.removeAttribute('id');
71 this.title = ''; 68 this.title = '';
72 }, 69 },
73 70
74 /** 71 /**
75 * Update the appearance of this tile according to |data|. 72 * Update the appearance of this tile according to |data|.
76 * @param {Object} data A dictionary of relevant data for the page. 73 * @param {Object} data A dictionary of relevant data for the page.
77 */ 74 */
78 updateForData: function(data) { 75 updateForData: function(data) {
79 if (this.classList.contains('blacklisted') && data) { 76 if (this.classList.contains('blacklisted') && data) {
80 // Animate appearance of new tile. 77 // Animate appearance of new tile.
81 this.classList.add('new-tile-contents'); 78 this.classList.add('new-tile-contents');
82 } 79 }
83 this.classList.remove('blacklisted'); 80 this.classList.remove('blacklisted');
84 81
85 if (!data || data.filler) { 82 if (!data || data.filler) {
86 if (this.data_) 83 if (this.data_)
87 this.reset(); 84 this.reset();
88 return; 85 return;
89 } 86 }
90 87
91 var id = tileID++; 88 var id = tileID++;
89 // TODO(pedrosimonetti): refactor
92 this.id = 'most-visited-tile-' + id; 90 this.id = 'most-visited-tile-' + id;
93 this.data_ = data; 91 this.data_ = data;
94 this.classList.add('focusable'); 92 this.classList.add('focusable');
95 93
96 var faviconDiv = this.querySelector('.favicon');
97 var faviconUrl = 'chrome://favicon/size/16/' + data.url;
98 faviconDiv.style.backgroundImage = url(faviconUrl);
99 chrome.send('getFaviconDominantColor', [faviconUrl, this.id]);
100
101 var title = this.querySelector('.title'); 94 var title = this.querySelector('.title');
102 title.textContent = data.title; 95 title.textContent = data.title;
103 title.dir = data.direction; 96 title.dir = data.direction;
104 97
105 // Sets the tooltip. 98 // Sets the tooltip.
106 this.title = data.title; 99 this.title = data.title;
107 100
108 var thumbnailUrl = 'chrome://thumb/' + data.url; 101 var thumbnailUrl = ntp.getThumbnailUrl(data.url);
109 this.querySelector('.thumbnail').style.backgroundImage = 102 this.querySelector('.thumbnail-image').style.backgroundImage =
110 url(thumbnailUrl); 103 url(thumbnailUrl);
111 104
112 this.href = data.url; 105 this.href = data.url;
113 106
114 this.classList.remove('filler'); 107 this.classList.remove('filler');
115 }, 108 },
116 109
117 /** 110 /**
118 * Sets the color of the favicon dominant color bar.
119 * @param {string} color The css-parsable value for the color.
120 */
121 set stripeColor(color) {
122 this.querySelector('.color-stripe').style.backgroundColor = color;
123 },
124
125 /**
126 * Handles a click on the tile.
127 * @param {Event} e The click event.
128 */
129 handleClick_: function(e) {
130 if (e.target.classList.contains('close-button')) {
131 this.blacklist_();
132 e.preventDefault();
133 } else {
134 // Records an app launch from the most visited page (Chrome will decide
135 // whether the url is an app). TODO(estade): this only works for clicks;
136 // other actions like "open in new tab" from the context menu won't be
137 // recorded. Can this be fixed?
138 chrome.send('recordAppLaunchByURL',
139 [encodeURIComponent(this.href),
140 ntp.APP_LAUNCH.NTP_MOST_VISITED]);
141 // Records the index of this tile.
142 chrome.send('metricsHandler:recordInHistogram',
143 ['NewTabPage.MostVisited', this.index, 8]);
144 chrome.send('mostVisitedAction',
145 [ntp.NtpFollowAction.CLICKED_TILE]);
146 }
147 },
148
149 /**
150 * Allow blacklisting most visited site using the keyboard.
151 */
152 handleKeyDown_: function(e) {
153 if (!cr.isMac && e.keyCode == 46 || // Del
154 cr.isMac && e.metaKey && e.keyCode == 8) { // Cmd + Backspace
155 this.blacklist_();
156 }
157 },
158
159 /**
160 * Permanently removes a page from Most Visited.
161 */
162 blacklist_: function() {
163 this.showUndoNotification_();
164 chrome.send('blacklistURLFromMostVisited', [this.data_.url]);
165 this.reset();
166 chrome.send('getMostVisited');
167 this.classList.add('blacklisted');
168 },
169
170 showUndoNotification_: function() {
171 var data = this.data_;
172 var self = this;
173 var doUndo = function() {
174 chrome.send('removeURLsFromMostVisitedBlacklist', [data.url]);
175 self.updateForData(data);
176 }
177
178 var undo = {
179 action: doUndo,
180 text: loadTimeData.getString('undothumbnailremove'),
181 };
182
183 var undoAll = {
184 action: function() {
185 chrome.send('clearMostVisitedURLsBlacklist');
186 },
187 text: loadTimeData.getString('restoreThumbnailsShort'),
188 };
189
190 ntp.showNotification(
191 loadTimeData.getString('thumbnailremovednotification'),
192 [undo, undoAll]);
193 },
194
195 /**
196 * Set the size and position of the most visited tile.
197 * @param {number} size The total size of |this|.
198 * @param {number} x The x-position.
199 * @param {number} y The y-position.
200 * animate.
201 */
202 setBounds: function(size, x, y) {
203 this.style.width = toCssPx(size);
204 this.style.height = toCssPx(heightForWidth(size));
205
206 this.style.left = toCssPx(x);
207 this.style.right = toCssPx(x);
208 this.style.top = toCssPx(y);
209 },
210
211 /**
212 * Returns whether this element can be 'removed' from chrome (i.e. whether
213 * the user can drag it onto the trash and expect something to happen).
214 * @return {boolean} True, since most visited pages can always be
215 * blacklisted.
216 */
217 canBeRemoved: function() {
218 return true;
219 },
220
221 /**
222 * Removes this element from chrome, i.e. blacklists it. 111 * Removes this element from chrome, i.e. blacklists it.
223 */ 112 */
113 // TODO(xci): delete? this seems to be used only by trash.
224 removeFromChrome: function() { 114 removeFromChrome: function() {
225 this.blacklist_(); 115 this.blacklist_();
226 this.parentNode.classList.add('finishing-drag'); 116 this.parentNode.classList.add('finishing-drag');
227 }, 117 },
228 118
229 /** 119 /**
230 * Called when a drag of this tile has ended (after all animations have 120 * Called when a drag of this tile has ended (after all animations have
231 * finished). 121 * finished).
232 */ 122 */
233 finalizeDrag: function() { 123 finalizeDrag: function() {
234 this.parentNode.classList.remove('finishing-drag'); 124 this.parentNode.classList.remove('finishing-drag');
235 }, 125 },
236 126
237 /** 127 /**
238 * Called when a drag is starting on the tile. Updates dataTransfer with 128 * Called when a drag is starting on the tile. Updates dataTransfer with
239 * data for this tile (for dragging outside of the NTP). 129 * data for this tile (for dragging outside of the NTP).
240 */ 130 */
131 // TODO(xci) delete
241 setDragData: function(dataTransfer) { 132 setDragData: function(dataTransfer) {
242 dataTransfer.setData('Text', this.data_.title); 133 dataTransfer.setData('Text', this.data_.title);
243 dataTransfer.setData('URL', this.data_.url); 134 dataTransfer.setData('URL', this.data_.url);
244 }, 135 },
245 }; 136 });
246 137
247 var mostVisitedPageGridValues = { 138 var THUMBNAIL_COUNT = 10; // TODO(xci)
248 // The fewest tiles we will show in a row.
249 minColCount: 2,
250 // The most tiles we will show in a row.
251 maxColCount: 4,
252
253 // The smallest a tile can be.
254 minTileWidth: 122,
255 // The biggest a tile can be. 212 (max thumbnail width) + 2.
256 maxTileWidth: 214,
257
258 // The padding between tiles, as a fraction of the tile width.
259 tileSpacingFraction: 1 / 8,
260 };
261 TilePage.initGridValues(mostVisitedPageGridValues);
262 139
263 /** 140 /**
264 * Calculates the height for a Most Visited tile for a given width. The size 141 * Creates a new ThumbnailPage object.
265 * is based on the thumbnail, which should have a 212:132 ratio.
266 * @return {number} The height.
267 */
268 function heightForWidth(width) {
269 // The 2s are for borders, the 31 is for the title.
270 return (width - 2) * 132 / 212 + 2 + 31;
271 }
272
273 var THUMBNAIL_COUNT = 8;
274
275 /**
276 * Creates a new MostVisitedPage object.
277 * @constructor 142 * @constructor
278 * @extends {TilePage} 143 * @extends {TilePage}
279 */ 144 */
280 function MostVisitedPage() { 145 function ThumbnailPage() {
281 var el = new TilePage(mostVisitedPageGridValues); 146 var el = new TilePage();
282 el.__proto__ = MostVisitedPage.prototype; 147 el.__proto__ = ThumbnailPage.prototype;
283 el.initialize(); 148 el.initialize();
284 149
285 return el; 150 return el;
286 } 151 }
287 152
288 MostVisitedPage.prototype = { 153 ThumbnailPage.prototype = {
289 __proto__: TilePage.prototype, 154 __proto__: TilePage.prototype,
290 155
156 gridValues_: {
157 tileWidth: 130,
158 tileHeight: 78,
159 tileHorMargin: 18, // TODO margin with CSS. There's no margin in first col
160 tileVerMargin: 22,
161 tileBorderWidth: 1,
162 bottomPanelHorMargin: 100,
163
164 tileCount: 10, // debug
165 tileClassName: 'thumbnail',
166 // TODO(pedrosimonetti): why not always use JavaScript?
167 // If reinforceStyles is true, the sizes of TileCell and Tile will be
168 // changed with JavaScript everytime one of those objects is instantiated.
169 // If you want to use CSS to do that, you can set this value to false.
170 reinforceStyles: true,
171
172 // debug
173 slowFactor: 1,
174 debug: false
175 },
176
177 // TODO(pedrosimonetti): document
178 ThumbnailClass: Thumbnail,
179
291 initialize: function() { 180 initialize: function() {
292 this.classList.add('most-visited-page'); 181 this.classList.add('thumbnail-page');
293 this.data_ = null; 182 this.data_ = null;
294 this.mostVisitedTiles_ = this.getElementsByClassName('most-visited real');
295 183
296 this.addEventListener('carddeselected', this.handleCardDeselected_); 184 this.addEventListener('carddeselected', this.handleCardDeselected_);
297 this.addEventListener('cardselected', this.handleCardSelected_); 185 this.addEventListener('cardselected', this.handleCardSelected_);
298 }, 186 },
299 187
300 /** 188 /**
301 * Create blank (filler) tiles. 189 * Create blank (filler) tiles.
302 * @private 190 * @private
191 * @param {number} count The number of Tiles to be created.
303 */ 192 */
304 createTiles_: function() { 193 createTiles_: function(count) {
305 for (var i = 0; i < THUMBNAIL_COUNT; i++) { 194 for (var i = 0; i < count; i++) {
306 this.appendTile(new MostVisited()); 195 this.appendTile(new this.ThumbnailClass(this.gridValues_));
307 } 196 }
308 }, 197 },
309 198
310 /** 199 /**
311 * Update the tiles after a change to |data_|. 200 * Update the tiles after a change to |data_|.
312 */ 201 */
313 updateTiles_: function() { 202 updateTiles_: function() {
314 for (var i = 0; i < THUMBNAIL_COUNT; i++) { 203 for (var i = 0; i < THUMBNAIL_COUNT; i++) {
315 var page = this.data_[i]; 204 var page = this.data_[i];
316 var tile = this.mostVisitedTiles_[i]; 205 var tile = this.tileElements[i];
206
207 // TODO(pedrosimonetti): what do we do when there's no tile here?
208 if (!tile) {
209 return;
210 }
317 211
318 if (i >= this.data_.length) 212 if (i >= this.data_.length)
319 tile.reset(); 213 tile.reset();
320 else 214 else
321 tile.updateForData(page); 215 tile.updateForData(page);
322 } 216 }
323 }, 217 },
324 218
325 /** 219 /**
326 * Handles the 'card deselected' event (i.e. the user clicked to another 220 * Handles the 'card deselected' event (i.e. the user clicked to another
327 * pane). 221 * pane).
328 * @param {Event} e The CardChanged event. 222 * @param {Event} e The CardChanged event.
329 */ 223 */
330 handleCardDeselected_: function(e) { 224 handleCardDeselected_: function(e) {
331 if (!document.documentElement.classList.contains('starting-up')) { 225 if (!document.documentElement.classList.contains('starting-up')) {
226 // TODO(xci) logging
332 chrome.send('mostVisitedAction', 227 chrome.send('mostVisitedAction',
333 [ntp.NtpFollowAction.CLICKED_OTHER_NTP_PANE]); 228 [ntp.NtpFollowAction.CLICKED_OTHER_NTP_PANE]);
334 } 229 }
335 }, 230 },
336 231
337 /** 232 /**
338 * Handles the 'card selected' event (i.e. the user clicked to select the 233 * Handles the 'card selected' event (i.e. the user clicked to select the
339 * Most Visited pane). 234 * this page's pane).
340 * @param {Event} e The CardChanged event. 235 * @param {Event} e The CardChanged event.
341 */ 236 */
342 handleCardSelected_: function(e) { 237 handleCardSelected_: function(e) {
343 if (!document.documentElement.classList.contains('starting-up')) 238 if (!document.documentElement.classList.contains('starting-up'))
239 // TODO(xci) logging
344 chrome.send('mostVisitedSelected'); 240 chrome.send('mostVisitedSelected');
345 }, 241 },
346 242
347 /** 243 /**
348 * Array of most visited data objects. 244 * Array of thumbnail data objects.
349 * @type {Array} 245 * @type {Array}
350 */ 246 */
351 get data() { 247 get data() {
352 return this.data_; 248 return this.data_;
353 }, 249 },
250
354 set data(data) { 251 set data(data) {
355 var startTime = Date.now(); 252 throw 'Each ThumbnailPage subclass should implement the data setter.';
356
357 // The first time data is set, create the tiles.
358 if (!this.data_) {
359 this.createTiles_();
360 this.data_ = data.slice(0, THUMBNAIL_COUNT);
361 } else {
362 this.data_ = refreshData(this.data_, data);
363 }
364
365 this.updateTiles_();
366 logEvent('mostVisited.layout: ' + (Date.now() - startTime));
367 }, 253 },
368 254
369 /** @inheritDoc */ 255 /** @inheritDoc */
370 shouldAcceptDrag: function(e) { 256 shouldAcceptDrag: function(e) {
371 return false; 257 return false;
372 }, 258 },
373
374 /** @inheritDoc */
375 heightForWidth: heightForWidth,
376 }; 259 };
377 260
378 /** 261 /**
379 * Executed once the NTP has loaded. Checks if the Most Visited pane is 262 * Executed once the NTP has loaded. Checks if the this page's pane is
380 * shown or not. If it is shown, the 'mostVisitedSelected' message is sent 263 * shown or not. If it is shown, the 'mostVisitedSelected' message is sent
381 * to the C++ code, to record the fact that the user has seen this pane. 264 * to the C++ code, to record the fact that the user has seen this pane.
382 */ 265 */
383 MostVisitedPage.onLoaded = function() { 266 // TODO(pedrosimonetti) is it possible to keep this inside Thumbnail class?
267 /*
268 ThumbnailPage.onLoaded = function() {
384 if (ntp.getCardSlider() && 269 if (ntp.getCardSlider() &&
385 ntp.getCardSlider().currentCardValue && 270 ntp.getCardSlider().currentCardValue &&
386 ntp.getCardSlider().currentCardValue.classList 271 ntp.getCardSlider().currentCardValue.classList
387 .contains('most-visited-page')) { 272 .contains('most-visited-page')) {
388 chrome.send('mostVisitedSelected'); 273 chrome.send('mostVisitedSelected');
389 } 274 }
390 } 275 }
391 276 */
392 /**
393 * We've gotten additional Most Visited data. Update our old data with the
394 * new data. The ordering of the new data is not important, except when a
395 * page is pinned. Thus we try to minimize re-ordering.
396 * @param {Array} oldData The current Most Visited page list.
397 * @param {Array} newData The new Most Visited page list.
398 * @return {Array} The merged page list that should replace the current page
399 * list.
400 */
401 function refreshData(oldData, newData) {
402 oldData = oldData.slice(0, THUMBNAIL_COUNT);
403 newData = newData.slice(0, THUMBNAIL_COUNT);
404
405 // Copy over pinned sites directly.
406 for (var j = 0; j < newData.length; j++) {
407 if (newData[j].pinned) {
408 oldData[j] = newData[j];
409 // Mark the entry as 'updated' so we don't try to update again.
410 oldData[j].updated = true;
411 // Mark the newData page as 'used' so we don't try to re-use it.
412 newData[j].used = true;
413 }
414 }
415
416 // Look through old pages; if they exist in the newData list, keep them
417 // where they are.
418 for (var i = 0; i < oldData.length; i++) {
419 if (!oldData[i] || oldData[i].updated)
420 continue;
421
422 for (var j = 0; j < newData.length; j++) {
423 if (newData[j].used)
424 continue;
425
426 if (newData[j].url == oldData[i].url) {
427 // The background image and other data may have changed.
428 oldData[i] = newData[j];
429 oldData[i].updated = true;
430 newData[j].used = true;
431 break;
432 }
433 }
434 }
435
436 // Look through old pages that haven't been updated yet; replace them.
437 for (var i = 0; i < oldData.length; i++) {
438 if (oldData[i] && oldData[i].updated)
439 continue;
440
441 for (var j = 0; j < newData.length; j++) {
442 if (newData[j].used)
443 continue;
444
445 oldData[i] = newData[j];
446 oldData[i].updated = true;
447 newData[j].used = true;
448 break;
449 }
450
451 if (oldData[i] && !oldData[i].updated)
452 oldData[i] = null;
453 }
454
455 // Clear 'updated' flags so this function will work next time it's called.
456 for (var i = 0; i < THUMBNAIL_COUNT; i++) {
457 if (oldData[i])
458 oldData[i].updated = false;
459 }
460
461 return oldData;
462 };
463 277
464 return { 278 return {
465 MostVisitedPage: MostVisitedPage, 279 Thumbnail: Thumbnail,
466 refreshData: refreshData, 280 ThumbnailPage: ThumbnailPage
467 }; 281 };
468 }); 282 });
469 283
470 document.addEventListener('ntpLoaded', ntp.MostVisitedPage.onLoaded);
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698