` if one is not provided. Defaults to true. Can be disabled if you provide a
* custom toast directive.
* - `scope` - `{object=}`: the scope to link the template / controller to. If none is specified, it will create a new child scope.
* This scope will be destroyed when the toast is removed unless `preserveScope` is set to true.
* - `preserveScope` - `{boolean=}`: whether to preserve the scope when the element is removed. Default is false
* - `hideDelay` - `{number=}`: How many milliseconds the toast should stay
* active before automatically closing. Set to 0 or false to have the toast stay open until
* closed manually. Default: 3000.
* - `position` - `{string=}`: Sets the position of the toast.
* Available: any combination of `'bottom'`, `'left'`, `'top'`, `'right'`, `'end'` and `'start'`.
* The properties `'end'` and `'start'` are dynamic and can be used for RTL support.
* Default combination: `'bottom left'`.
* - `toastClass` - `{string=}`: A class to set on the toast element.
* - `controller` - `{string=}`: The controller to associate with this toast.
* The controller will be injected the local `$mdToast.hide( )`, which is a function
* used to hide the toast.
* - `locals` - `{string=}`: An object containing key/value pairs. The keys will
* be used as names of values to inject into the controller. For example,
* `locals: {three: 3}` would inject `three` into the controller with the value
* of 3.
* - `bindToController` - `bool`: bind the locals to the controller, instead of passing them in.
* - `resolve` - `{object=}`: Similar to locals, except it takes promises as values
* and the toast will not open until the promises resolve.
* - `controllerAs` - `{string=}`: An alias to assign the controller to on the scope.
* - `parent` - `{element=}`: The element to append the toast to. Defaults to appending
* to the root element of the application.
*
* @returns {promise} A promise that can be resolved with `$mdToast.hide()` or
* rejected with `$mdToast.cancel()`. `$mdToast.hide()` will resolve either with a Boolean
* value == 'true' or the value passed as an argument to `$mdToast.hide()`.
* And `$mdToast.cancel()` will resolve the promise with a Boolean value == 'false'
*/
/**
* @ngdoc method
* @name $mdToast#hide
*
* @description
* Hide an existing toast and resolve the promise returned from `$mdToast.show()`.
*
* @param {*=} response An argument for the resolved promise.
*
* @returns {promise} a promise that is called when the existing element is removed from the DOM.
* The promise is resolved with either a Boolean value == 'true' or the value passed as the
* argument to `.hide()`.
*
*/
/**
* @ngdoc method
* @name $mdToast#cancel
*
* @description
* `DEPRECATED` - The promise returned from opening a toast is used only to notify about the closing of the toast.
* As such, there isn't any reason to also allow that promise to be rejected,
* since it's not clear what the difference between resolve and reject would be.
*
* Hide the existing toast and reject the promise returned from
* `$mdToast.show()`.
*
* @param {*=} response An argument for the rejected promise.
*
* @returns {promise} a promise that is called when the existing element is removed from the DOM
* The promise is resolved with a Boolean value == 'false'.
*
*/
function MdToastProvider($$interimElementProvider) {
// Differentiate promise resolves: hide timeout (value == true) and hide action clicks (value == ok).
MdToastController.$inject = ["$mdToast", "$scope"];
toastDefaultOptions.$inject = ["$animate", "$mdToast", "$mdUtil", "$mdMedia"];
var ACTION_RESOLVE = 'ok';
var activeToastContent;
var $mdToast = $$interimElementProvider('$mdToast')
.setDefaults({
methods: ['position', 'hideDelay', 'capsule', 'parent', 'position', 'toastClass'],
options: toastDefaultOptions
})
.addPreset('simple', {
argOption: 'textContent',
methods: ['textContent', 'content', 'action', 'highlightAction', 'highlightClass', 'theme', 'parent' ],
options: /* @ngInject */ ["$mdToast", "$mdTheming", function($mdToast, $mdTheming) {
return {
template:
'
' +
' ' +
' ' +
' {{ toast.content }}' +
' ' +
' ' +
' {{ toast.action }}' +
' ' +
'
' +
'',
controller: MdToastController,
theme: $mdTheming.defaultTheme(),
controllerAs: 'toast',
bindToController: true
};
}]
})
.addMethod('updateTextContent', updateTextContent)
.addMethod('updateContent', updateTextContent);
function updateTextContent(newContent) {
activeToastContent = newContent;
}
return $mdToast;
/**
* Controller for the Toast interim elements.
* @ngInject
*/
function MdToastController($mdToast, $scope) {
// For compatibility with AngularJS 1.6+, we should always use the $onInit hook in
// interimElements. The $mdCompiler simulates the $onInit hook for all versions.
this.$onInit = function() {
var self = this;
if (self.highlightAction) {
$scope.highlightClasses = [
'md-highlight',
self.highlightClass
];
}
$scope.$watch(function() { return activeToastContent; }, function() {
self.content = activeToastContent;
});
this.resolve = function() {
$mdToast.hide( ACTION_RESOLVE );
};
};
}
/* @ngInject */
function toastDefaultOptions($animate, $mdToast, $mdUtil, $mdMedia) {
var SWIPE_EVENTS = '$md.swipeleft $md.swiperight $md.swipeup $md.swipedown';
return {
onShow: onShow,
onRemove: onRemove,
toastClass: '',
position: 'bottom left',
themable: true,
hideDelay: 3000,
autoWrap: true,
transformTemplate: function(template, options) {
var shouldAddWrapper = options.autoWrap && template && !/md-toast-content/g.test(template);
if (shouldAddWrapper) {
// Root element of template will be
. We need to wrap all of its content inside of
// of . All templates provided here should be static, developer-controlled
// content (meaning we're not attempting to guard against XSS).
var templateRoot = document.createElement('md-template');
templateRoot.innerHTML = template;
// Iterate through all root children, to detect possible md-toast directives.
for (var i = 0; i < templateRoot.children.length; i++) {
if (templateRoot.children[i].nodeName === 'MD-TOAST') {
var wrapper = angular.element('
');
// Wrap the children of the `md-toast` directive in jqLite, to be able to append multiple
// nodes with the same execution.
wrapper.append(angular.element(templateRoot.children[i].childNodes));
// Append the new wrapped element to the `md-toast` directive.
templateRoot.children[i].appendChild(wrapper[0]);
}
}
// We have to return the innerHTMl, because we do not want to have the `md-template` element to be
// the root element of our interimElement.
return templateRoot.innerHTML;
}
return template || '';
}
};
function onShow(scope, element, options) {
activeToastContent = options.textContent || options.content; // support deprecated #content method
var isSmScreen = !$mdMedia('gt-sm');
element = $mdUtil.extractElementByName(element, 'md-toast', true);
options.element = element;
options.onSwipe = function(ev, gesture) {
//Add the relevant swipe class to the element so it can animate correctly
var swipe = ev.type.replace('$md.','');
var direction = swipe.replace('swipe', '');
// If the swipe direction is down/up but the toast came from top/bottom don't fade away
// Unless the screen is small, then the toast always on bottom
if ((direction === 'down' && options.position.indexOf('top') != -1 && !isSmScreen) ||
(direction === 'up' && (options.position.indexOf('bottom') != -1 || isSmScreen))) {
return;
}
if ((direction === 'left' || direction === 'right') && isSmScreen) {
return;
}
element.addClass('md-' + swipe);
$mdUtil.nextTick($mdToast.cancel);
};
options.openClass = toastOpenClass(options.position);
element.addClass(options.toastClass);
// 'top left' -> 'md-top md-left'
options.parent.addClass(options.openClass);
// static is the default position
if ($mdUtil.hasComputedStyle(options.parent, 'position', 'static')) {
options.parent.css('position', 'relative');
}
element.on(SWIPE_EVENTS, options.onSwipe);
element.addClass(isSmScreen ? 'md-bottom' : options.position.split(' ').map(function(pos) {
return 'md-' + pos;
}).join(' '));
if (options.parent) options.parent.addClass('md-toast-animating');
return $animate.enter(element, options.parent).then(function() {
if (options.parent) options.parent.removeClass('md-toast-animating');
});
}
function onRemove(scope, element, options) {
element.off(SWIPE_EVENTS, options.onSwipe);
if (options.parent) options.parent.addClass('md-toast-animating');
if (options.openClass) options.parent.removeClass(options.openClass);
return ((options.$destroy == true) ? element.remove() : $animate.leave(element))
.then(function () {
if (options.parent) options.parent.removeClass('md-toast-animating');
if ($mdUtil.hasComputedStyle(options.parent, 'position', 'static')) {
options.parent.css('position', '');
}
});
}
function toastOpenClass(position) {
// For mobile, always open full-width on bottom
if (!$mdMedia('gt-xs')) {
return 'md-toast-open-bottom';
}
return 'md-toast-open-' +
(position.indexOf('top') > -1 ? 'top' : 'bottom');
}
}
}
})();
(function(){
"use strict";
/**
* @ngdoc module
* @name material.components.toolbar
*/
mdToolbarDirective.$inject = ["$$rAF", "$mdConstant", "$mdUtil", "$mdTheming", "$animate"];
angular.module('material.components.toolbar', [
'material.core',
'material.components.content'
])
.directive('mdToolbar', mdToolbarDirective);
/**
* @ngdoc directive
* @name mdToolbar
* @module material.components.toolbar
* @restrict E
* @description
* `md-toolbar` is used to place a toolbar in your app.
*
* Toolbars are usually used above a content area to display the title of the
* current page, and show relevant action buttons for that page.
*
* You can change the height of the toolbar by adding either the
* `md-medium-tall` or `md-tall` class to the toolbar.
*
* @usage
*
*
*
*
*
*
My App's Title
*
*
* Right Bar Button
*
*
*
*
*
* Hello!
*
*
*
*
*
Note: The code above shows usage with the `md-truncate` component which provides an
* ellipsis if the title is longer than the width of the Toolbar.
*
* ## CSS & Styles
*
* The `
` provides a few custom CSS classes that you may use to enhance the
* functionality of your toolbar.
*
*
*
*
*
* The `md-toolbar-tools` class provides quite a bit of automatic styling for your toolbar
* buttons and text. When applied, it will center the buttons and text vertically for you.
*
*
*
*
*
* ### Private Classes
*
* Currently, the only private class is the `md-toolbar-transitions` class. All other classes are
* considered public.
*
* @param {boolean=} md-scroll-shrink Whether the header should shrink away as
* the user scrolls down, and reveal itself as the user scrolls up.
*
* _**Note (1):** for scrollShrink to work, the toolbar must be a sibling of a
* `md-content` element, placed before it. See the scroll shrink demo._
*
* _**Note (2):** The `md-scroll-shrink` attribute is only parsed on component
* initialization, it does not watch for scope changes._
*
*
* @param {number=} md-shrink-speed-factor How much to change the speed of the toolbar's
* shrinking by. For example, if 0.25 is given then the toolbar will shrink
* at one fourth the rate at which the user scrolls down. Default 0.5.
*
*/
function mdToolbarDirective($$rAF, $mdConstant, $mdUtil, $mdTheming, $animate) {
var translateY = angular.bind(null, $mdUtil.supplant, 'translate3d(0,{0}px,0)');
return {
template: '',
restrict: 'E',
link: function(scope, element, attr) {
element.addClass('_md'); // private md component indicator for styling
$mdTheming(element);
$mdUtil.nextTick(function () {
element.addClass('_md-toolbar-transitions'); // adding toolbar transitions after digest
}, false);
if (angular.isDefined(attr.mdScrollShrink)) {
setupScrollShrink();
}
function setupScrollShrink() {
var toolbarHeight;
var contentElement;
var disableScrollShrink = angular.noop;
// Current "y" position of scroll
// Store the last scroll top position
var y = 0;
var prevScrollTop = 0;
var shrinkSpeedFactor = attr.mdShrinkSpeedFactor || 0.5;
var debouncedContentScroll = $$rAF.throttle(onContentScroll);
var debouncedUpdateHeight = $mdUtil.debounce(updateToolbarHeight, 5 * 1000);
// Wait for $mdContentLoaded event from mdContent directive.
// If the mdContent element is a sibling of our toolbar, hook it up
// to scroll events.
scope.$on('$mdContentLoaded', onMdContentLoad);
// If the toolbar is used inside an ng-if statement, we may miss the
// $mdContentLoaded event, so we attempt to fake it if we have a
// md-content close enough.
attr.$observe('mdScrollShrink', onChangeScrollShrink);
// If the toolbar has ngShow or ngHide we need to update height immediately as it changed
// and not wait for $mdUtil.debounce to happen
if (attr.ngShow) { scope.$watch(attr.ngShow, updateToolbarHeight); }
if (attr.ngHide) { scope.$watch(attr.ngHide, updateToolbarHeight); }
// If the scope is destroyed (which could happen with ng-if), make sure
// to disable scroll shrinking again
scope.$on('$destroy', disableScrollShrink);
/**
*
*/
function onChangeScrollShrink(shrinkWithScroll) {
var closestContent = element.parent().find('md-content');
// If we have a content element, fake the call; this might still fail
// if the content element isn't a sibling of the toolbar
if (!contentElement && closestContent.length) {
onMdContentLoad(null, closestContent);
}
// Evaluate the expression
shrinkWithScroll = scope.$eval(shrinkWithScroll);
// Disable only if the attribute's expression evaluates to false
if (shrinkWithScroll === false) {
disableScrollShrink();
} else {
disableScrollShrink = enableScrollShrink();
}
}
/**
*
*/
function onMdContentLoad($event, newContentEl) {
// Toolbar and content must be siblings
if (newContentEl && element.parent()[0] === newContentEl.parent()[0]) {
// unhook old content event listener if exists
if (contentElement) {
contentElement.off('scroll', debouncedContentScroll);
}
contentElement = newContentEl;
disableScrollShrink = enableScrollShrink();
}
}
/**
*
*/
function onContentScroll(e) {
var scrollTop = e ? e.target.scrollTop : prevScrollTop;
debouncedUpdateHeight();
y = Math.min(
toolbarHeight / shrinkSpeedFactor,
Math.max(0, y + scrollTop - prevScrollTop)
);
element.css($mdConstant.CSS.TRANSFORM, translateY([-y * shrinkSpeedFactor]));
contentElement.css($mdConstant.CSS.TRANSFORM, translateY([(toolbarHeight - y) * shrinkSpeedFactor]));
prevScrollTop = scrollTop;
$mdUtil.nextTick(function() {
var hasWhiteFrame = element.hasClass('md-whiteframe-z1');
if (hasWhiteFrame && !y) {
$animate.removeClass(element, 'md-whiteframe-z1');
} else if (!hasWhiteFrame && y) {
$animate.addClass(element, 'md-whiteframe-z1');
}
});
}
/**
*
*/
function enableScrollShrink() {
if (!contentElement) return angular.noop; // no md-content
contentElement.on('scroll', debouncedContentScroll);
contentElement.attr('scroll-shrink', 'true');
$mdUtil.nextTick(updateToolbarHeight, false);
return function disableScrollShrink() {
contentElement.off('scroll', debouncedContentScroll);
contentElement.attr('scroll-shrink', 'false');
updateToolbarHeight();
};
}
/**
*
*/
function updateToolbarHeight() {
toolbarHeight = element.prop('offsetHeight');
// Add a negative margin-top the size of the toolbar to the content el.
// The content will start transformed down the toolbarHeight amount,
// so everything looks normal.
//
// As the user scrolls down, the content will be transformed up slowly
// to put the content underneath where the toolbar was.
var margin = (-toolbarHeight * shrinkSpeedFactor) + 'px';
contentElement.css({
"margin-top": margin,
"margin-bottom": margin
});
onContentScroll();
}
}
}
};
}
})();
(function(){
"use strict";
/**
* @ngdoc module
* @name material.components.tooltip
*/
MdTooltipDirective.$inject = ["$timeout", "$window", "$$rAF", "$document", "$interpolate", "$mdUtil", "$mdPanel", "$$mdTooltipRegistry"];
angular
.module('material.components.tooltip', [
'material.core',
'material.components.panel'
])
.directive('mdTooltip', MdTooltipDirective)
.service('$$mdTooltipRegistry', MdTooltipRegistry);
/**
* @ngdoc directive
* @name mdTooltip
* @module material.components.tooltip
* @description
* Tooltips are used to describe elements that are interactive and primarily
* graphical (not textual).
*
* Place a `` as a child of the element it describes.
*
* A tooltip will activate when the user hovers over, focuses, or touches the
* parent element.
*
* @usage
*
*
* Play Music
*
*
*
*
* @param {number=} md-z-index The visual level that the tooltip will appear
* in comparison with the rest of the elements of the application.
* @param {expression=} md-visible Boolean bound to whether the tooltip is
* currently visible.
* @param {number=} md-delay How many milliseconds to wait to show the tooltip
* after the user hovers over, focuses, or touches the parent element.
* Defaults to 0ms on non-touch devices and 75ms on touch.
* @param {boolean=} md-autohide If present or provided with a boolean value,
* the tooltip will hide on mouse leave, regardless of focus.
* @param {string=} md-direction The direction that the tooltip is shown,
* relative to the parent element. Supports top, right, bottom, and left.
* Defaults to bottom.
*/
function MdTooltipDirective($timeout, $window, $$rAF, $document, $interpolate,
$mdUtil, $mdPanel, $$mdTooltipRegistry) {
var ENTER_EVENTS = 'focus touchstart mouseenter';
var LEAVE_EVENTS = 'blur touchcancel mouseleave';
var TOOLTIP_DEFAULT_Z_INDEX = 100;
var TOOLTIP_DEFAULT_SHOW_DELAY = 0;
var TOOLTIP_DEFAULT_DIRECTION = 'bottom';
var TOOLTIP_DIRECTIONS = {
top: { x: $mdPanel.xPosition.CENTER, y: $mdPanel.yPosition.ABOVE },
right: { x: $mdPanel.xPosition.OFFSET_END, y: $mdPanel.yPosition.CENTER },
bottom: { x: $mdPanel.xPosition.CENTER, y: $mdPanel.yPosition.BELOW },
left: { x: $mdPanel.xPosition.OFFSET_START, y: $mdPanel.yPosition.CENTER }
};
return {
restrict: 'E',
priority: 210, // Before ngAria
scope: {
mdZIndex: '=?mdZIndex',
mdDelay: '=?mdDelay',
mdVisible: '=?mdVisible',
mdAutohide: '=?mdAutohide',
mdDirection: '@?mdDirection' // Do not expect expressions.
},
link: linkFunc
};
function linkFunc(scope, element, attr) {
// Set constants.
var tooltipId = 'md-tooltip-' + $mdUtil.nextUid();
var parent = $mdUtil.getParentWithPointerEvents(element);
var debouncedOnResize = $$rAF.throttle(updatePosition);
var mouseActive = false;
var origin, position, panelPosition, panelRef, autohide, showTimeout,
elementFocusedOnWindowBlur = null;
// Set defaults
setDefaults();
// Set parent aria-label.
addAriaLabel();
// Remove the element from its current DOM position.
element.detach();
updatePosition();
bindEvents();
configureWatchers();
function setDefaults() {
scope.mdZIndex = scope.mdZIndex || TOOLTIP_DEFAULT_Z_INDEX;
scope.mdDelay = scope.mdDelay || TOOLTIP_DEFAULT_SHOW_DELAY;
if (!TOOLTIP_DIRECTIONS[scope.mdDirection]) {
scope.mdDirection = TOOLTIP_DEFAULT_DIRECTION;
}
}
function addAriaLabel(labelText) {
// Only interpolate the text from the HTML element because otherwise the custom text could
// be interpolated twice and cause XSS violations.
var interpolatedText = labelText || $interpolate(element.text().trim())(scope.$parent);
// Only add the `aria-label` to the parent if there isn't already one, if there isn't an
// already present `aria-labelledby`, or if the previous `aria-label` was added by the
// tooltip directive.
if (
(!parent.attr('aria-label') && !parent.attr('aria-labelledby')) ||
parent.attr('md-labeled-by-tooltip')
) {
parent.attr('aria-label', interpolatedText);
// Set the `md-labeled-by-tooltip` attribute if it has not already been set.
if (!parent.attr('md-labeled-by-tooltip')) {
parent.attr('md-labeled-by-tooltip', tooltipId);
}
}
}
function updatePosition() {
setDefaults();
// If the panel has already been created, remove the current origin
// class from the panel element.
if (panelRef && panelRef.panelEl) {
panelRef.panelEl.removeClass(origin);
}
// Set the panel element origin class based off of the current
// mdDirection.
origin = 'md-origin-' + scope.mdDirection;
// Create the position of the panel based off of the mdDirection.
position = TOOLTIP_DIRECTIONS[scope.mdDirection];
// Using the newly created position object, use the MdPanel
// panelPosition API to build the panel's position.
panelPosition = $mdPanel.newPanelPosition()
.relativeTo(parent)
.addPanelPosition(position.x, position.y);
// If the panel has already been created, add the new origin class to
// the panel element and update it's position with the panelPosition.
if (panelRef && panelRef.panelEl) {
panelRef.panelEl.addClass(origin);
panelRef.updatePosition(panelPosition);
}
}
function bindEvents() {
// Add a mutationObserver where there is support for it and the need
// for it in the form of viable host(parent[0]).
if (parent[0] && 'MutationObserver' in $window) {
// Use a mutationObserver to tackle #2602.
var attributeObserver = new MutationObserver(function(mutations) {
if (isDisabledMutation(mutations)) {
$mdUtil.nextTick(function() {
setVisible(false);
});
}
});
attributeObserver.observe(parent[0], {
attributes: true
});
}
elementFocusedOnWindowBlur = false;
$$mdTooltipRegistry.register('scroll', windowScrollEventHandler, true);
$$mdTooltipRegistry.register('blur', windowBlurEventHandler);
$$mdTooltipRegistry.register('resize', debouncedOnResize);
scope.$on('$destroy', onDestroy);
// To avoid 'synthetic clicks', we listen to mousedown instead of
// 'click'.
parent.on('mousedown', mousedownEventHandler);
parent.on(ENTER_EVENTS, enterEventHandler);
function isDisabledMutation(mutations) {
mutations.some(function(mutation) {
return mutation.attributeName === 'disabled' && parent[0].disabled;
});
return false;
}
function windowScrollEventHandler() {
setVisible(false);
}
function windowBlurEventHandler() {
elementFocusedOnWindowBlur = document.activeElement === parent[0];
}
function enterEventHandler($event) {
// Prevent the tooltip from showing when the window is receiving
// focus.
if ($event.type === 'focus' && elementFocusedOnWindowBlur) {
elementFocusedOnWindowBlur = false;
} else if (!scope.mdVisible) {
parent.on(LEAVE_EVENTS, leaveEventHandler);
setVisible(true);
// If the user is on a touch device, we should bind the tap away
// after the 'touched' in order to prevent the tooltip being
// removed immediately.
if ($event.type === 'touchstart') {
parent.one('touchend', function() {
$mdUtil.nextTick(function() {
$document.one('touchend', leaveEventHandler);
}, false);
});
}
}
}
function leaveEventHandler() {
autohide = scope.hasOwnProperty('mdAutohide') ?
scope.mdAutohide :
attr.hasOwnProperty('mdAutohide');
if (autohide || mouseActive ||
$document[0].activeElement !== parent[0]) {
// When a show timeout is currently in progress, then we have
// to cancel it, otherwise the tooltip will remain showing
// without focus or hover.
if (showTimeout) {
$timeout.cancel(showTimeout);
setVisible.queued = false;
showTimeout = null;
}
parent.off(LEAVE_EVENTS, leaveEventHandler);
parent.triggerHandler('blur');
setVisible(false);
}
mouseActive = false;
}
function mousedownEventHandler() {
mouseActive = true;
}
function onDestroy() {
$$mdTooltipRegistry.deregister('scroll', windowScrollEventHandler, true);
$$mdTooltipRegistry.deregister('blur', windowBlurEventHandler);
$$mdTooltipRegistry.deregister('resize', debouncedOnResize);
parent
.off(ENTER_EVENTS, enterEventHandler)
.off(LEAVE_EVENTS, leaveEventHandler)
.off('mousedown', mousedownEventHandler);
// Trigger the handler in case any of the tooltips are
// still visible.
leaveEventHandler();
attributeObserver && attributeObserver.disconnect();
}
}
function configureWatchers() {
if (element[0] && 'MutationObserver' in $window) {
var attributeObserver = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.attributeName === 'md-visible' &&
!scope.visibleWatcher ) {
scope.visibleWatcher = scope.$watch('mdVisible',
onVisibleChanged);
}
});
});
attributeObserver.observe(element[0], {
attributes: true
});
// Build watcher only if mdVisible is being used.
if (attr.hasOwnProperty('mdVisible')) {
scope.visibleWatcher = scope.$watch('mdVisible',
onVisibleChanged);
}
} else {
// MutationObserver not supported
scope.visibleWatcher = scope.$watch('mdVisible', onVisibleChanged);
}
// Direction watcher
scope.$watch('mdDirection', updatePosition);
// Clean up if the element or parent was removed via jqLite's .remove.
// A couple of notes:
// - In these cases the scope might not have been destroyed, which
// is why we destroy it manually. An example of this can be having
// `md-visible="false"` and adding tooltips while they're
// invisible. If `md-visible` becomes true, at some point, you'd
// usually get a lot of tooltips.
// - We use `.one`, not `.on`, because this only needs to fire once.
// If we were using `.on`, it would get thrown into an infinite
// loop.
// - This kicks off the scope's `$destroy` event which finishes the
// cleanup.
element.one('$destroy', onElementDestroy);
parent.one('$destroy', onElementDestroy);
scope.$on('$destroy', function() {
setVisible(false);
panelRef && panelRef.destroy();
attributeObserver && attributeObserver.disconnect();
element.remove();
});
// Updates the aria-label when the element text changes. This watch
// doesn't need to be set up if the element doesn't have any data
// bindings.
if (element.text().indexOf($interpolate.startSymbol()) > -1) {
scope.$watch(function() {
return element.text().trim();
}, addAriaLabel);
}
function onElementDestroy() {
scope.$destroy();
}
}
function setVisible(value) {
// Break if passed value is already in queue or there is no queue and
// passed value is current in the controller.
if (setVisible.queued && setVisible.value === !!value ||
!setVisible.queued && scope.mdVisible === !!value) {
return;
}
setVisible.value = !!value;
if (!setVisible.queued) {
if (value) {
setVisible.queued = true;
showTimeout = $timeout(function() {
scope.mdVisible = setVisible.value;
setVisible.queued = false;
showTimeout = null;
if (!scope.visibleWatcher) {
onVisibleChanged(scope.mdVisible);
}
}, scope.mdDelay);
} else {
$mdUtil.nextTick(function() {
scope.mdVisible = false;
if (!scope.visibleWatcher) {
onVisibleChanged(false);
}
});
}
}
}
function onVisibleChanged(isVisible) {
isVisible ? showTooltip() : hideTooltip();
}
function showTooltip() {
// Do not show the tooltip if the text is empty.
if (!element[0].textContent.trim()) {
throw new Error('Text for the tooltip has not been provided. ' +
'Please include text within the mdTooltip element.');
}
if (!panelRef) {
var attachTo = angular.element(document.body);
var panelAnimation = $mdPanel.newPanelAnimation()
.openFrom(parent)
.closeTo(parent)
.withAnimation({
open: 'md-show',
close: 'md-hide'
});
var panelConfig = {
id: tooltipId,
attachTo: attachTo,
contentElement: element,
propagateContainerEvents: true,
panelClass: 'md-tooltip',
animation: panelAnimation,
position: panelPosition,
zIndex: scope.mdZIndex,
focusOnOpen: false,
onDomAdded: function() {
panelRef.panelEl.addClass(origin);
}
};
panelRef = $mdPanel.create(panelConfig);
}
panelRef.open().then(function() {
panelRef.panelEl.attr('role', 'tooltip');
});
}
function hideTooltip() {
panelRef && panelRef.close();
}
}
}
/**
* Service that is used to reduce the amount of listeners that are being
* registered on the `window` by the tooltip component. Works by collecting
* the individual event handlers and dispatching them from a global handler.
*
* @ngInject
*/
function MdTooltipRegistry() {
var listeners = {};
var ngWindow = angular.element(window);
return {
register: register,
deregister: deregister
};
/**
* Global event handler that dispatches the registered handlers in the
* service.
* @param {!Event} event Event object passed in by the browser
*/
function globalEventHandler(event) {
if (listeners[event.type]) {
listeners[event.type].forEach(function(currentHandler) {
currentHandler.call(this, event);
}, this);
}
}
/**
* Registers a new handler with the service.
* @param {string} type Type of event to be registered.
* @param {!Function} handler Event handler.
* @param {boolean} useCapture Whether to use event capturing.
*/
function register(type, handler, useCapture) {
var handlers = listeners[type] = listeners[type] || [];
if (!handlers.length) {
useCapture ? window.addEventListener(type, globalEventHandler, true) :
ngWindow.on(type, globalEventHandler);
}
if (handlers.indexOf(handler) === -1) {
handlers.push(handler);
}
}
/**
* Removes an event handler from the service.
* @param {string} type Type of event handler.
* @param {!Function} handler The event handler itself.
* @param {boolean} useCapture Whether the event handler used event capturing.
*/
function deregister(type, handler, useCapture) {
var handlers = listeners[type];
var index = handlers ? handlers.indexOf(handler) : -1;
if (index > -1) {
handlers.splice(index, 1);
if (handlers.length === 0) {
useCapture ? window.removeEventListener(type, globalEventHandler, true) :
ngWindow.off(type, globalEventHandler);
}
}
}
}
})();
(function(){
"use strict";
/**
* @ngdoc module
* @name material.components.truncate
*/
MdTruncateController.$inject = ["$element"];
angular.module('material.components.truncate', ['material.core'])
.directive('mdTruncate', MdTruncateDirective);
/**
* @ngdoc directive
* @name mdTruncate
* @module material.components.truncate
* @restrict AE
* @description
*
* The `md-truncate` component displays a label that will automatically clip text which is wider
* than the component. By default, it displays an ellipsis, but you may apply the `md-clip` CSS
* class to override this default and use a standard "clipping" approach.
*
* Note: The `md-truncate` component does not automatically adjust it's width. You must
* provide the `flex` attribute, or some other CSS-based width management. See the
* demos for examples.
*
* @usage
*
* ### As an Element
*
*
*
* Back
*
* Chapter 1 - The Way of the Old West
*
* Forward
*
*
*
* ### As an Attribute
*
*
* Some Title With a Lot of Text
*
*
* ## CSS & Styles
*
* `` provides two CSS classes that you may use to control the type of clipping.
*
* Note: The `md-truncate` also applies a setting of `width: 0;` when used with the `flex`
* attribute to fix an issue with the flex element not shrinking properly.
*
*
*
*
*
* Assigns the "ellipsis" behavior (default) which will cut off mid-word and append an ellipsis
* (…) to the end of the text.
*
*
*
* Assigns the "clipping" behavior which will simply chop off the text. This may happen
* mid-word or even mid-character.
*
*
*
*
*/
function MdTruncateDirective() {
return {
restrict: 'AE',
controller: MdTruncateController
};
}
/**
* Controller for the component.
*
* @param $element The md-truncate element.
*
* @constructor
* @ngInject
*/
function MdTruncateController($element) {
$element.addClass('md-truncate');
}
})();
(function(){
"use strict";
/**
* @ngdoc module
* @name material.components.virtualRepeat
*/
VirtualRepeatContainerController.$inject = ["$$rAF", "$mdUtil", "$mdConstant", "$parse", "$rootScope", "$window", "$scope", "$element", "$attrs"];
VirtualRepeatController.$inject = ["$scope", "$element", "$attrs", "$browser", "$document", "$rootScope", "$$rAF", "$mdUtil"];
VirtualRepeatDirective.$inject = ["$parse"];
angular.module('material.components.virtualRepeat', [
'material.core',
'material.components.showHide'
])
.directive('mdVirtualRepeatContainer', VirtualRepeatContainerDirective)
.directive('mdVirtualRepeat', VirtualRepeatDirective)
.directive('mdForceHeight', ForceHeightDirective);
/**
* @ngdoc directive
* @name mdVirtualRepeatContainer
* @module material.components.virtualRepeat
* @restrict E
* @description
* `md-virtual-repeat-container` provides the scroll container for
* md-virtual-repeat.
*
* VirtualRepeat is a limited substitute for `ng-repeat` that renders only
* enough DOM nodes to fill the container, recycling them as the user scrolls.
*
* Once an element is not visible anymore, the Virtual Repeat recycles the element and reuses it
* for another visible item by replacing the previous data set with the set of currently visible
* elements.
*
* ### Common Issues
*
* - When having one-time bindings inside of the view template, the Virtual Repeat will not properly
* update the bindings for new items, since the view will be recycled.
* - Directives inside of a Virtual Repeat will be only compiled (linked) once, because those
* items will be recycled and used for other items.
* The Virtual Repeat just updates the scope bindings.
*
*
* ### Notes
*
* > The VirtualRepeat is a similar implementation to the Android
* [RecyclerView](https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html).
*
*
*
* > Please also review the mdVirtualRepeat
* documentation for more information.
*
*
* @usage
*
*
*
* Hello {{i}}!
*
*
*
* @param {boolean=} md-auto-shrink When present and the container will shrink to fit
* the number of items in the `md-virtual-repeat`.
* @param {number=} md-auto-shrink-min Minimum number of items that md-auto-shrink
* will shrink to. Default: `0`.
* @param {boolean=} md-orient-horizontal Whether the container should scroll horizontally.
* The default is `false` which indicates vertical orientation and scrolling.
* @param {number=} md-top-index Binds the index of the item that is at the top of the scroll
* container to `$scope`. It can both read and set the scroll position.
*/
function VirtualRepeatContainerDirective() {
return {
controller: VirtualRepeatContainerController,
template: virtualRepeatContainerTemplate,
compile: function virtualRepeatContainerCompile($element, $attrs) {
$element
.addClass('md-virtual-repeat-container')
.addClass($attrs.hasOwnProperty('mdOrientHorizontal')
? 'md-orient-horizontal'
: 'md-orient-vertical');
}
};
}
function virtualRepeatContainerTemplate($element) {
return '';
}
/**
* Number of additional elements to render above and below the visible area inside
* of the virtual repeat container. A higher number results in less flicker when scrolling
* very quickly in Safari, but comes with a higher rendering and dirty-checking cost.
* @const {number}
*/
var NUM_EXTRA = 3;
/** @ngInject */
function VirtualRepeatContainerController($$rAF, $mdUtil, $mdConstant, $parse, $rootScope, $window, $scope,
$element, $attrs) {
this.$rootScope = $rootScope;
this.$scope = $scope;
this.$element = $element;
this.$attrs = $attrs;
/** @type {number} The width or height of the container */
this.size = 0;
/** @type {number} The scroll width or height of the scroller */
this.scrollSize = 0;
/** @type {number} The scrollLeft or scrollTop of the scroller */
this.scrollOffset = 0;
/** @type {boolean} Whether the scroller is oriented horizontally */
this.horizontal = this.$attrs.hasOwnProperty('mdOrientHorizontal');
/** @type {!VirtualRepeatController} The repeater inside of this container */
this.repeater = null;
/** @type {boolean} Whether auto-shrink is enabled */
this.autoShrink = this.$attrs.hasOwnProperty('mdAutoShrink');
/** @type {number} Minimum number of items to auto-shrink to */
this.autoShrinkMin = parseInt(this.$attrs.mdAutoShrinkMin, 10) || 0;
/** @type {?number} Original container size when shrank */
this.originalSize = null;
/** @type {number} Amount to offset the total scroll size by. */
this.offsetSize = parseInt(this.$attrs.mdOffsetSize, 10) || 0;
/** @type {?string} height or width element style on the container prior to auto-shrinking. */
this.oldElementSize = null;
/** @type {!number} Maximum amount of pixels allowed for a single DOM element */
this.maxElementPixels = $mdConstant.ELEMENT_MAX_PIXELS;
if (this.$attrs.mdTopIndex) {
/** @type {function(angular.Scope): number} Binds to topIndex on AngularJS scope */
this.bindTopIndex = $parse(this.$attrs.mdTopIndex);
/** @type {number} The index of the item that is at the top of the scroll container */
this.topIndex = this.bindTopIndex(this.$scope);
if (!angular.isDefined(this.topIndex)) {
this.topIndex = 0;
this.bindTopIndex.assign(this.$scope, 0);
}
this.$scope.$watch(this.bindTopIndex, angular.bind(this, function(newIndex) {
if (newIndex !== this.topIndex) {
this.scrollToIndex(newIndex);
}
}));
} else {
this.topIndex = 0;
}
this.scroller = $element[0].querySelector('.md-virtual-repeat-scroller');
this.sizer = this.scroller.querySelector('.md-virtual-repeat-sizer');
this.offsetter = this.scroller.querySelector('.md-virtual-repeat-offsetter');
// After the DOM stabilizes, measure the initial size of the container and
// make a best effort at re-measuring as it changes.
var boundUpdateSize = angular.bind(this, this.updateSize);
$$rAF(angular.bind(this, function() {
boundUpdateSize();
var debouncedUpdateSize = $mdUtil.debounce(boundUpdateSize, 10, null, false);
var jWindow = angular.element($window);
// Make one more attempt to get the size if it is 0.
// This is not by any means a perfect approach, but there's really no
// silver bullet here.
if (!this.size) {
debouncedUpdateSize();
}
jWindow.on('resize', debouncedUpdateSize);
$scope.$on('$destroy', function() {
jWindow.off('resize', debouncedUpdateSize);
});
$scope.$emit('$md-resize-enable');
$scope.$on('$md-resize', boundUpdateSize);
}));
}
/** Called by the md-virtual-repeat inside of the container at startup. */
VirtualRepeatContainerController.prototype.register = function(repeaterCtrl) {
this.repeater = repeaterCtrl;
angular.element(this.scroller)
.on('scroll wheel touchmove touchend', angular.bind(this, this.handleScroll_));
};
/** @return {boolean} Whether the container is configured for horizontal scrolling. */
VirtualRepeatContainerController.prototype.isHorizontal = function() {
return this.horizontal;
};
/** @return {number} The size (width or height) of the container. */
VirtualRepeatContainerController.prototype.getSize = function() {
return this.size;
};
/**
* Resizes the container.
* @private
* @param {number} size The new size to set.
*/
VirtualRepeatContainerController.prototype.setSize_ = function(size) {
var dimension = this.getDimensionName_();
this.size = size;
this.$element[0].style[dimension] = size + 'px';
};
VirtualRepeatContainerController.prototype.unsetSize_ = function() {
this.$element[0].style[this.getDimensionName_()] = this.oldElementSize;
this.oldElementSize = null;
};
/** Instructs the container to re-measure its size. */
VirtualRepeatContainerController.prototype.updateSize = function() {
// If the original size is already determined, we can skip the update.
if (this.originalSize) return;
this.size = this.isHorizontal()
? this.$element[0].clientWidth
: this.$element[0].clientHeight;
// Recheck the scroll position after updating the size. This resolves
// problems that can result if the scroll position was measured while the
// element was display: none or detached from the document.
this.handleScroll_();
this.repeater && this.repeater.containerUpdated();
};
/** @return {number} The container's scrollHeight or scrollWidth. */
VirtualRepeatContainerController.prototype.getScrollSize = function() {
return this.scrollSize;
};
VirtualRepeatContainerController.prototype.getDimensionName_ = function() {
return this.isHorizontal() ? 'width' : 'height';
};
/**
* Sets the scroller element to the specified size.
* @private
* @param {number} size The new size.
*/
VirtualRepeatContainerController.prototype.sizeScroller_ = function(size) {
var dimension = this.getDimensionName_();
var crossDimension = this.isHorizontal() ? 'height' : 'width';
// Clear any existing dimensions.
this.sizer.innerHTML = '';
// If the size falls within the browser's maximum explicit size for a single element, we can
// set the size and be done. Otherwise, we have to create children that add up the the desired
// size.
if (size < this.maxElementPixels) {
this.sizer.style[dimension] = size + 'px';
} else {
this.sizer.style[dimension] = 'auto';
this.sizer.style[crossDimension] = 'auto';
// Divide the total size we have to render into N max-size pieces.
var numChildren = Math.floor(size / this.maxElementPixels);
// Element template to clone for each max-size piece.
var sizerChild = document.createElement('div');
sizerChild.style[dimension] = this.maxElementPixels + 'px';
sizerChild.style[crossDimension] = '1px';
for (var i = 0; i < numChildren; i++) {
this.sizer.appendChild(sizerChild.cloneNode(false));
}
// Re-use the element template for the remainder.
sizerChild.style[dimension] = (size - (numChildren * this.maxElementPixels)) + 'px';
this.sizer.appendChild(sizerChild);
}
};
/**
* If auto-shrinking is enabled, shrinks or unshrinks as appropriate.
* @private
* @param {number} size The new size.
*/
VirtualRepeatContainerController.prototype.autoShrink_ = function(size) {
var shrinkSize = Math.max(size, this.autoShrinkMin * this.repeater.getItemSize());
if (this.autoShrink && shrinkSize !== this.size) {
if (this.oldElementSize === null) {
this.oldElementSize = this.$element[0].style[this.getDimensionName_()];
}
var currentSize = this.originalSize || this.size;
if (!currentSize || shrinkSize < currentSize) {
if (!this.originalSize) {
this.originalSize = this.size;
}
// Now we update the containers size, because shrinking is enabled.
this.setSize_(shrinkSize);
} else if (this.originalSize !== null) {
// Set the size back to our initial size.
this.unsetSize_();
var _originalSize = this.originalSize;
this.originalSize = null;
// We determine the repeaters size again, if the original size was zero.
// The originalSize needs to be null, to be able to determine the size.
if (!_originalSize) this.updateSize();
// Apply the original size or the determined size back to the container, because
// it has been overwritten before, in the shrink block.
this.setSize_(_originalSize || this.size);
}
this.repeater.containerUpdated();
}
};
/**
* Sets the scrollHeight or scrollWidth. Called by the repeater based on
* its item count and item size.
* @param {number} itemsSize The total size of the items.
*/
VirtualRepeatContainerController.prototype.setScrollSize = function(itemsSize) {
var size = itemsSize + this.offsetSize;
if (this.scrollSize === size) return;
this.sizeScroller_(size);
this.autoShrink_(size);
this.scrollSize = size;
};
/** @return {number} The container's current scroll offset. */
VirtualRepeatContainerController.prototype.getScrollOffset = function() {
return this.scrollOffset;
};
/**
* Scrolls to a given scrollTop position.
* @param {number} position
*/
VirtualRepeatContainerController.prototype.scrollTo = function(position) {
this.scroller[this.isHorizontal() ? 'scrollLeft' : 'scrollTop'] = position;
this.handleScroll_();
};
/**
* Scrolls the item with the given index to the top of the scroll container.
* @param {number} index
*/
VirtualRepeatContainerController.prototype.scrollToIndex = function(index) {
var itemSize = this.repeater.getItemSize();
var itemsLength = this.repeater.itemsLength;
if(index > itemsLength) {
index = itemsLength - 1;
}
this.scrollTo(itemSize * index);
};
VirtualRepeatContainerController.prototype.resetScroll = function() {
this.scrollTo(0);
};
VirtualRepeatContainerController.prototype.handleScroll_ = function() {
var ltr = document.dir != 'rtl' && document.body.dir != 'rtl';
if(!ltr && !this.maxSize) {
this.scroller.scrollLeft = this.scrollSize;
this.maxSize = this.scroller.scrollLeft;
}
var offset = this.isHorizontal() ?
(ltr?this.scroller.scrollLeft : this.maxSize - this.scroller.scrollLeft)
: this.scroller.scrollTop;
if (offset === this.scrollOffset || offset > this.scrollSize - this.size) return;
var itemSize = this.repeater.getItemSize();
if (!itemSize) return;
var numItems = Math.max(0, Math.floor(offset / itemSize) - NUM_EXTRA);
var transform = (this.isHorizontal() ? 'translateX(' : 'translateY(') +
(!this.isHorizontal() || ltr ? (numItems * itemSize) : - (numItems * itemSize)) + 'px)';
this.scrollOffset = offset;
this.offsetter.style.webkitTransform = transform;
this.offsetter.style.transform = transform;
if (this.bindTopIndex) {
var topIndex = Math.floor(offset / itemSize);
if (topIndex !== this.topIndex && topIndex < this.repeater.getItemCount()) {
this.topIndex = topIndex;
this.bindTopIndex.assign(this.$scope, topIndex);
if (!this.$rootScope.$$phase) this.$scope.$digest();
}
}
this.repeater.containerUpdated();
};
/**
* @ngdoc directive
* @name mdVirtualRepeat
* @module material.components.virtualRepeat
* @restrict A
* @priority 1000
* @description
* The `md-virtual-repeat` attribute is applied to a template that is repeated using virtual
* scrolling. This provides smooth and performant scrolling through very large lists of elements.
*
* Virtual repeat is a limited substitute for `ng-repeat` that renders only
* enough DOM nodes to fill the container, recycling them as the user scrolls.
*
* ### Notes
*
* - Arrays are supported for iteration by default.
* - An object can used use if `md-on-demand` is specified and the object implements the interface
* described in the `md-on-demand` documentation.
* - `trackBy`, `as` alias, and `(key, value)` syntax from `ng-repeat` are not supported.
*
* ### On-Demand Async Item Loading
*
* When using the `md-on-demand` attribute and loading some asynchronous data,
* the `getItemAtIndex` function will mostly return nothing.
*
*
* DynamicItems.prototype.getItemAtIndex = function(index) {
* if (this.pages[index]) {
* return this.pages[index];
* } else {
* // This is an asynchronous action and does not return any value.
* this.loadPage(index);
* }
* };
*
*
* This means that the Virtual Repeat will not have any value for the given index.
* After the data loading completes, the user expects the Virtual Repeat to recognize the change.
*
* To make sure that the Virtual Repeat properly detects any change, you need to run the operation
* in another digest.
*
*
* DynamicItems.prototype.loadPage = function(index) {
* var self = this;
*
* // Trigger a new digest by using $timeout
* $timeout(function() {
* self.pages[index] = Data;
* });
* };
*
*
* > Note: Please also review the
* VirtualRepeatContainer documentation
* for more information.
*
* @usage
*
*
* Hello {{i}}!
*
*
*
* Hello {{i}}!
*
*
*
* @param {expression=} md-extra-name Evaluates to an additional name to which the current iterated item
* can be assigned on the repeated scope (needed for use in `md-autocomplete`).
* @param {number=} md-item-size Optional height or width of the repeated elements (which **must be
* identical for each element**). Virtual repeat will attempt to read the size from the DOM,
* if missing, but it still assumes that all repeated nodes have the **same height**
* (when scrolling vertically) or **same width** (when scrolling horizontally).
* @param {boolean=} md-on-demand When present, treats the `md-virtual-repeat` argument as an object
* that can fetch rows rather than an array.
*
* **NOTE:** This object **must** implement the following interface with two methods:
*
* - `getItemAtIndex` - `{function(index): Object}`: The item at that `index` or `null` if it is not
* yet loaded (it should start downloading the item in that case).
* - `getLength` - `{function(): number}`: The data length to which the repeater container
* should be sized. Ideally, when the count is known, this method should return it.
* Otherwise, return a higher number than the currently loaded items to produce an
* infinite-scroll behavior.
*/
function VirtualRepeatDirective($parse) {
return {
controller: VirtualRepeatController,
priority: 1000,
require: ['mdVirtualRepeat', '^^mdVirtualRepeatContainer'],
restrict: 'A',
terminal: true,
transclude: 'element',
compile: function VirtualRepeatCompile($element, $attrs) {
var expression = $attrs.mdVirtualRepeat;
var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)\s*$/);
var repeatName = match[1];
var repeatListExpression = $parse(match[2]);
var extraName = $attrs.mdExtraName && $parse($attrs.mdExtraName);
return function VirtualRepeatLink($scope, $element, $attrs, ctrl, $transclude) {
ctrl[0].link_(ctrl[1], $transclude, repeatName, repeatListExpression, extraName);
};
}
};
}
/** @ngInject */
function VirtualRepeatController($scope, $element, $attrs, $browser, $document, $rootScope,
$$rAF, $mdUtil) {
this.$scope = $scope;
this.$element = $element;
this.$attrs = $attrs;
this.$browser = $browser;
this.$document = $document;
this.$mdUtil = $mdUtil;
this.$rootScope = $rootScope;
this.$$rAF = $$rAF;
/** @type {boolean} Whether we are in on-demand mode. */
this.onDemand = $mdUtil.parseAttributeBoolean($attrs.mdOnDemand);
/** @type {!Function} Backup reference to $browser.$$checkUrlChange */
this.browserCheckUrlChange = $browser.$$checkUrlChange;
/** @type {number} Most recent starting repeat index (based on scroll offset) */
this.newStartIndex = 0;
/** @type {number} Most recent ending repeat index (based on scroll offset) */
this.newEndIndex = 0;
/** @type {number} Most recent end visible index (based on scroll offset) */
this.newVisibleEnd = 0;
/** @type {number} Previous starting repeat index (based on scroll offset) */
this.startIndex = 0;
/** @type {number} Previous ending repeat index (based on scroll offset) */
this.endIndex = 0;
/** @type {?number} Height/width of repeated elements. */
this.itemSize = $scope.$eval($attrs.mdItemSize) || null;
/** @type {boolean} Whether this is the first time that items are rendered. */
this.isFirstRender = true;
/**
* @private {boolean} Whether the items in the list are already being updated. Used to prevent
* nested calls to virtualRepeatUpdate_.
*/
this.isVirtualRepeatUpdating_ = false;
/** @type {number} Most recently seen length of items. */
this.itemsLength = 0;
/**
* @type {!Function} Unwatch callback for item size (when md-items-size is
* not specified), or angular.noop otherwise.
*/
this.unwatchItemSize_ = angular.noop;
/**
* Presently rendered blocks by repeat index.
* @type {Object}
*/
this.blocks = {};
/** @type {Array} A pool of presently unused blocks. */
this.pooledBlocks = [];
$scope.$on('$destroy', angular.bind(this, this.cleanupBlocks_));
}
/**
* An object representing a repeated item.
* @typedef {{element: !jqLite, new: boolean, scope: !angular.Scope}}
*/
VirtualRepeatController.Block;
/**
* Called at startup by the md-virtual-repeat postLink function.
* @param {!VirtualRepeatContainerController} container The container's controller.
* @param {!Function} transclude The repeated element's bound transclude function.
* @param {string} repeatName The left hand side of the repeat expression, indicating
* the name for each item in the array.
* @param {!Function} repeatListExpression A compiled expression based on the right hand side
* of the repeat expression. Points to the array to repeat over.
* @param {string|undefined} extraName The optional extra repeatName.
*/
VirtualRepeatController.prototype.link_ =
function(container, transclude, repeatName, repeatListExpression, extraName) {
this.container = container;
this.transclude = transclude;
this.repeatName = repeatName;
this.rawRepeatListExpression = repeatListExpression;
this.extraName = extraName;
this.sized = false;
this.repeatListExpression = angular.bind(this, this.repeatListExpression_);
this.container.register(this);
};
/** @private Cleans up unused blocks. */
VirtualRepeatController.prototype.cleanupBlocks_ = function() {
angular.forEach(this.pooledBlocks, function cleanupBlock(block) {
block.element.remove();
});
};
/** @private Attempts to set itemSize by measuring a repeated element in the dom */
VirtualRepeatController.prototype.readItemSize_ = function() {
if (this.itemSize) {
// itemSize was successfully read in a different asynchronous call.
return;
}
this.items = this.repeatListExpression(this.$scope);
this.parentNode = this.$element[0].parentNode;
var block = this.getBlock_(0);
if (!block.element[0].parentNode) {
this.parentNode.appendChild(block.element[0]);
}
this.itemSize = block.element[0][
this.container.isHorizontal() ? 'offsetWidth' : 'offsetHeight'] || null;
this.blocks[0] = block;
this.poolBlock_(0);
if (this.itemSize) {
this.containerUpdated();
}
};
/**
* Returns the user-specified repeat list, transforming it into an array-like
* object in the case of infinite scroll/dynamic load mode.
* @param {!angular.Scope} The scope.
* @return {!Array|!Object} An array or array-like object for iteration.
*/
VirtualRepeatController.prototype.repeatListExpression_ = function(scope) {
var repeatList = this.rawRepeatListExpression(scope);
if (this.onDemand && repeatList) {
var virtualList = new VirtualRepeatModelArrayLike(repeatList);
virtualList.$$includeIndexes(this.newStartIndex, this.newVisibleEnd);
return virtualList;
} else {
return repeatList;
}
};
/**
* Called by the container. Informs us that the container's scroll or size has
* changed.
*/
VirtualRepeatController.prototype.containerUpdated = function() {
// If itemSize is unknown, attempt to measure it.
if (!this.itemSize) {
// Make sure to clean up watchers if we can (see #8178)
if(this.unwatchItemSize_ && this.unwatchItemSize_ !== angular.noop){
this.unwatchItemSize_();
}
this.unwatchItemSize_ = this.$scope.$watchCollection(
this.repeatListExpression,
angular.bind(this, function(items) {
if (items && items.length) {
this.readItemSize_();
}
}));
if (!this.$rootScope.$$phase) this.$scope.$digest();
return;
} else if (!this.sized) {
this.items = this.repeatListExpression(this.$scope);
}
if (!this.sized) {
this.unwatchItemSize_();
this.sized = true;
this.$scope.$watchCollection(this.repeatListExpression,
angular.bind(this, function(items, oldItems) {
if (!this.isVirtualRepeatUpdating_) {
this.virtualRepeatUpdate_(items, oldItems);
}
}));
}
this.updateIndexes_();
if (this.newStartIndex !== this.startIndex ||
this.newEndIndex !== this.endIndex ||
this.container.getScrollOffset() > this.container.getScrollSize()) {
if (this.items instanceof VirtualRepeatModelArrayLike) {
this.items.$$includeIndexes(this.newStartIndex, this.newEndIndex);
}
this.virtualRepeatUpdate_(this.items, this.items);
}
};
/**
* Called by the container. Returns the size of a single repeated item.
* @return {?number} size of a repeated item.
*/
VirtualRepeatController.prototype.getItemSize = function() {
return this.itemSize;
};
/**
* Called by the container.
* @return {?number} the most recently seen length of items.
*/
VirtualRepeatController.prototype.getItemCount = function() {
return this.itemsLength;
};
/**
* Updates the order and visible offset of repeated blocks in response to scrolling
* or updates to `items`.
* @param items {Array} visible elements
* @param oldItems {Array} previously visible elements
* @private
*/
VirtualRepeatController.prototype.virtualRepeatUpdate_ = function(items, oldItems) {
this.isVirtualRepeatUpdating_ = true;
var itemsLength = items && items.length || 0;
var lengthChanged = false;
// If the number of items shrank, keep the scroll position.
if (this.items && itemsLength < this.items.length && this.container.getScrollOffset() !== 0) {
this.items = items;
var previousScrollOffset = this.container.getScrollOffset();
this.container.resetScroll();
this.container.scrollTo(previousScrollOffset);
}
if (itemsLength !== this.itemsLength) {
lengthChanged = true;
this.itemsLength = itemsLength;
}
this.items = items;
if (items !== oldItems || lengthChanged) {
this.updateIndexes_();
}
this.parentNode = this.$element[0].parentNode;
if (lengthChanged) {
this.container.setScrollSize(itemsLength * this.itemSize);
}
// Detach and pool any blocks that are no longer in the viewport.
Object.keys(this.blocks).forEach(function(blockIndex) {
var index = parseInt(blockIndex, 10);
if (index < this.newStartIndex || index >= this.newEndIndex) {
this.poolBlock_(index);
}
}, this);
// Add needed blocks.
// For performance reasons, temporarily block browser url checks as we digest
// the restored block scopes ($$checkUrlChange reads window.location to
// check for changes and trigger route change, etc, which we don't need when
// trying to scroll at 60fps).
this.$browser.$$checkUrlChange = angular.noop;
var i, block,
newStartBlocks = [],
newEndBlocks = [];
// Collect blocks at the top.
for (i = this.newStartIndex; i < this.newEndIndex && this.blocks[i] == null; i++) {
block = this.getBlock_(i);
this.updateBlock_(block, i);
newStartBlocks.push(block);
}
// Update blocks that are already rendered.
for (; this.blocks[i] != null; i++) {
this.updateBlock_(this.blocks[i], i);
}
var maxIndex = i - 1;
// Collect blocks at the end.
for (; i < this.newEndIndex; i++) {
block = this.getBlock_(i);
this.updateBlock_(block, i);
newEndBlocks.push(block);
}
// Attach collected blocks to the document.
if (newStartBlocks.length) {
this.parentNode.insertBefore(
this.domFragmentFromBlocks_(newStartBlocks),
this.$element[0].nextSibling);
}
if (newEndBlocks.length) {
this.parentNode.insertBefore(
this.domFragmentFromBlocks_(newEndBlocks),
this.blocks[maxIndex] && this.blocks[maxIndex].element[0].nextSibling);
}
// Restore $$checkUrlChange.
this.$browser.$$checkUrlChange = this.browserCheckUrlChange;
this.startIndex = this.newStartIndex;
this.endIndex = this.newEndIndex;
if (this.isFirstRender) {
this.isFirstRender = false;
var firstRenderStartIndex = this.$attrs.mdStartIndex ?
this.$scope.$eval(this.$attrs.mdStartIndex) :
this.container.topIndex;
// The first call to virtualRepeatUpdate_ may not be when the virtual repeater is ready.
// Introduce a slight delay so that the update happens when it is actually ready.
this.$mdUtil.nextTick(function() {
this.container.scrollToIndex(firstRenderStartIndex);
}.bind(this));
}
this.isVirtualRepeatUpdating_ = false;
};
/**
* @param {number} index Where the block is to be in the repeated list.
* @return {!VirtualRepeatController.Block} A new or pooled block to place at the specified index.
* @private
*/
VirtualRepeatController.prototype.getBlock_ = function(index) {
if (this.pooledBlocks.length) {
return this.pooledBlocks.pop();
}
var block;
this.transclude(angular.bind(this, function(clone, scope) {
block = {
element: clone,
new: true,
scope: scope
};
this.updateScope_(scope, index);
this.parentNode.appendChild(clone[0]);
}));
return block;
};
/**
* Updates and if not in a digest cycle, digests the specified block's scope to the data
* at the specified index.
* @param {!VirtualRepeatController.Block} block The block whose scope should be updated.
* @param {number} index The index to set.
* @private
*/
VirtualRepeatController.prototype.updateBlock_ = function(block, index) {
this.blocks[index] = block;
if (!block.new &&
(block.scope.$index === index && block.scope[this.repeatName] === this.items[index])) {
return;
}
block.new = false;
// Update and digest the block's scope.
this.updateScope_(block.scope, index);
// Perform digest before reattaching the block.
// Any resulting synchronous DOM mutations should be much faster as a result.
// This might break some directives.
if (!this.$rootScope.$$phase) {
block.scope.$digest();
}
};
/**
* Updates scope to the data at the specified index.
* @param {!angular.Scope} scope The scope which should be updated.
* @param {number} index The index to set.
* @private
*/
VirtualRepeatController.prototype.updateScope_ = function(scope, index) {
scope.$index = index;
scope[this.repeatName] = this.items && this.items[index];
if (this.extraName) scope[this.extraName(this.$scope)] = this.items[index];
};
/**
* Pools the block at the specified index (Pulls its element out of the dom and stores it).
* @param {number} index The index at which the block to pool is stored.
* @private
*/
VirtualRepeatController.prototype.poolBlock_ = function(index) {
this.pooledBlocks.push(this.blocks[index]);
this.parentNode.removeChild(this.blocks[index].element[0]);
delete this.blocks[index];
};
/**
* Produces a dom fragment containing the elements from the list of blocks.
* @param {!Array} blocks The blocks whose elements
* should be added to the document fragment.
* @return {DocumentFragment}
* @private
*/
VirtualRepeatController.prototype.domFragmentFromBlocks_ = function(blocks) {
var fragment = this.$document[0].createDocumentFragment();
blocks.forEach(function(block) {
fragment.appendChild(block.element[0]);
});
return fragment;
};
/**
* Updates start and end indexes based on length of repeated items and container size.
* @private
*/
VirtualRepeatController.prototype.updateIndexes_ = function() {
var itemsLength = this.items ? this.items.length : 0;
var containerLength = Math.ceil(this.container.getSize() / this.itemSize);
this.newStartIndex = Math.max(0, Math.min(
itemsLength - containerLength,
Math.floor(this.container.getScrollOffset() / this.itemSize)));
this.newVisibleEnd = this.newStartIndex + containerLength + NUM_EXTRA;
this.newEndIndex = Math.min(itemsLength, this.newVisibleEnd);
this.newStartIndex = Math.max(0, this.newStartIndex - NUM_EXTRA);
};
/**
* This VirtualRepeatModelArrayLike class enforces the interface requirements
* for infinite scrolling within a mdVirtualRepeatContainer. An object with this
* interface must implement the following interface with two (2) methods:
*
* getItemAtIndex: function(index) -> item at that index or null if it is not yet
* loaded (It should start downloading the item in that case).
*
* getLength: function() -> number The data legnth to which the repeater container
* should be sized. Ideally, when the count is known, this method should return it.
* Otherwise, return a higher number than the currently loaded items to produce an
* infinite-scroll behavior.
*
* @usage
*
*
*
* Hello {{i}}!
*
*
*
*
*/
function VirtualRepeatModelArrayLike(model) {
if (!angular.isFunction(model.getItemAtIndex) ||
!angular.isFunction(model.getLength)) {
throw Error('When md-on-demand is enabled, the Object passed to md-virtual-repeat must implement ' +
'functions getItemAtIndex() and getLength() ');
}
this.model = model;
}
VirtualRepeatModelArrayLike.prototype.$$includeIndexes = function(start, end) {
for (var i = start; i < end; i++) {
if (!this.hasOwnProperty(i)) {
this[i] = this.model.getItemAtIndex(i);
}
}
this.length = this.model.getLength();
};
/**
* @ngdoc directive
* @name mdForceHeight
* @module material.components.virtualRepeat
* @restrict A
* @description
*
* Force an element to have a certain `px` height. This is used in place of a style tag in order to
* conform to the
*
* Content Security Policy regarding `unsafe-inline` `