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
3 // found in the LICENSE file.
5 cr
.define('ntp', function() {
8 // We can't pass the currently dragging tile via dataTransfer because of
9 // http://crbug.com/31037
10 var currentlyDraggingTile
= null;
11 function getCurrentlyDraggingTile() {
12 return currentlyDraggingTile
;
14 function setCurrentlyDraggingTile(tile
) {
15 currentlyDraggingTile
= tile
;
17 ntp
.enterRearrangeMode();
19 ntp
.leaveRearrangeMode();
23 * Changes the current dropEffect of a drag. This modifies the native cursor
24 * and serves as an indicator of what we should do at the end of the drag as
25 * well as give indication to the user if a drop would succeed if they let go.
26 * @param {DataTransfer} dataTransfer A dataTransfer object from a drag event.
27 * @param {string} effect A drop effect to change to (i.e. copy, move, none).
29 function setCurrentDropEffect(dataTransfer
, effect
) {
30 dataTransfer
.dropEffect
= effect
;
31 if (currentlyDraggingTile
)
32 currentlyDraggingTile
.lastDropEffect
= dataTransfer
.dropEffect
;
36 * Creates a new Tile object. Tiles wrap content on a TilePage, providing
37 * some styling and drag functionality.
39 * @extends {HTMLDivElement}
41 function Tile(contents
) {
42 var tile
= cr
.doc
.createElement('div');
43 tile
.__proto__
= Tile
.prototype;
44 tile
.initialize(contents
);
50 __proto__
: HTMLDivElement
.prototype,
52 initialize: function(contents
) {
53 // 'real' as opposed to doppleganger.
54 this.className
= 'tile real';
55 this.appendChild(contents
);
58 this.addEventListener('dragstart', this.onDragStart_
);
59 this.addEventListener('drag', this.onDragMove_
);
60 this.addEventListener('dragend', this.onDragEnd_
);
62 this.firstChild
.addEventListener(
63 'webkitAnimationEnd', this.onContentsAnimationEnd_
.bind(this));
65 this.eventTracker
= new EventTracker();
69 return Array
.prototype.indexOf
.call(this.tilePage
.tileElements_
, this);
73 return findAncestorByClass(this, 'tile-page');
77 * Position the tile at |x, y|, and store this as the grid location, i.e.
78 * where the tile 'belongs' when it's not being dragged.
79 * @param {number} x The x coordinate, in pixels.
80 * @param {number} y The y coordinate, in pixels.
82 setGridPosition: function(x
, y
) {
89 * Position the tile at |x, y|.
90 * @param {number} x The x coordinate, in pixels.
91 * @param {number} y The y coordinate, in pixels.
93 moveTo: function(x
, y
) {
94 // left overrides right in LTR, and right takes precedence in RTL.
95 this.style
.left
= toCssPx(x
);
96 this.style
.right
= toCssPx(x
);
97 this.style
.top
= toCssPx(y
);
101 * The handler for dragstart events fired on |this|.
102 * @param {Event} e The event for the drag.
105 onDragStart_: function(e
) {
106 // The user may start dragging again during a previous drag's finishing
108 if (this.classList
.contains('dragging'))
109 this.finalizeDrag_();
111 setCurrentlyDraggingTile(this);
113 e
.dataTransfer
.effectAllowed
= 'copyMove';
114 this.firstChild
.setDragData(e
.dataTransfer
);
116 // The drag clone is the node we use as a representation during the drag.
117 // It's attached to the top level document element so that it floats above
119 this.dragClone
= this.cloneNode(true);
120 this.dragClone
.style
.right
= '';
121 this.dragClone
.classList
.add('drag-representation');
122 $('card-slider-frame').appendChild(this.dragClone
);
123 this.eventTracker
.add(this.dragClone
, 'webkitTransitionEnd',
124 this.onDragCloneTransitionEnd_
.bind(this));
126 this.classList
.add('dragging');
127 // offsetLeft is mirrored in RTL. Un-mirror it.
128 var offsetLeft
= isRTL() ?
129 this.parentNode
.clientWidth
- this.offsetLeft
:
131 this.dragOffsetX
= e
.x
- offsetLeft
- this.parentNode
.offsetLeft
;
132 this.dragOffsetY
= e
.y
- this.offsetTop
-
133 // Unlike offsetTop, this value takes scroll position into account.
134 this.parentNode
.getBoundingClientRect().top
;
140 * The handler for drag events fired on |this|.
141 * @param {Event} e The event for the drag.
144 onDragMove_: function(e
) {
145 if (e
.view
!= window
|| (e
.x
== 0 && e
.y
== 0)) {
146 this.dragClone
.hidden
= true;
150 this.dragClone
.hidden
= false;
151 this.dragClone
.style
.left
= toCssPx(e
.x
- this.dragOffsetX
);
152 this.dragClone
.style
.top
= toCssPx(e
.y
- this.dragOffsetY
);
156 * The handler for dragend events fired on |this|.
157 * @param {Event} e The event for the drag.
160 onDragEnd_: function(e
) {
161 this.dragClone
.hidden
= false;
162 this.dragClone
.classList
.add('placing');
164 setCurrentlyDraggingTile(null);
166 // tilePage will be null if we've already been removed.
167 var tilePage
= this.tilePage
;
169 tilePage
.positionTile_(this.index
);
171 // Take an appropriate action with the drag clone.
172 if (this.landedOnTrash
) {
173 this.dragClone
.classList
.add('deleting');
174 } else if (tilePage
) {
175 // TODO(dbeam): Until we fix dropEffect to the correct behavior it will
176 // differ on windows - crbug.com/39399. That's why we use the custom
177 // this.lastDropEffect instead of e.dataTransfer.dropEffect.
178 if (tilePage
.selected
&& this.lastDropEffect
!= 'copy') {
179 // The drag clone can still be hidden from the last drag move event.
180 this.dragClone
.hidden
= false;
181 // The tile's contents may have moved following the respositioning;
183 var contentDiffX
= this.dragClone
.firstChild
.offsetLeft
-
184 this.firstChild
.offsetLeft
;
185 var contentDiffY
= this.dragClone
.firstChild
.offsetTop
-
186 this.firstChild
.offsetTop
;
187 this.dragClone
.style
.left
=
188 toCssPx(this.gridX
+ this.parentNode
.offsetLeft
-
190 this.dragClone
.style
.top
=
192 this.parentNode
.getBoundingClientRect().top
-
194 } else if (this.dragClone
.hidden
) {
195 this.finalizeDrag_();
197 // The CSS3 transitions spec intentionally leaves it up to individual
198 // user agents to determine when styles should be applied. On some
199 // platforms (at the moment, Windows), when you apply both classes
200 // immediately a transition may not occur correctly. That's why we're
201 // using a setTimeout here to queue adding the class until the
202 // previous class (currently: .placing) sets up a transition.
203 // http://dev.w3.org/csswg/css3-transitions/#starting
204 window
.setTimeout(function() {
206 this.dragClone
.classList
.add('dropped-on-other-page');
211 delete this.lastDropEffect
;
212 this.landedOnTrash
= false;
216 * Creates a clone of this node offset by the coordinates. Used for the
217 * dragging effect where a tile appears to float off one side of the grid
218 * and re-appear on the other.
219 * @param {number} x x-axis offset, in pixels.
220 * @param {number} y y-axis offset, in pixels.
222 showDoppleganger: function(x
, y
) {
223 // We always have to clear the previous doppleganger to make sure we get
224 // style updates for the contents of this tile.
225 this.clearDoppleganger();
227 var clone
= this.cloneNode(true);
228 clone
.classList
.remove('real');
229 clone
.classList
.add('doppleganger');
230 var clonelets
= clone
.querySelectorAll('.real');
231 for (var i
= 0; i
< clonelets
.length
; i
++) {
232 clonelets
[i
].classList
.remove('real');
235 this.appendChild(clone
);
236 this.doppleganger_
= clone
;
241 this.doppleganger_
.style
.WebkitTransform
= 'translate(' + x
+ 'px, ' +
246 * Destroys the current doppleganger.
248 clearDoppleganger: function() {
249 if (this.doppleganger_
) {
250 this.removeChild(this.doppleganger_
);
251 this.doppleganger_
= null;
256 * Returns status of doppleganger.
257 * @return {boolean} True if there is a doppleganger showing for |this|.
259 hasDoppleganger: function() {
260 return !!this.doppleganger_
;
264 * Cleans up after the drag is over. This is either called when the
265 * drag representation finishes animating to the final position, or when
266 * the next drag starts (if the user starts a 2nd drag very quickly).
269 finalizeDrag_: function() {
270 assert(this.classList
.contains('dragging'));
272 var clone
= this.dragClone
;
273 this.dragClone
= null;
275 clone
.parentNode
.removeChild(clone
);
276 this.eventTracker
.remove(clone
, 'webkitTransitionEnd');
277 this.classList
.remove('dragging');
278 if (this.firstChild
.finalizeDrag
)
279 this.firstChild
.finalizeDrag();
283 * Called when the drag representation node is done migrating to its final
285 * @param {Event} e The transition end event.
287 onDragCloneTransitionEnd_: function(e
) {
288 if (this.classList
.contains('dragging') &&
289 (e
.propertyName
== 'left' || e
.propertyName
== 'top' ||
290 e
.propertyName
== 'transform')) {
291 this.finalizeDrag_();
296 * Called when an app is removed from Chrome. Animates its disappearance.
297 * @param {boolean=} opt_animate Whether the animation should be animated.
299 doRemove: function(opt_animate
) {
301 this.firstChild
.classList
.add('removing-tile-contents');
303 this.tilePage
.removeTile(this, false);
307 * Callback for the webkitAnimationEnd event on the tile's contents.
308 * @param {Event} e The event object.
310 onContentsAnimationEnd_: function(e
) {
311 if (this.firstChild
.classList
.contains('new-tile-contents'))
312 this.firstChild
.classList
.remove('new-tile-contents');
313 if (this.firstChild
.classList
.contains('removing-tile-contents'))
314 this.tilePage
.removeTile(this, true);
319 * Gives the proportion of the row width that is devoted to a single icon.
320 * @param {number} rowTileCount The number of tiles in a row.
321 * @param {number} tileSpacingFraction The proportion of the tile width which
322 * will be used as spacing between tiles.
323 * @return {number} The ratio between icon width and row width.
325 function tileWidthFraction(rowTileCount
, tileSpacingFraction
) {
326 return rowTileCount
+ (rowTileCount
- 1) * tileSpacingFraction
;
330 * Calculates an assortment of tile-related values for a grid with the
332 * @param {number} width The pixel width of the grid.
333 * @param {number} numRowTiles The number of tiles in a row.
334 * @param {number} tileSpacingFraction The proportion of the tile width which
335 * will be used as spacing between tiles.
336 * @return {Object} A mapping of pixel values.
338 function tileValuesForGrid(width
, numRowTiles
, tileSpacingFraction
) {
339 var tileWidth
= width
/ tileWidthFraction(numRowTiles
, tileSpacingFraction
);
340 var offsetX
= tileWidth
* (1 + tileSpacingFraction
);
341 var interTileSpacing
= offsetX
- tileWidth
;
344 tileWidth
: tileWidth
,
346 interTileSpacing
: interTileSpacing
,
350 // The smallest amount of horizontal blank space to display on the sides when
351 // displaying a wide arrangement. There is an additional 26px of margin from
352 // the tile page padding.
353 var MIN_WIDE_MARGIN
= 18;
356 * Creates a new TilePage object. This object contains tiles and controls
358 * @param {Object} gridValues Pixel values that define the size and layout
361 * @extends {HTMLDivElement}
363 function TilePage(gridValues
) {
364 var el
= cr
.doc
.createElement('div');
365 el
.gridValues_
= gridValues
;
366 el
.__proto__
= TilePage
.prototype;
373 * Takes a collection of grid layout pixel values and updates them with
374 * additional tiling values that are calculated from TilePage constants.
375 * @param {Object} grid The grid layout pixel values to update.
377 TilePage
.initGridValues = function(grid
) {
378 // The amount of space we need to display a narrow grid (all narrow grids
381 grid
.minTileWidth
* tileWidthFraction(grid
.minColCount
,
382 grid
.tileSpacingFraction
);
383 // The minimum amount of space we need to display a wide grid.
385 grid
.minTileWidth
* tileWidthFraction(grid
.maxColCount
,
386 grid
.tileSpacingFraction
);
387 // The largest we will ever display a wide grid.
389 grid
.maxTileWidth
* tileWidthFraction(grid
.maxColCount
,
390 grid
.tileSpacingFraction
);
391 // Tile-related pixel values for the narrow display.
392 grid
.narrowTileValues
= tileValuesForGrid(grid
.narrowWidth
,
394 grid
.tileSpacingFraction
);
395 // Tile-related pixel values for the minimum narrow display.
396 grid
.wideTileValues
= tileValuesForGrid(grid
.minWideWidth
,
398 grid
.tileSpacingFraction
);
401 TilePage
.prototype = {
402 __proto__
: HTMLDivElement
.prototype,
404 initialize: function() {
405 this.className
= 'tile-page';
407 // Div that acts as a custom scrollbar. The scrollbar has to live
408 // outside the content div so it doesn't flicker when scrolling (due to
409 // repainting after the scroll, then repainting again when moved in the
410 // onScroll handler). |scrollbar_| is only aesthetic, and it only
411 // represents the thumb. Actual events are still handled by the invisible
412 // native scrollbars. This div gives us more flexibility with the visuals.
413 this.scrollbar_
= this.ownerDocument
.createElement('div');
414 this.scrollbar_
.className
= 'tile-page-scrollbar';
415 this.scrollbar_
.hidden
= true;
416 this.appendChild(this.scrollbar_
);
418 // This contains everything but the scrollbar.
419 this.content_
= this.ownerDocument
.createElement('div');
420 this.content_
.className
= 'tile-page-content';
421 this.appendChild(this.content_
);
423 // Div that sets the vertical position of the tile grid.
424 this.topMargin_
= this.ownerDocument
.createElement('div');
425 this.topMargin_
.className
= 'top-margin';
426 this.content_
.appendChild(this.topMargin_
);
428 // Div that holds the tiles.
429 this.tileGrid_
= this.ownerDocument
.createElement('div');
430 this.tileGrid_
.className
= 'tile-grid';
431 this.tileGrid_
.style
.minWidth
= this.gridValues_
.narrowWidth
+ 'px';
432 this.tileGrid_
.setAttribute('role', 'menu');
433 this.tileGrid_
.setAttribute('aria-label',
434 loadTimeData
.getString(
435 'tile_grid_screenreader_accessible_description'));
437 this.content_
.appendChild(this.tileGrid_
);
439 // Ordered list of our tiles.
440 this.tileElements_
= this.tileGrid_
.getElementsByClassName('tile real');
441 // Ordered list of the elements which want to accept keyboard focus. These
442 // elements will not be a part of the normal tab order; the tile grid
443 // initially gets focused and then these elements can be focused via the
445 this.focusableElements_
=
446 this.tileGrid_
.getElementsByClassName('focusable');
448 // These are properties used in updateTopMargin.
449 this.animatedTopMarginPx_
= 0;
450 this.topMarginPx_
= 0;
452 this.eventTracker
= new EventTracker();
453 this.eventTracker
.add(window
, 'resize', this.onResize_
.bind(this));
455 this.addEventListener('DOMNodeInsertedIntoDocument',
456 this.onNodeInsertedIntoDocument_
);
458 this.content_
.addEventListener('scroll', this.onScroll_
.bind(this));
460 this.dragWrapper_
= new cr
.ui
.DragWrapper(this.tileGrid_
, this);
462 this.addEventListener('cardselected', this.handleCardSelection_
);
463 this.addEventListener('carddeselected', this.handleCardDeselection_
);
464 this.addEventListener('focus', this.handleFocus_
);
465 this.addEventListener('keydown', this.handleKeyDown_
);
466 this.addEventListener('mousedown', this.handleMouseDown_
);
468 this.focusElementIndex_
= -1;
472 return this.tileElements_
;
476 return this.tileElements_
.length
;
480 return Array
.prototype.indexOf
.call(this.parentNode
.children
, this) ==
481 ntp
.getCardSlider().currentCard
;
485 * The size of the margin (unused space) on the sides of the tile grid, in
490 return this.layoutValues_
.leftMargin
;
494 * Returns the width of the scrollbar, in pixels, if it is active, or 0
498 get scrollbarWidth() {
499 return this.scrollbar_
.hidden
? 0 : 13;
503 * The notification content of this tile (if any, otherwise null).
504 * @type {!HTMLElement}
507 return this.topMargin_
.nextElementSibling
.id
== 'notification-container' ?
508 this.topMargin_
.nextElementSibling
: null;
511 * The notification content of this tile (if any, otherwise null).
512 * @type {!HTMLElement}
514 set notification(node
) {
515 assert(node
instanceof HTMLElement
, '|node| isn\'t an HTMLElement!');
516 // NOTE: Implicitly removes from DOM if |node| is inside it.
517 this.content_
.insertBefore(node
, this.topMargin_
.nextElementSibling
);
518 this.positionNotification_();
522 * Fetches the size, in pixels, of the padding-top of the tile contents.
525 get contentPadding() {
526 if (typeof this.contentPadding_
== 'undefined') {
527 this.contentPadding_
=
528 parseInt(window
.getComputedStyle(this.content_
).paddingTop
, 10);
530 return this.contentPadding_
;
534 * Removes the tilePage from the DOM and cleans up event handlers.
537 // This checks arguments.length as most remove functions have a boolean
538 // |opt_animate| argument, but that's not necesarilly applicable to
539 // removing a tilePage. Selecting a different card in an animated way and
540 // deleting the card afterward is probably a better choice.
541 assert(typeof arguments
[0] != 'boolean',
542 'This function takes no |opt_animate| argument.');
544 this.parentNode
.removeChild(this);
548 * Cleans up resources that are no longer needed after this TilePage
549 * instance is removed from the DOM.
552 tearDown_: function() {
553 this.eventTracker
.removeAll();
557 * Appends a tile to the end of the tile grid.
558 * @param {HTMLElement} tileElement The contents of the tile.
559 * @param {boolean} animate If true, the append will be animated.
562 appendTile: function(tileElement
, animate
) {
563 this.addTileAt(tileElement
, this.tileElements_
.length
, animate
);
567 * Adds the given element to the tile grid.
568 * @param {Node} tileElement The tile object/node to insert.
569 * @param {number} index The location in the tile grid to insert it at.
570 * @param {boolean} animate If true, the tile in question will be
571 * animated (other tiles, if they must reposition, do not animate).
574 addTileAt: function(tileElement
, index
, animate
) {
575 this.classList
.remove('animating-tile-page');
577 tileElement
.classList
.add('new-tile-contents');
579 // Make sure the index is positive and either in the the bounds of
580 // this.tileElements_ or at the end (meaning append).
581 assert(index
>= 0 && index
<= this.tileElements_
.length
);
583 var wrapperDiv
= new Tile(tileElement
);
584 // If is out of the bounds of the tile element list, .insertBefore() will
585 // act just like appendChild().
586 this.tileGrid_
.insertBefore(wrapperDiv
, this.tileElements_
[index
]);
587 this.calculateLayoutValues_();
588 this.heightChanged_();
590 this.repositionTiles_();
592 // If this is the first tile being added, make it focusable after add.
593 if (this.focusableElements_
.length
== 1)
594 this.updateFocusableElement();
595 this.fireAddedEvent(wrapperDiv
, index
, animate
);
599 * Notify interested subscribers that a tile has been removed from this
601 * @param {ntp.Tile} tile The newly added tile.
602 * @param {number} index The index of the tile that was added.
603 * @param {boolean} wasAnimated Whether the removal was animated.
605 fireAddedEvent: function(tile
, index
, wasAnimated
) {
606 var e
= document
.createEvent('Event');
607 e
.initEvent('tilePage:tile_added', true, true);
608 e
.addedIndex
= index
;
610 e
.wasAnimated
= wasAnimated
;
611 this.dispatchEvent(e
);
615 * Removes the given tile and animates the repositioning of the other tiles.
616 * @param {boolean=} opt_animate Whether the removal should be animated.
617 * @param {boolean=} opt_dontNotify Whether a page should be removed if the
618 * last tile is removed from it.
620 removeTile: function(tile
, opt_animate
, opt_dontNotify
) {
622 this.classList
.add('animating-tile-page');
624 var index
= tile
.index
;
625 tile
.parentNode
.removeChild(tile
);
626 this.calculateLayoutValues_();
628 this.updateFocusableElement();
631 this.fireRemovedEvent(tile
, index
, !!opt_animate
);
635 * Notify interested subscribers that a tile has been removed from this
637 * @param {ntp.Tile} tile The tile that was removed.
638 * @param {number} oldIndex Where the tile was positioned before removal.
639 * @param {boolean} wasAnimated Whether the removal was animated.
641 fireRemovedEvent: function(tile
, oldIndex
, wasAnimated
) {
642 var e
= document
.createEvent('Event');
643 e
.initEvent('tilePage:tile_removed', true, true);
644 e
.removedIndex
= oldIndex
;
645 e
.removedTile
= tile
;
646 e
.wasAnimated
= wasAnimated
;
647 this.dispatchEvent(e
);
651 * Removes all tiles from the page.
653 removeAllTiles: function() {
654 this.tileGrid_
.innerHTML
= '';
658 * Called when the page is selected (in the card selector).
659 * @param {Event} e A custom cardselected event.
662 handleCardSelection_: function(e
) {
663 this.updateFocusableElement();
665 // When we are selected, we re-calculate the layout values. (See comment
667 this.calculateLayoutValues_();
671 * Called when the page loses selection (in the card selector).
672 * @param {Event} e A custom carddeselected event.
675 handleCardDeselection_: function(e
) {
676 if (this.currentFocusElement_
)
677 this.currentFocusElement_
.tabIndex
= -1;
681 * When we get focus, pass it on to the focus element.
682 * @param {Event} e The focus event.
685 handleFocus_: function(e
) {
686 if (this.focusableElements_
.length
== 0)
689 this.updateFocusElement_();
693 * Since we are doing custom focus handling, we have to manually
694 * set focusability on click (as well as keyboard nav above).
695 * @param {Event} e The focus event.
698 handleMouseDown_: function(e
) {
699 var focusable
= findAncestorByClass(/** @type {Element} */(e
.target
),
702 this.focusElementIndex_
=
703 Array
.prototype.indexOf
.call(this.focusableElements_
,
705 this.updateFocusElement_();
707 // This prevents the tile page from getting focus when the user clicks
708 // inside the grid but outside of any tile.
714 * Handle arrow key focus nav.
715 * @param {Event} e The focus event.
718 handleKeyDown_: function(e
) {
719 // We only handle up, down, left, right without control keys.
720 if (e
.metaKey
|| e
.shiftKey
|| e
.altKey
|| e
.ctrlKey
)
723 // Wrap the given index to |this.focusableElements_|.
724 var wrap = function(idx
) {
725 return (idx
+ this.focusableElements_
.length
) %
726 this.focusableElements_
.length
;
729 switch (e
.keyIdentifier
) {
732 var direction
= e
.keyIdentifier
== 'Right' ? 1 : -1;
733 this.focusElementIndex_
= wrap(this.focusElementIndex_
+ direction
);
737 // Look through all focusable elements. Find the first one that is
738 // in the same column.
739 var direction
= e
.keyIdentifier
== 'Up' ? -1 : 1;
741 Array
.prototype.indexOf
.call(this.focusableElements_
,
742 this.currentFocusElement_
);
743 var newFocusIdx
= wrap(currentIndex
+ direction
);
744 var tile
= this.currentFocusElement_
.parentNode
;
745 for (;; newFocusIdx
= wrap(newFocusIdx
+ direction
)) {
746 var newTile
= this.focusableElements_
[newFocusIdx
].parentNode
;
747 var rowTiles
= this.layoutValues_
.numRowTiles
;
748 if ((newTile
.index
- tile
.index
) % rowTiles
== 0)
752 this.focusElementIndex_
= newFocusIdx
;
759 this.updateFocusElement_();
766 * Ensure 0 <= this.focusElementIndex_ < this.focusableElements_.length,
767 * make the focusable element at this.focusElementIndex_ (if any) eligible
768 * for tab focus, and the previously-focused element not eligible.
771 updateFocusableElement: function() {
772 if (this.focusableElements_
.length
== 0 || !this.selected
) {
773 this.focusElementIndex_
= -1;
777 this.focusElementIndex_
= Math
.min(this.focusableElements_
.length
- 1,
778 this.focusElementIndex_
);
779 this.focusElementIndex_
= Math
.max(0, this.focusElementIndex_
);
781 var newFocusElement
= this.focusableElements_
[this.focusElementIndex_
];
782 var lastFocusElement
= this.currentFocusElement_
;
783 if (lastFocusElement
&& lastFocusElement
!= newFocusElement
)
784 lastFocusElement
.tabIndex
= -1;
786 newFocusElement
.tabIndex
= 1;
790 * Focuses the element at |this.focusElementIndex_|. Makes the previous
791 * focus element, if any, no longer eligible for tab focus.
794 updateFocusElement_: function() {
795 this.updateFocusableElement();
796 if (this.focusElementIndex_
>= 0)
797 this.focusableElements_
[this.focusElementIndex_
].focus();
801 * The current focus element is that element which is eligible for focus.
802 * @type {HTMLElement} The node.
805 get currentFocusElement_() {
806 return this.querySelector('.focusable[tabindex="1"]');
810 * Makes some calculations for tile layout. These change depending on
811 * height, width, and the number of tiles.
812 * TODO(estade): optimize calls to this function. Do nothing if the page is
813 * hidden, but call before being shown.
816 calculateLayoutValues_: function() {
817 var grid
= this.gridValues_
;
818 var availableSpace
= this.tileGrid_
.clientWidth
- 2 * MIN_WIDE_MARGIN
;
819 var wide
= availableSpace
>= grid
.minWideWidth
;
820 var numRowTiles
= wide
? grid
.maxColCount
: grid
.minColCount
;
822 var effectiveGridWidth
= wide
?
823 Math
.min(Math
.max(availableSpace
, grid
.minWideWidth
),
826 var realTileValues
= tileValuesForGrid(effectiveGridWidth
, numRowTiles
,
827 grid
.tileSpacingFraction
);
829 // leftMargin centers the grid within the avaiable space.
830 var minMargin
= wide
? MIN_WIDE_MARGIN
: 0;
833 (this.tileGrid_
.clientWidth
- effectiveGridWidth
) / 2);
835 var rowHeight
= this.heightForWidth(realTileValues
.tileWidth
) +
836 realTileValues
.interTileSpacing
;
838 this.layoutValues_
= {
839 colWidth
: realTileValues
.offsetX
,
840 gridWidth
: effectiveGridWidth
,
841 leftMargin
: leftMargin
,
842 numRowTiles
: numRowTiles
,
843 rowHeight
: rowHeight
,
844 tileWidth
: realTileValues
.tileWidth
,
848 // We need to update the top margin as well.
849 this.updateTopMargin_();
851 this.firePageLayoutEvent_();
855 * Dispatches the custom pagelayout event.
858 firePageLayoutEvent_: function() {
859 cr
.dispatchSimpleEvent(this, 'pagelayout', true, true);
863 * @return {number} The amount of margin that should be animated (in pixels)
864 * for the current grid layout.
866 getAnimatedLeftMargin_: function() {
867 if (this.layoutValues_
.wide
)
870 var grid
= this.gridValues_
;
871 return (grid
.minWideWidth
- MIN_WIDE_MARGIN
- grid
.narrowWidth
) / 2;
875 * Calculates the x/y coordinates for an element and moves it there.
876 * @param {number} index The index of the element to be positioned.
877 * @param {number=} opt_indexOffset If provided, this is added to |index|
878 * when positioning the tile. The effect is that the tile will be
879 * positioned in a non-default location.
882 positionTile_: function(index
, opt_indexOffset
) {
883 var grid
= this.gridValues_
;
884 var layout
= this.layoutValues_
;
886 var indexOffset
= opt_indexOffset
|| 0;
887 // Add the offset _after_ the modulus division. We might want to show the
888 // tile off the side of the grid.
889 var col
= index
% layout
.numRowTiles
+ indexOffset
;
890 var row
= Math
.floor(index
/ layout
.numRowTiles
);
891 // Calculate the final on-screen position for the tile.
892 var realX
= col
* layout
.colWidth
+ layout
.leftMargin
;
893 var realY
= row
* layout
.rowHeight
;
895 // Calculate the portion of the tile's position that should be animated.
896 var animatedTileValues
= layout
.wide
?
897 grid
.wideTileValues
: grid
.narrowTileValues
;
898 // Animate the difference between three-wide and six-wide.
899 var animatedLeftMargin
= this.getAnimatedLeftMargin_();
900 var animatedX
= col
* animatedTileValues
.offsetX
+ animatedLeftMargin
;
901 var animatedY
= row
* (this.heightForWidth(animatedTileValues
.tileWidth
) +
902 animatedTileValues
.interTileSpacing
);
904 var tile
= this.tileElements_
[index
];
905 tile
.setGridPosition(animatedX
, animatedY
);
906 tile
.firstChild
.setBounds(layout
.tileWidth
,
910 // This code calculates whether the tile needs to show a clone of itself
911 // wrapped around the other side of the tile grid.
912 var offTheRight
= col
== layout
.numRowTiles
||
913 (col
== layout
.numRowTiles
- 1 && tile
.hasDoppleganger());
914 var offTheLeft
= col
== -1 || (col
== 0 && tile
.hasDoppleganger());
915 if (this.isCurrentDragTarget
&& (offTheRight
|| offTheLeft
)) {
916 var sign
= offTheRight
? 1 : -1;
917 tile
.showDoppleganger(-layout
.numRowTiles
* layout
.colWidth
* sign
,
918 layout
.rowHeight
* sign
);
920 tile
.clearDoppleganger();
923 if (index
== this.tileElements_
.length
- 1) {
924 this.tileGrid_
.style
.height
= (realY
+ layout
.rowHeight
) + 'px';
925 this.queueUpdateScrollbars_();
930 * Gets the index of the tile that should occupy coordinate (x, y). Note
931 * that this function doesn't care where the tiles actually are, and will
932 * return an index even for the space between two tiles. This function is
933 * effectively the inverse of |positionTile_|.
934 * @param {number} x The x coordinate, in pixels, relative to the left of
936 * @param {number} y The y coordinate, in pixels, relative to the top of
941 getWouldBeIndexForPoint_: function(x
, y
) {
942 var grid
= this.gridValues_
;
943 var layout
= this.layoutValues_
;
945 var gridClientRect
= this.tileGrid_
.getBoundingClientRect();
946 var col
= Math
.floor((x
- gridClientRect
.left
- layout
.leftMargin
) /
948 if (col
< 0 || col
>= layout
.numRowTiles
)
952 col
= layout
.numRowTiles
- 1 - col
;
954 var row
= Math
.floor((y
- gridClientRect
.top
) / layout
.rowHeight
);
955 return row
* layout
.numRowTiles
+ col
;
959 * Window resize event handler. Window resizes may trigger re-layouts.
960 * @param {Object} e The resize event.
962 onResize_: function(e
) {
963 if (this.lastWidth_
== this.clientWidth
&&
964 this.lastHeight_
== this.clientHeight
) {
968 this.calculateLayoutValues_();
970 this.lastWidth_
= this.clientWidth
;
971 this.lastHeight_
= this.clientHeight
;
972 this.classList
.add('animating-tile-page');
973 this.heightChanged_();
975 this.positionNotification_();
976 this.repositionTiles_();
980 * The tile grid has an image mask which fades at the edges. We only show
981 * the mask when there is an active drag; it obscures doppleganger tiles
982 * as they enter or exit the grid.
985 updateMask_: function() {
986 if (!this.isCurrentDragTarget
) {
987 this.tileGrid_
.style
.WebkitMaskBoxImage
= '';
991 var leftMargin
= this.layoutValues_
.leftMargin
;
992 // The fade distance is the space between tiles.
993 var fadeDistance
= (this.gridValues_
.tileSpacingFraction
*
994 this.layoutValues_
.tileWidth
);
995 fadeDistance
= Math
.min(leftMargin
, fadeDistance
);
996 // On Skia we don't use any fade because it works very poorly. See
997 // http://crbug.com/99373
1001 '-webkit-linear-gradient(left,' +
1003 'transparent ' + (leftMargin
- fadeDistance
) + 'px, ' +
1004 'black ' + leftMargin
+ 'px, ' +
1005 'black ' + (this.tileGrid_
.clientWidth
- leftMargin
) + 'px, ' +
1006 'transparent ' + (this.tileGrid_
.clientWidth
- leftMargin
+
1007 fadeDistance
) + 'px, ' +
1009 this.tileGrid_
.style
.WebkitMaskBoxImage
= gradient
;
1012 updateTopMargin_: function() {
1013 var layout
= this.layoutValues_
;
1015 // The top margin is set so that the vertical midpoint of the grid will
1016 // be 1/3 down the page.
1017 var numTiles
= this.tileCount
+
1018 (this.isCurrentDragTarget
&& !this.withinPageDrag_
? 1 : 0);
1019 var numRows
= Math
.max(1, Math
.ceil(numTiles
/ layout
.numRowTiles
));
1020 var usedHeight
= layout
.rowHeight
* numRows
;
1021 var newMargin
= document
.documentElement
.clientHeight
/ 3 -
1022 usedHeight
/ 3 - this.contentPadding
;
1023 // The 'height' style attribute of topMargin is non-zero to work around
1024 // webkit's collapsing margin behavior, so we have to factor that into
1025 // our calculations here.
1026 newMargin
= Math
.max(newMargin
, 0) - this.topMargin_
.offsetHeight
;
1028 // |newMargin| is the final margin we actually want to show. However,
1029 // part of that should be animated and part should not (for the same
1030 // reason as with leftMargin). The approach is to consider differences
1031 // when the layout changes from wide to narrow or vice versa as
1032 // 'animatable'. These differences accumulate in animatedTopMarginPx_,
1033 // while topMarginPx_ caches the real (total) margin. Either of these
1034 // calculations may come out to be negative, so we use margins as the
1037 if (typeof this.topMarginIsForWide_
== 'undefined')
1038 this.topMarginIsForWide_
= layout
.wide
;
1039 if (this.topMarginIsForWide_
!= layout
.wide
) {
1040 this.animatedTopMarginPx_
+= newMargin
- this.topMarginPx_
;
1041 this.topMargin_
.style
.marginBottom
= toCssPx(this.animatedTopMarginPx_
);
1044 this.topMarginIsForWide_
= layout
.wide
;
1045 this.topMarginPx_
= newMargin
;
1046 this.topMargin_
.style
.marginTop
=
1047 toCssPx(this.topMarginPx_
- this.animatedTopMarginPx_
);
1051 * Position the notification if there's one showing.
1053 positionNotification_: function() {
1054 var notification
= this.notification
;
1055 if (!notification
|| notification
.hidden
)
1058 // Update the horizontal position.
1059 var animatedLeftMargin
= this.getAnimatedLeftMargin_();
1060 notification
.style
.WebkitMarginStart
= animatedLeftMargin
+ 'px';
1061 var leftOffset
= (this.layoutValues_
.leftMargin
- animatedLeftMargin
) *
1063 notification
.style
.WebkitTransform
= 'translateX(' + leftOffset
+ 'px)';
1065 // Update the allowable widths of the text.
1066 var buttonWidth
= notification
.querySelector('button').offsetWidth
+ 8;
1067 notification
.querySelector('span').style
.maxWidth
=
1068 this.layoutValues_
.gridWidth
- buttonWidth
+ 'px';
1070 // This makes sure the text doesn't condense smaller than the narrow size
1071 // of the grid (e.g. when a user makes the window really small).
1072 notification
.style
.minWidth
=
1073 this.gridValues_
.narrowWidth
- buttonWidth
+ 'px';
1075 // Update the top position.
1076 notification
.style
.marginTop
= -notification
.offsetHeight
+ 'px';
1080 * Handles final setup that can only happen after |this| is inserted into
1084 onNodeInsertedIntoDocument_: function(e
) {
1085 this.calculateLayoutValues_();
1086 this.heightChanged_();
1090 * Called when the height of |this| has changed: update the size of
1094 heightChanged_: function() {
1095 // The tile grid will expand to the bottom footer, or enough to hold all
1096 // the tiles, whichever is greater. It would be nicer if tilePage were
1097 // a flex box, and the tile grid could be box-flex: 1, but this exposes a
1098 // bug where repositioning tiles will cause the scroll position to reset.
1099 this.tileGrid_
.style
.minHeight
= this.clientHeight
-
1100 this.tileGrid_
.offsetTop
- this.content_
.offsetTop
+ 'px';
1104 * Scrolls the page in response to an mousewheel event, although the event
1105 * may have been triggered on a different element. Return true if the
1106 * event triggered scrolling, and false otherwise.
1107 * This is called explicitly, which allows a consistent experience whether
1108 * the user scrolls on the page or on the page switcher, because this
1109 * function provides a common conversion factor between wheel delta and
1111 * @param {Event} e The mousewheel event.
1113 handleMouseWheel: function(e
) {
1114 // The ctrl-wheel should triggle the zoom in/out actions in Chromium for
1116 if (e
.wheelDeltaY
== 0 || e
.ctrlKey
)
1119 this.content_
.scrollTop
-= e
.wheelDeltaY
/ 3;
1124 * Handler for the 'scroll' event on |content_|.
1125 * @param {Event} e The scroll event.
1128 onScroll_: function(e
) {
1129 this.queueUpdateScrollbars_();
1133 * ID of scrollbar update timer. If 0, there's no scrollbar re-calc queued.
1136 scrollbarUpdate_
: 0,
1139 * Queues an update on the custom scrollbar. Used for two reasons: first,
1140 * coalescing of multiple updates, and second, because action like
1141 * repositioning a tile can require a delay before they affect values
1142 * like clientHeight.
1145 queueUpdateScrollbars_: function() {
1146 if (this.scrollbarUpdate_
)
1149 this.scrollbarUpdate_
= window
.setTimeout(
1150 this.doUpdateScrollbars_
.bind(this), 0);
1154 * Does the work of calculating the visibility, height and position of the
1155 * scrollbar thumb (there is no track or buttons).
1158 doUpdateScrollbars_: function() {
1159 this.scrollbarUpdate_
= 0;
1161 var content
= this.content_
;
1163 // Adjust scroll-height to account for possible header-bar.
1164 var adjustedScrollHeight
= content
.scrollHeight
- content
.offsetTop
;
1166 if (adjustedScrollHeight
<= content
.clientHeight
) {
1167 this.scrollbar_
.hidden
= true;
1170 this.scrollbar_
.hidden
= false;
1173 var thumbTop
= content
.offsetTop
+
1174 content
.scrollTop
/ adjustedScrollHeight
* content
.clientHeight
;
1175 var thumbHeight
= content
.clientHeight
/ adjustedScrollHeight
*
1178 this.scrollbar_
.style
.top
= thumbTop
+ 'px';
1179 this.scrollbar_
.style
.height
= thumbHeight
+ 'px';
1180 this.firePageLayoutEvent_();
1184 * Get the height for a tile of a certain width. Override this function to
1185 * get non-square tiles.
1186 * @param {number} width The pixel width of a tile.
1187 * @return {number} The height for |width|.
1189 heightForWidth: function(width
) {
1195 get isCurrentDragTarget() {
1196 return this.dragWrapper_
.isCurrentDragTarget
;
1200 * Thunk for dragleave events fired on |tileGrid_|.
1201 * @param {Event} e A MouseEvent for the drag.
1203 doDragLeave: function(e
) {
1208 * Performs all actions necessary when a drag enters the tile page.
1209 * @param {Event} e A mouseover event for the drag enter.
1211 doDragEnter: function(e
) {
1212 // Applies the mask so doppleganger tiles disappear into the fog.
1215 this.classList
.add('animating-tile-page');
1216 this.withinPageDrag_
= this.contains(currentlyDraggingTile
);
1217 this.dragItemIndex_
= this.withinPageDrag_
?
1218 currentlyDraggingTile
.index
: this.tileElements_
.length
;
1219 this.currentDropIndex_
= this.dragItemIndex_
;
1221 // The new tile may change the number of rows, hence the top margin
1223 if (!this.withinPageDrag_
)
1224 this.updateTopMargin_();
1230 * Performs all actions necessary when the user moves the cursor during
1231 * a drag over the tile page.
1232 * @param {Event} e A mouseover event for the drag over.
1234 doDragOver: function(e
) {
1237 this.setDropEffect(e
.dataTransfer
);
1238 var newDragIndex
= this.getWouldBeIndexForPoint_(e
.pageX
, e
.pageY
);
1239 if (newDragIndex
< 0 || newDragIndex
>= this.tileElements_
.length
)
1240 newDragIndex
= this.dragItemIndex_
;
1241 this.updateDropIndicator_(newDragIndex
);
1245 * Performs all actions necessary when the user completes a drop.
1246 * @param {Event} e A mouseover event for the drag drop.
1248 doDrop: function(e
) {
1249 e
.stopPropagation();
1252 var index
= this.currentDropIndex_
;
1253 // Only change data if this was not a 'null drag'.
1254 if (!((index
== this.dragItemIndex_
) && this.withinPageDrag_
)) {
1255 var adjustedIndex
= this.currentDropIndex_
+
1256 (index
> this.dragItemIndex_
? 1 : 0);
1257 if (this.withinPageDrag_
) {
1258 this.tileGrid_
.insertBefore(
1259 currentlyDraggingTile
,
1260 this.tileElements_
[adjustedIndex
]);
1261 this.tileMoved(currentlyDraggingTile
, this.dragItemIndex_
);
1263 var originalPage
= currentlyDraggingTile
?
1264 currentlyDraggingTile
.tilePage
: null;
1265 this.addDragData(e
.dataTransfer
, adjustedIndex
);
1267 originalPage
.cleanupDrag();
1270 // Dropping the icon may cause topMargin to change, but changing it
1271 // now would cause everything to move (annoying), so we leave it
1272 // alone. The top margin will be re-calculated next time the window is
1273 // resized or the page is selected.
1276 this.classList
.remove('animating-tile-page');
1281 * Appends the currently dragged tile to the end of the page. Called
1282 * from outside the page, e.g. when dropping on a nav dot.
1284 appendDraggingTile: function() {
1285 var originalPage
= currentlyDraggingTile
.tilePage
;
1286 if (originalPage
== this)
1289 this.addDragData(null, this.tileElements_
.length
);
1291 originalPage
.cleanupDrag();
1295 * Makes sure all the tiles are in the right place after a drag is over.
1297 cleanupDrag: function() {
1298 this.repositionTiles_(currentlyDraggingTile
);
1299 // Remove the drag mask.
1304 * Reposition all the tiles (possibly ignoring one).
1305 * @param {Node=} opt_ignoreNode An optional node to ignore.
1308 repositionTiles_: function(opt_ignoreNode
) {
1309 for (var i
= 0; i
< this.tileElements_
.length
; i
++) {
1310 if (!opt_ignoreNode
|| opt_ignoreNode
!== this.tileElements_
[i
])
1311 this.positionTile_(i
);
1316 * Updates the visual indicator for the drop location for the active drag.
1317 * @param {number} newDragIndex
1320 updateDropIndicator_: function(newDragIndex
) {
1321 var oldDragIndex
= this.currentDropIndex_
;
1322 if (newDragIndex
== oldDragIndex
)
1325 var repositionStart
= Math
.min(newDragIndex
, oldDragIndex
);
1326 var repositionEnd
= Math
.max(newDragIndex
, oldDragIndex
);
1328 for (var i
= repositionStart
; i
<= repositionEnd
; i
++) {
1329 if (i
== this.dragItemIndex_
)
1331 else if (i
> this.dragItemIndex_
)
1332 var adjustment
= i
<= newDragIndex
? -1 : 0;
1334 var adjustment
= i
>= newDragIndex
? 1 : 0;
1336 this.positionTile_(i
, adjustment
);
1338 this.currentDropIndex_
= newDragIndex
;
1342 * Checks if a page can accept a drag with the given data.
1343 * @param {Event} e The drag event if the drag object. Implementations will
1344 * likely want to check |e.dataTransfer|.
1345 * @return {boolean} True if this page can handle the drag.
1347 shouldAcceptDrag: function(e
) {
1352 * Called to accept a drag drop. Will not be called for in-page drops.
1353 * @param {Object} dataTransfer The data transfer object that holds the drop
1354 * data. This should only be used if currentlyDraggingTile is null.
1355 * @param {number} index The tile index at which the drop occurred.
1357 addDragData: function(dataTransfer
, index
) {
1362 * Called when a tile has been moved (via dragging). Override this to make
1364 * @param {Node} draggedTile The tile that was dropped.
1365 * @param {number} prevIndex The previous index of the tile.
1367 tileMoved: function(draggedTile
, prevIndex
) {
1371 * Sets the drop effect on |dataTransfer| to the desired value (e.g.
1373 * @param {Object} dataTransfer The drag event dataTransfer object.
1375 setDropEffect: function(dataTransfer
) {
1381 getCurrentlyDraggingTile
: getCurrentlyDraggingTile
,
1382 setCurrentDropEffect
: setCurrentDropEffect
,
1383 // Not used outside, just for usage in JSDoc inside this file.