This repository has been archived by the owner on Dec 1, 2023. It is now read-only.
/
scrollspy.js
257 lines (197 loc) · 8.2 KB
/
scrollspy.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
'use strict';
angular.module('mgcrea.ngStrap.scrollspy', ['mgcrea.ngStrap.helpers.debounce', 'mgcrea.ngStrap.helpers.dimensions'])
.provider('$scrollspy', function () {
// Pool of registered spies
var spies = this.$$spies = {};
var defaults = this.defaults = {
debounce: 150,
throttle: 100,
offset: 100
};
this.$get = function ($window, $document, $rootScope, dimensions, debounce, throttle) {
var windowEl = angular.element($window);
var docEl = angular.element($document.prop('documentElement'));
var bodyEl = angular.element($window.document.body);
// Helper functions
function nodeName (element, name) {
return element[0].nodeName && element[0].nodeName.toLowerCase() === name.toLowerCase();
}
function ScrollSpyFactory (config) {
// Common vars
var options = angular.extend({}, defaults, config);
if (!options.element) options.element = bodyEl;
var isWindowSpy = nodeName(options.element, 'body');
var scrollEl = isWindowSpy ? windowEl : options.element;
var scrollId = isWindowSpy ? 'window' : options.id;
// Use existing spy
if (spies[scrollId]) {
spies[scrollId].$$count++;
return spies[scrollId];
}
var $scrollspy = {};
// Private vars
var unbindViewContentLoaded;
var unbindIncludeContentLoaded;
var trackedElements = $scrollspy.$trackedElements = [];
var sortedElements = [];
var activeTarget;
var debouncedCheckPosition;
var throttledCheckPosition;
var debouncedCheckOffsets;
/* eslint-disable no-unused-vars */
var viewportHeight;
/* eslint-enable no-unused-vars */
var scrollTop;
$scrollspy.init = function () {
// Setup internal ref counter
this.$$count = 1;
// Bind events
debouncedCheckPosition = debounce(this.checkPosition, options.debounce);
throttledCheckPosition = throttle(this.checkPosition, options.throttle);
scrollEl.on('click', this.checkPositionWithEventLoop);
windowEl.on('resize', debouncedCheckPosition);
scrollEl.on('scroll', throttledCheckPosition);
debouncedCheckOffsets = debounce(this.checkOffsets, options.debounce);
unbindViewContentLoaded = $rootScope.$on('$viewContentLoaded', debouncedCheckOffsets);
unbindIncludeContentLoaded = $rootScope.$on('$includeContentLoaded', debouncedCheckOffsets);
debouncedCheckOffsets();
// Register spy for reuse
if (scrollId) {
spies[scrollId] = $scrollspy;
}
};
$scrollspy.destroy = function () {
// Check internal ref counter
this.$$count--;
if (this.$$count > 0) {
return;
}
// Unbind events
scrollEl.off('click', this.checkPositionWithEventLoop);
windowEl.off('resize', debouncedCheckPosition);
scrollEl.off('scroll', throttledCheckPosition);
unbindViewContentLoaded();
unbindIncludeContentLoaded();
if (scrollId) {
delete spies[scrollId];
}
};
$scrollspy.checkPosition = function () {
// Not ready yet
if (!sortedElements.length) return;
// Calculate the scroll position
scrollTop = (isWindowSpy ? $window.pageYOffset : scrollEl.prop('scrollTop')) || 0;
// Calculate the viewport height for use by the components
viewportHeight = Math.max($window.innerHeight, docEl.prop('clientHeight'));
// Activate first element if scroll is smaller
if (scrollTop < sortedElements[0].offsetTop && activeTarget !== sortedElements[0].target) {
return $scrollspy.$activateElement(sortedElements[0]);
}
// Activate proper element
for (var i = sortedElements.length; i--;) {
if (angular.isUndefined(sortedElements[i].offsetTop) || sortedElements[i].offsetTop === null) continue;
if (activeTarget === sortedElements[i].target) continue;
if (scrollTop < sortedElements[i].offsetTop) continue;
if (sortedElements[i + 1] && scrollTop > sortedElements[i + 1].offsetTop) continue;
return $scrollspy.$activateElement(sortedElements[i]);
}
};
$scrollspy.checkPositionWithEventLoop = function () {
// IE 9 throws an error if we use 'this' instead of '$scrollspy'
// in this setTimeout call
setTimeout($scrollspy.checkPosition, 1);
};
// Protected methods
$scrollspy.$activateElement = function (element) {
if (activeTarget) {
var activeElement = $scrollspy.$getTrackedElement(activeTarget);
if (activeElement) {
activeElement.source.removeClass('active');
if (nodeName(activeElement.source, 'li') && nodeName(activeElement.source.parent().parent(), 'li')) {
activeElement.source.parent().parent().removeClass('active');
}
}
}
activeTarget = element.target;
element.source.addClass('active');
if (nodeName(element.source, 'li') && nodeName(element.source.parent().parent(), 'li')) {
element.source.parent().parent().addClass('active');
}
};
$scrollspy.$getTrackedElement = function (target) {
return trackedElements.filter(function (obj) {
return obj.target === target;
})[0];
};
// Track offsets behavior
$scrollspy.checkOffsets = function () {
angular.forEach(trackedElements, function (trackedElement) {
var targetElement = document.querySelector(trackedElement.target);
trackedElement.offsetTop = targetElement ? dimensions.offset(targetElement).top : null;
if (options.offset && trackedElement.offsetTop !== null) trackedElement.offsetTop -= options.offset * 1;
});
sortedElements = trackedElements
.filter(function (el) {
return el.offsetTop !== null;
})
.sort(function (a, b) {
return a.offsetTop - b.offsetTop;
});
debouncedCheckPosition();
};
$scrollspy.trackElement = function (target, source) {
trackedElements.push({target: target, source: source});
};
$scrollspy.untrackElement = function (target, source) {
var toDelete;
for (var i = trackedElements.length; i--;) {
if (trackedElements[i].target === target && trackedElements[i].source === source) {
toDelete = i;
break;
}
}
trackedElements.splice(toDelete, 1);
};
$scrollspy.activate = function (i) {
trackedElements[i].addClass('active');
};
// Initialize plugin
$scrollspy.init();
return $scrollspy;
}
return ScrollSpyFactory;
};
})
.directive('bsScrollspy', function ($rootScope, debounce, dimensions, $scrollspy) {
return {
restrict: 'EAC',
link: function postLink (scope, element, attr) {
var options = {scope: scope};
angular.forEach(['offset', 'target'], function (key) {
if (angular.isDefined(attr[key])) options[key] = attr[key];
});
var scrollspy = $scrollspy(options);
scrollspy.trackElement(options.target, element);
scope.$on('$destroy', function () {
if (scrollspy) {
scrollspy.untrackElement(options.target, element);
scrollspy.destroy();
}
options = null;
scrollspy = null;
});
}
};
})
.directive('bsScrollspyList', function ($rootScope, debounce, dimensions, $scrollspy) {
return {
restrict: 'A',
compile: function postLink (element, attr) {
var children = element[0].querySelectorAll('li > a[href]');
angular.forEach(children, function (child) {
var childEl = angular.element(child);
childEl.parent().attr('bs-scrollspy', '').attr('data-target', childEl.attr('href'));
});
}
};
});