You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

363 lines
11 KiB

7 years ago
  1. /*!
  2. * Angular Material Design
  3. * https://github.com/angular/material
  4. * @license MIT
  5. * v1.1.3
  6. */
  7. (function( window, angular, undefined ){
  8. "use strict";
  9. /**
  10. * @ngdoc module
  11. * @name material.components.sticky
  12. * @description
  13. * Sticky effects for md
  14. *
  15. */
  16. MdSticky['$inject'] = ["$mdConstant", "$$rAF", "$mdUtil", "$compile"];
  17. angular
  18. .module('material.components.sticky', [
  19. 'material.core',
  20. 'material.components.content'
  21. ])
  22. .factory('$mdSticky', MdSticky);
  23. /**
  24. * @ngdoc service
  25. * @name $mdSticky
  26. * @module material.components.sticky
  27. *
  28. * @description
  29. * The `$mdSticky`service provides a mixin to make elements sticky.
  30. *
  31. * Whenever the current browser supports stickiness natively, the `$mdSticky` service will just
  32. * use the native browser stickiness.
  33. *
  34. * By default the `$mdSticky` service compiles the cloned element, when not specified through the `elementClone`
  35. * parameter, in the same scope as the actual element lives.
  36. *
  37. *
  38. * <h3>Notes</h3>
  39. * When using an element which is containing a compiled directive, which changed its DOM structure during compilation,
  40. * you should compile the clone yourself using the plain template.<br/><br/>
  41. * See the right usage below:
  42. * <hljs lang="js">
  43. * angular.module('myModule')
  44. * .directive('stickySelect', function($mdSticky, $compile) {
  45. * var SELECT_TEMPLATE =
  46. * '<md-select ng-model="selected">' +
  47. * '<md-option>Option 1</md-option>' +
  48. * '</md-select>';
  49. *
  50. * return {
  51. * restrict: 'E',
  52. * replace: true,
  53. * template: SELECT_TEMPLATE,
  54. * link: function(scope,element) {
  55. * $mdSticky(scope, element, $compile(SELECT_TEMPLATE)(scope));
  56. * }
  57. * };
  58. * });
  59. * </hljs>
  60. *
  61. * @usage
  62. * <hljs lang="js">
  63. * angular.module('myModule')
  64. * .directive('stickyText', function($mdSticky, $compile) {
  65. * return {
  66. * restrict: 'E',
  67. * template: '<span>Sticky Text</span>',
  68. * link: function(scope,element) {
  69. * $mdSticky(scope, element);
  70. * }
  71. * };
  72. * });
  73. * </hljs>
  74. *
  75. * @returns A `$mdSticky` function that takes three arguments:
  76. * - `scope`
  77. * - `element`: The element that will be 'sticky'
  78. * - `elementClone`: A clone of the element, that will be shown
  79. * when the user starts scrolling past the original element.
  80. * If not provided, it will use the result of `element.clone()` and compiles it in the given scope.
  81. */
  82. function MdSticky($mdConstant, $$rAF, $mdUtil, $compile) {
  83. var browserStickySupport = $mdUtil.checkStickySupport();
  84. /**
  85. * Registers an element as sticky, used internally by directives to register themselves
  86. */
  87. return function registerStickyElement(scope, element, stickyClone) {
  88. var contentCtrl = element.controller('mdContent');
  89. if (!contentCtrl) return;
  90. if (browserStickySupport) {
  91. element.css({
  92. position: browserStickySupport,
  93. top: 0,
  94. 'z-index': 2
  95. });
  96. } else {
  97. var $$sticky = contentCtrl.$element.data('$$sticky');
  98. if (!$$sticky) {
  99. $$sticky = setupSticky(contentCtrl);
  100. contentCtrl.$element.data('$$sticky', $$sticky);
  101. }
  102. // Compile our cloned element, when cloned in this service, into the given scope.
  103. var cloneElement = stickyClone || $compile(element.clone())(scope);
  104. var deregister = $$sticky.add(element, cloneElement);
  105. scope.$on('$destroy', deregister);
  106. }
  107. };
  108. function setupSticky(contentCtrl) {
  109. var contentEl = contentCtrl.$element;
  110. // Refresh elements is very expensive, so we use the debounced
  111. // version when possible.
  112. var debouncedRefreshElements = $$rAF.throttle(refreshElements);
  113. // setupAugmentedScrollEvents gives us `$scrollstart` and `$scroll`,
  114. // more reliable than `scroll` on android.
  115. setupAugmentedScrollEvents(contentEl);
  116. contentEl.on('$scrollstart', debouncedRefreshElements);
  117. contentEl.on('$scroll', onScroll);
  118. var self;
  119. return self = {
  120. prev: null,
  121. current: null, //the currently stickied item
  122. next: null,
  123. items: [],
  124. add: add,
  125. refreshElements: refreshElements
  126. };
  127. /***************
  128. * Public
  129. ***************/
  130. // Add an element and its sticky clone to this content's sticky collection
  131. function add(element, stickyClone) {
  132. stickyClone.addClass('md-sticky-clone');
  133. var item = {
  134. element: element,
  135. clone: stickyClone
  136. };
  137. self.items.push(item);
  138. $mdUtil.nextTick(function() {
  139. contentEl.prepend(item.clone);
  140. });
  141. debouncedRefreshElements();
  142. return function remove() {
  143. self.items.forEach(function(item, index) {
  144. if (item.element[0] === element[0]) {
  145. self.items.splice(index, 1);
  146. item.clone.remove();
  147. }
  148. });
  149. debouncedRefreshElements();
  150. };
  151. }
  152. function refreshElements() {
  153. // Sort our collection of elements by their current position in the DOM.
  154. // We need to do this because our elements' order of being added may not
  155. // be the same as their order of display.
  156. self.items.forEach(refreshPosition);
  157. self.items = self.items.sort(function(a, b) {
  158. return a.top < b.top ? -1 : 1;
  159. });
  160. // Find which item in the list should be active,
  161. // based upon the content's current scroll position
  162. var item;
  163. var currentScrollTop = contentEl.prop('scrollTop');
  164. for (var i = self.items.length - 1; i >= 0; i--) {
  165. if (currentScrollTop > self.items[i].top) {
  166. item = self.items[i];
  167. break;
  168. }
  169. }
  170. setCurrentItem(item);
  171. }
  172. /***************
  173. * Private
  174. ***************/
  175. // Find the `top` of an item relative to the content element,
  176. // and also the height.
  177. function refreshPosition(item) {
  178. // Find the top of an item by adding to the offsetHeight until we reach the
  179. // content element.
  180. var current = item.element[0];
  181. item.top = 0;
  182. item.left = 0;
  183. item.right = 0;
  184. while (current && current !== contentEl[0]) {
  185. item.top += current.offsetTop;
  186. item.left += current.offsetLeft;
  187. if ( current.offsetParent ){
  188. item.right += current.offsetParent.offsetWidth - current.offsetWidth - current.offsetLeft; //Compute offsetRight
  189. }
  190. current = current.offsetParent;
  191. }
  192. item.height = item.element.prop('offsetHeight');
  193. var defaultVal = $mdUtil.floatingScrollbars() ? '0' : undefined;
  194. $mdUtil.bidi(item.clone, 'margin-left', item.left, defaultVal);
  195. $mdUtil.bidi(item.clone, 'margin-right', defaultVal, item.right);
  196. }
  197. // As we scroll, push in and select the correct sticky element.
  198. function onScroll() {
  199. var scrollTop = contentEl.prop('scrollTop');
  200. var isScrollingDown = scrollTop > (onScroll.prevScrollTop || 0);
  201. // Store the previous scroll so we know which direction we are scrolling
  202. onScroll.prevScrollTop = scrollTop;
  203. //
  204. // AT TOP (not scrolling)
  205. //
  206. if (scrollTop === 0) {
  207. // If we're at the top, just clear the current item and return
  208. setCurrentItem(null);
  209. return;
  210. }
  211. //
  212. // SCROLLING DOWN (going towards the next item)
  213. //
  214. if (isScrollingDown) {
  215. // If we've scrolled down past the next item's position, sticky it and return
  216. if (self.next && self.next.top <= scrollTop) {
  217. setCurrentItem(self.next);
  218. return;
  219. }
  220. // If the next item is close to the current one, push the current one up out of the way
  221. if (self.current && self.next && self.next.top - scrollTop <= self.next.height) {
  222. translate(self.current, scrollTop + (self.next.top - self.next.height - scrollTop));
  223. return;
  224. }
  225. }
  226. //
  227. // SCROLLING UP (not at the top & not scrolling down; must be scrolling up)
  228. //
  229. if (!isScrollingDown) {
  230. // If we've scrolled up past the previous item's position, sticky it and return
  231. if (self.current && self.prev && scrollTop < self.current.top) {
  232. setCurrentItem(self.prev);
  233. return;
  234. }
  235. // If the next item is close to the current one, pull the current one down into view
  236. if (self.next && self.current && (scrollTop >= (self.next.top - self.current.height))) {
  237. translate(self.current, scrollTop + (self.next.top - scrollTop - self.current.height));
  238. return;
  239. }
  240. }
  241. //
  242. // Otherwise, just move the current item to the proper place (scrolling up or down)
  243. //
  244. if (self.current) {
  245. translate(self.current, scrollTop);
  246. }
  247. }
  248. function setCurrentItem(item) {
  249. if (self.current === item) return;
  250. // Deactivate currently active item
  251. if (self.current) {
  252. translate(self.current, null);
  253. setStickyState(self.current, null);
  254. }
  255. // Activate new item if given
  256. if (item) {
  257. setStickyState(item, 'active');
  258. }
  259. self.current = item;
  260. var index = self.items.indexOf(item);
  261. // If index === -1, index + 1 = 0. It works out.
  262. self.next = self.items[index + 1];
  263. self.prev = self.items[index - 1];
  264. setStickyState(self.next, 'next');
  265. setStickyState(self.prev, 'prev');
  266. }
  267. function setStickyState(item, state) {
  268. if (!item || item.state === state) return;
  269. if (item.state) {
  270. item.clone.attr('sticky-prev-state', item.state);
  271. item.element.attr('sticky-prev-state', item.state);
  272. }
  273. item.clone.attr('sticky-state', state);
  274. item.element.attr('sticky-state', state);
  275. item.state = state;
  276. }
  277. function translate(item, amount) {
  278. if (!item) return;
  279. if (amount === null || amount === undefined) {
  280. if (item.translateY) {
  281. item.translateY = null;
  282. item.clone.css($mdConstant.CSS.TRANSFORM, '');
  283. }
  284. } else {
  285. item.translateY = amount;
  286. $mdUtil.bidi( item.clone, $mdConstant.CSS.TRANSFORM,
  287. 'translate3d(' + item.left + 'px,' + amount + 'px,0)',
  288. 'translateY(' + amount + 'px)'
  289. );
  290. }
  291. }
  292. }
  293. // Android 4.4 don't accurately give scroll events.
  294. // To fix this problem, we setup a fake scroll event. We say:
  295. // > If a scroll or touchmove event has happened in the last DELAY milliseconds,
  296. // then send a `$scroll` event every animationFrame.
  297. // Additionally, we add $scrollstart and $scrollend events.
  298. function setupAugmentedScrollEvents(element) {
  299. var SCROLL_END_DELAY = 200;
  300. var isScrolling;
  301. var lastScrollTime;
  302. element.on('scroll touchmove', function() {
  303. if (!isScrolling) {
  304. isScrolling = true;
  305. $$rAF.throttle(loopScrollEvent);
  306. element.triggerHandler('$scrollstart');
  307. }
  308. element.triggerHandler('$scroll');
  309. lastScrollTime = +$mdUtil.now();
  310. });
  311. function loopScrollEvent() {
  312. if (+$mdUtil.now() - lastScrollTime > SCROLL_END_DELAY) {
  313. isScrolling = false;
  314. element.triggerHandler('$scrollend');
  315. } else {
  316. element.triggerHandler('$scroll');
  317. $$rAF.throttle(loopScrollEvent);
  318. }
  319. }
  320. }
  321. }
  322. })(window, window.angular);