sticky.js 9.7 KB

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