2 * Angular Material Design
3 * https://github.com/angular/material
7 goog.provide('ng.material.components.gridList');
8 goog.require('ng.material.core');
11 * @name material.components.gridList
13 angular.module('material.components.gridList', ['material.core'])
14 .directive('mdGridList', GridListDirective)
15 .directive('mdGridTile', GridTileDirective)
16 .directive('mdGridTileFooter', GridTileCaptionDirective)
17 .directive('mdGridTileHeader', GridTileCaptionDirective)
18 .factory('$mdGridLayout', GridLayoutFactory);
23 * @module material.components.gridList
26 * Grid lists are an alternative to standard list views. Grid lists are distinct
27 * from grids used for layouts and other visual presentations.
29 * A grid list is best suited to presenting a homogenous data type, typically
30 * images, and is optimized for visual comprehension and differentiating between
33 * A grid list is a continuous element consisting of tessellated, regular
34 * subdivisions called cells that contain tiles (`md-grid-tile`).
36 * <img src="//material-design.storage.googleapis.com/publish/v_2/material_ext_publish/0Bx4BSt6jniD7OVlEaXZ5YmU1Xzg/components_grids_usage2.png"
37 * style="width: 300px; height: auto; margin-right: 16px;" alt="Concept of grid explained visually">
38 * <img src="//material-design.storage.googleapis.com/publish/v_2/material_ext_publish/0Bx4BSt6jniD7VGhsOE5idWlJWXM/components_grids_usage3.png"
39 * style="width: 300px; height: auto;" alt="Grid concepts legend">
41 * Cells are arrayed vertically and horizontally within the grid.
43 * Tiles hold content and can span one or more cells vertically or horizontally.
45 * ### Responsive Attributes
47 * The `md-grid-list` directive supports "responsive" attributes, which allow
48 * different `md-cols`, `md-gutter` and `md-row-height` values depending on the
49 * currently matching media query (as defined in `$mdConstant.MEDIA`).
51 * In order to set a responsive attribute, first define the fallback value with
52 * the standard attribute name, then add additional attributes with the
53 * following convention: `{base-attribute-name}-{media-query-name}="{value}"`
54 * (ie. `md-cols-lg="8"`)
56 * @param {number} md-cols Number of columns in the grid.
57 * @param {string} md-row-height One of
59 * <li>CSS length - Fixed height rows (eg. `8px` or `1rem`)</li>
60 * <li>`{width}:{height}` - Ratio of width to height (eg.
61 * `md-row-height="16:9"`)</li>
62 * <li>`"fit"` - Height will be determined by subdividing the available
63 * height by the number of rows</li>
65 * @param {string=} md-gutter The amount of space between tiles in CSS units
67 * @param {expression=} md-on-layout Expression to evaluate after layout. Event
68 * object is available as `$event`, and contains performance information.
73 * <md-grid-list md-cols="5" md-gutter="1em" md-row-height="4:3">
74 * <md-grid-tile></md-grid-tile>
80 * <md-grid-list md-cols="4" md-row-height="200px" ...>
81 * <md-grid-tile></md-grid-tile>
87 * <md-grid-list md-cols="4" md-row-height="fit" style="height: 400px;" ...>
88 * <md-grid-tile></md-grid-tile>
92 * Using responsive attributes:
100 * <md-grid-tile></md-grid-tile>
104 function GridListDirective($interpolate, $mdConstant, $mdGridLayout, $mdMedia) {
107 controller: GridListController,
114 function postLink(scope, element, attrs, ctrl) {
116 element.attr('role', 'list');
118 // Provide the controller with a way to trigger layouts.
119 ctrl.layoutDelegate = layoutDelegate;
121 var invalidateLayout = angular.bind(ctrl, ctrl.invalidateLayout),
122 unwatchAttrs = watchMedia();
123 scope.$on('$destroy', unwatchMedia);
126 * Watches for changes in media, invalidating layout as necessary.
128 function watchMedia() {
129 for (var mediaName in $mdConstant.MEDIA) {
130 $mdMedia(mediaName); // initialize
131 $mdMedia.getQuery($mdConstant.MEDIA[mediaName])
132 .addListener(invalidateLayout);
134 return $mdMedia.watchResponsiveAttributes(
135 ['md-cols', 'md-row-height'], attrs, layoutIfMediaMatch);
138 function unwatchMedia() {
139 ctrl.layoutDelegate = angular.noop;
142 for (var mediaName in $mdConstant.MEDIA) {
143 $mdMedia.getQuery($mdConstant.MEDIA[mediaName])
144 .removeListener(invalidateLayout);
149 * Performs grid layout if the provided mediaName matches the currently
152 function layoutIfMediaMatch(mediaName) {
153 if (mediaName == null) {
154 // TODO(shyndman): It would be nice to only layout if we have
155 // instances of attributes using this media type
156 ctrl.invalidateLayout();
157 } else if ($mdMedia(mediaName)) {
158 ctrl.invalidateLayout();
165 * Invokes the layout engine, and uses its results to lay out our
168 * @param {boolean} tilesInvalidated Whether tiles have been
169 * added/removed/moved since the last layout. This is to avoid situations
170 * where tiles are replaced with properties identical to their removed
173 function layoutDelegate(tilesInvalidated) {
174 var tiles = getTileElements();
176 tileSpans: getTileSpans(tiles),
177 colCount: getColumnCount(),
178 rowMode: getRowMode(),
179 rowHeight: getRowHeight(),
183 if (!tilesInvalidated && angular.equals(props, lastLayoutProps)) {
188 $mdGridLayout(props.colCount, props.tileSpans, tiles)
189 .map(function(tilePositions, rowCount) {
193 style: getGridStyle(props.colCount, rowCount,
194 props.gutter, props.rowMode, props.rowHeight)
196 tiles: tilePositions.map(function(ps, i) {
198 element: angular.element(tiles[i]),
199 style: getTileStyle(ps.position, ps.spans,
200 props.colCount, props.rowCount,
201 props.gutter, props.rowMode, props.rowHeight)
212 performance: performance
216 lastLayoutProps = props;
219 // Use $interpolate to do some simple string interpolation as a convenience.
221 var startSymbol = $interpolate.startSymbol();
222 var endSymbol = $interpolate.endSymbol();
224 // Returns an expression wrapped in the interpolator's start and end symbols.
225 function expr(exprStr) {
226 return startSymbol + exprStr + endSymbol;
229 // The amount of space a single 1x1 tile would take up (either width or height), used as
230 // a basis for other calculations. This consists of taking the base size percent (as would be
231 // if evenly dividing the size between cells), and then subtracting the size of one gutter.
232 // However, since there are no gutters on the edges, each tile only uses a fration
233 // (gutterShare = numGutters / numCells) of the gutter size. (Imagine having one gutter per
234 // tile, and then breaking up the extra gutter on the edge evenly among the cells).
235 var UNIT = $interpolate(expr('share') + '% - (' + expr('gutter') + ' * ' + expr('gutterShare') + ')');
237 // The horizontal or vertical position of a tile, e.g., the 'top' or 'left' property value.
238 // The position comes the size of a 1x1 tile plus gutter for each previous tile in the
239 // row/column (offset).
240 var POSITION = $interpolate('calc((' + expr('unit') + ' + ' + expr('gutter') + ') * ' + expr('offset') + ')');
242 // The actual size of a tile, e.g., width or height, taking rowSpan or colSpan into account.
243 // This is computed by multiplying the base unit by the rowSpan/colSpan, and then adding back
244 // in the space that the gutter would normally have used (which was already accounted for in
245 // the base unit calculation).
246 var DIMENSION = $interpolate('calc((' + expr('unit') + ') * ' + expr('span') + ' + (' + expr('span') + ' - 1) * ' + expr('gutter') + ')');
249 * Gets the styles applied to a tile element described by the given parameters.
250 * @param {{row: number, col: number}} position The row and column indices of the tile.
251 * @param {{row: number, col: number}} spans The rowSpan and colSpan of the tile.
252 * @param {number} colCount The number of columns.
253 * @param {number} rowCount The number of rows.
254 * @param {string} gutter The amount of space between tiles. This will be something like
256 * @param {string} rowMode The row height mode. Can be one of:
257 * 'fixed': all rows have a fixed size, given by rowHeight,
258 * 'ratio': row height defined as a ratio to width, or
259 * 'fit': fit to the grid-list element height, divinding evenly among rows.
260 * @param {string|number} rowHeight The height of a row. This is only used for 'fixed' mode and
261 * for 'ratio' mode. For 'ratio' mode, this is the *ratio* of width-to-height (e.g., 0.75).
262 * @returns {Object} Map of CSS properties to be applied to the style element. Will define
263 * values for top, left, width, height, marginTop, and paddingTop.
265 function getTileStyle(position, spans, colCount, rowCount, gutter, rowMode, rowHeight) {
266 // TODO(shyndman): There are style caching opportunities here.
268 // Percent of the available horizontal space that one column takes up.
269 var hShare = (1 / colCount) * 100;
271 // Fraction of the gutter size that each column takes up.
272 var hGutterShare = (colCount - 1) / colCount;
274 // Base horizontal size of a column.
275 var hUnit = UNIT({share: hShare, gutterShare: hGutterShare, gutter: gutter});
277 // The width and horizontal position of each tile is always calculated the same way, but the
278 // height and vertical position depends on the rowMode.
280 left: POSITION({ unit: hUnit, offset: position.col, gutter: gutter }),
281 width: DIMENSION({ unit: hUnit, span: spans.col, gutter: gutter }),
291 // In fixed mode, simply use the given rowHeight.
292 style.top = POSITION({ unit: rowHeight, offset: position.row, gutter: gutter });
293 style.height = DIMENSION({ unit: rowHeight, span: spans.row, gutter: gutter });
297 // Percent of the available vertical space that one row takes up. Here, rowHeight holds
298 // the ratio value. For example, if the width:height ratio is 4:3, rowHeight = 1.333.
299 var vShare = hShare / rowHeight;
301 // Base veritcal size of a row.
302 var vUnit = UNIT({ share: vShare, gutterShare: hGutterShare, gutter: gutter });
304 // padidngTop and marginTop are used to maintain the given aspect ratio, as
305 // a percentage-based value for these properties is applied to the *width* of the
306 // containing block. See http://www.w3.org/TR/CSS2/box.html#margin-properties
307 style.paddingTop = DIMENSION({ unit: vUnit, span: spans.row, gutter: gutter});
308 style.marginTop = POSITION({ unit: vUnit, offset: position.row, gutter: gutter });
312 // Fraction of the gutter size that each column takes up.
313 var vGutterShare = (rowCount - 1) / rowCount;
315 // Percent of the available vertical space that one row takes up.
316 var vShare = (1 / rowCount) * 100;
318 // Base vertical size of a row.
319 var vUnit = UNIT({share: vShare, gutterShare: vGutterShare, gutter: gutter});
321 style.top = POSITION({unit: vUnit, offset: position.row, gutter: gutter});
322 style.height = DIMENSION({unit: vUnit, span: spans.row, gutter: gutter});
329 function getGridStyle(colCount, rowCount, gutter, rowMode, rowHeight) {
337 style.height = DIMENSION({ unit: rowHeight, span: rowCount, gutter: gutter });
341 // rowHeight is width / height
342 var hGutterShare = colCount === 1 ? 0 : (colCount - 1) / colCount,
343 hShare = (1 / colCount) * 100,
344 vShare = hShare * (1 / rowHeight),
345 vUnit = UNIT({ share: vShare, gutterShare: hGutterShare, gutter: gutter });
347 style.paddingBottom = DIMENSION({ unit: vUnit, span: rowCount, gutter: gutter});
351 // noop, as the height is user set
358 function getTileElements() {
359 return [].filter.call(element.children(), function(ele) {
360 return ele.tagName == 'MD-GRID-TILE';
365 * Gets an array of objects containing the rowspan and colspan for each tile.
366 * @returns {Array<{row: number, col: number}>}
368 function getTileSpans(tileElements) {
369 return [].map.call(tileElements, function(ele) {
370 var ctrl = angular.element(ele).controller('mdGridTile');
373 $mdMedia.getResponsiveAttribute(ctrl.$attrs, 'md-rowspan'), 10) || 1,
375 $mdMedia.getResponsiveAttribute(ctrl.$attrs, 'md-colspan'), 10) || 1
380 function getColumnCount() {
381 var colCount = parseInt($mdMedia.getResponsiveAttribute(attrs, 'md-cols'), 10);
382 if (isNaN(colCount)) {
383 throw 'md-grid-list: md-cols attribute was not found, or contained a non-numeric value';
388 function getGutter() {
389 return applyDefaultUnit($mdMedia.getResponsiveAttribute(attrs, 'md-gutter') || 1);
392 function getRowHeight() {
393 var rowHeight = $mdMedia.getResponsiveAttribute(attrs, 'md-row-height');
394 switch (getRowMode()) {
396 return applyDefaultUnit(rowHeight);
398 var whRatio = rowHeight.split(':');
399 return parseFloat(whRatio[0]) / parseFloat(whRatio[1]);
405 function getRowMode() {
406 var rowHeight = $mdMedia.getResponsiveAttribute(attrs, 'md-row-height');
407 if (rowHeight == 'fit') {
409 } else if (rowHeight.indexOf(':') !== -1) {
416 function applyDefaultUnit(val) {
417 return /\D$/.test(val) ? val : val + 'px';
421 GridListDirective.$inject = ["$interpolate", "$mdConstant", "$mdGridLayout", "$mdMedia"];
424 function GridListController($timeout) {
425 this.layoutInvalidated = false;
426 this.tilesInvalidated = false;
427 this.$timeout_ = $timeout;
428 this.layoutDelegate = angular.noop;
430 GridListController.$inject = ["$timeout"];
432 GridListController.prototype = {
433 invalidateTiles: function() {
434 this.tilesInvalidated = true;
435 this.invalidateLayout();
438 invalidateLayout: function() {
439 if (this.layoutInvalidated) {
442 this.layoutInvalidated = true;
443 this.$timeout_(angular.bind(this, this.layout));
448 this.layoutDelegate(this.tilesInvalidated);
450 this.layoutInvalidated = false;
451 this.tilesInvalidated = false;
458 function GridLayoutFactory($mdUtil) {
459 var defaultAnimator = GridTileAnimator;
462 * Set the reflow animator callback
464 GridLayout.animateWith = function(customAnimator) {
465 defaultAnimator = !angular.isFunction(customAnimator) ? GridTileAnimator : customAnimator;
471 * Publish layout function
473 function GridLayout(colCount, tileSpans) {
474 var self, layoutInfo, gridStyles, layoutTime, mapTime, reflowTime;
476 layoutTime = $mdUtil.time(function() {
477 layoutInfo = calculateGridFor(colCount, tileSpans);
483 * An array of objects describing each tile's position in the grid.
485 layoutInfo: function() {
490 * Maps grid positioning to an element and a set of styles using the
493 map: function(updateFn) {
494 mapTime = $mdUtil.time(function() {
495 var info = self.layoutInfo();
496 gridStyles = updateFn(info.positioning, info.rowCount);
502 * Default animator simply sets the element.css( <styles> ). An alternate
503 * animator can be provided as an argument. The function has the following
506 * function({grid: {element: JQLite, style: Object}, tiles: Array<{element: JQLite, style: Object}>)
508 reflow: function(animatorFn) {
509 reflowTime = $mdUtil.time(function() {
510 var animator = animatorFn || defaultAnimator;
511 animator(gridStyles.grid, gridStyles.tiles);
517 * Timing for the most recent layout run.
519 performance: function() {
521 tileCount: tileSpans.length,
522 layoutTime: layoutTime,
524 reflowTime: reflowTime,
525 totalTime: layoutTime + mapTime + reflowTime
532 * Default Gridlist animator simple sets the css for each element;
533 * NOTE: any transitions effects must be manually set in the CSS.
537 * transition: all 700ms ease-out 50ms;
541 function GridTileAnimator(grid, tiles) {
542 grid.element.css(grid.style);
543 tiles.forEach(function(t) {
544 t.element.css(t.style);
549 * Calculates the positions of tiles.
551 * The algorithm works as follows:
552 * An Array<Number> with length colCount (spaceTracker) keeps track of
553 * available tiling positions, where elements of value 0 represents an
554 * empty position. Space for a tile is reserved by finding a sequence of
555 * 0s with length <= than the tile's colspan. When such a space has been
556 * found, the occupied tile positions are incremented by the tile's
557 * rowspan value, as these positions have become unavailable for that
560 * If the end of a row has been reached without finding space for the
561 * tile, spaceTracker's elements are each decremented by 1 to a minimum
562 * of 0. Rows are searched in this fashion until space is found.
564 function calculateGridFor(colCount, tileSpans) {
567 spaceTracker = newSpaceTracker();
570 positioning: tileSpans.map(function(spans, i) {
573 position: reserveSpace(spans, i)
576 rowCount: curRow + Math.max.apply(Math, spaceTracker)
579 function reserveSpace(spans, i) {
580 if (spans.col > colCount) {
581 throw 'md-grid-list: Tile at position ' + i + ' has a colspan ' +
582 '(' + spans.col + ') that exceeds the column count ' +
583 '(' + colCount + ')';
589 // TODO(shyndman): This loop isn't strictly necessary if you can
590 // determine the minimum number of rows before a space opens up. To do
591 // this, recognize that you've iterated across an entire row looking for
592 // space, and if so fast-forward by the minimum rowSpan count. Repeat
593 // until the required space opens up.
594 while (end - start < spans.col) {
595 if (curCol >= colCount) {
600 start = spaceTracker.indexOf(0, curCol);
601 if (start === -1 || (end = findEnd(start + 1)) === -1) {
610 adjustRow(start, spans.col, spans.row);
611 curCol = start + spans.col;
622 adjustRow(0, colCount, -1); // Decrement row spans by one
625 function adjustRow(from, cols, by) {
626 for (var i = from; i < from + cols; i++) {
627 spaceTracker[i] = Math.max(spaceTracker[i] + by, 0);
631 function findEnd(start) {
633 for (i = start; i < spaceTracker.length; i++) {
634 if (spaceTracker[i] !== 0) {
639 if (i === spaceTracker.length) {
644 function newSpaceTracker() {
646 for (var i = 0; i < colCount; i++) {
653 GridLayoutFactory.$inject = ["$mdUtil"];
658 * @module material.components.gridList
661 * Tiles contain the content of an `md-grid-list`. They span one or more grid
662 * cells vertically or horizontally, and use `md-grid-tile-{footer,header}` to
663 * display secondary content.
665 * ### Responsive Attributes
667 * The `md-grid-tile` directive supports "responsive" attributes, which allow
668 * different `md-rowspan` and `md-colspan` values depending on the currently
669 * matching media query (as defined in `$mdConstant.MEDIA`).
671 * In order to set a responsive attribute, first define the fallback value with
672 * the standard attribute name, then add additional attributes with the
673 * following convention: `{base-attribute-name}-{media-query-name}="{value}"`
674 * (ie. `md-colspan-sm="4"`)
676 * @param {number=} md-colspan The number of columns to span (default 1). Cannot
677 * exceed the number of columns in the grid. Supports interpolation.
678 * @param {number=} md-rowspan The number of rows to span (default 1). Supports
685 * <md-grid-tile-header>
686 * <h3>This is a header</h3>
687 * </md-grid-tile-header>
694 * <md-grid-tile-footer>
695 * <h3>This is a footer</h3>
696 * </md-grid-tile-footer>
700 * Spanning multiple rows/columns:
702 * <md-grid-tile md-colspan="2" md-rowspan="3">
706 * Responsive attributes:
708 * <md-grid-tile md-colspan="1" md-colspan-sm="3" md-colspan-md="5">
712 function GridTileDirective($mdMedia) {
715 require: '^mdGridList',
716 template: '<figure ng-transclude></figure>',
719 // Simple controller that exposes attributes to the grid directive
720 controller: ["$attrs", function($attrs) {
721 this.$attrs = $attrs;
726 function postLink(scope, element, attrs, gridCtrl) {
728 element.attr('role', 'listitem');
730 // If our colspan or rowspan changes, trigger a layout
731 var unwatchAttrs = $mdMedia.watchResponsiveAttributes(['md-colspan', 'md-rowspan'],
732 attrs, angular.bind(gridCtrl, gridCtrl.invalidateLayout));
734 // Tile registration/deregistration
735 gridCtrl.invalidateTiles();
736 scope.$on('$destroy', function() {
738 gridCtrl.invalidateLayout();
741 if (angular.isDefined(scope.$parent.$index)) {
742 scope.$watch(function() { return scope.$parent.$index; },
743 function indexChanged(newIdx, oldIdx) {
744 if (newIdx === oldIdx) {
747 gridCtrl.invalidateTiles();
752 GridTileDirective.$inject = ["$mdMedia"];
755 function GridTileCaptionDirective() {
757 template: '<figcaption ng-transclude></figcaption>',
762 ng.material.components.gridList = angular.module("material.components.gridList");