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
258
259
260
261
262
263
264
265
266
267
268
|
/**
* --------------------------------------------------------------------------
* Bootstrap (v5.1.1): scrollspy.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* --------------------------------------------------------------------------
*/
import { defineJQueryPlugin, getElement, typeCheckConfig } from './util/index'
import EventHandler from './dom/event-handler'
import Manipulator from './dom/manipulator'
import SelectorEngine from './dom/selector-engine'
import BaseComponent from './base-component'
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
const NAME = 'scrollspy'
const DATA_KEY = 'bs.scrollspy'
const EVENT_KEY = `.${DATA_KEY}`
const DATA_API_KEY = '.data-api'
const Default = {
offset: null, // @deprecated, only for backwards Compatibility reasons
rootMargin: '0px 0px -40%',
target: null
}
const DefaultType = {
offset: '(number|null)', // @deprecated, only for backwards Compatibility reasons
rootMargin: 'string',
target: 'element'
}
const EVENT_ACTIVATE = `activate${EVENT_KEY}`
const EVENT_LOAD_DATA_API = `load${EVENT_KEY}${DATA_API_KEY}`
const CLASS_NAME_DROPDOWN_ITEM = 'dropdown-item'
const CLASS_NAME_ACTIVE = 'active'
const SELECTOR_DATA_SPY = '[data-bs-spy="scroll"]'
const SELECTOR_NAV_LIST_GROUP = '.nav, .list-group'
const SELECTOR_NAV_LINKS = '.nav-link'
const SELECTOR_NAV_ITEMS = '.nav-item'
const SELECTOR_LIST_ITEMS = '.list-group-item'
const SELECTOR_DROPDOWN = '.dropdown'
const SELECTOR_DROPDOWN_TOGGLE = '.dropdown-toggle'
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
class ScrollSpy extends BaseComponent {
constructor(element, config) {
super(element)
// this._element is the observablesContainer and config.target the menu-links wrapper
this._config = this._getConfig(config)
this._targetLinks = []
this._activeTarget = null
this._observableSections = []
this._observer = null
this.refresh() // initialize
}
// Getters
static get Default() {
return Default
}
static get NAME() {
return NAME
}
// Public
refresh() {
this._targetLinks = SelectorEngine
.find('[href]', this._config.target)// `${SELECTOR_NAV_LINKS}, ${SELECTOR_LIST_ITEMS}, .${CLASS_NAME_DROPDOWN_ITEM}`
.filter(el => el.hash.length > 0)// ensure that all have id
this._observableSections = this._targetLinks
.map(el => SelectorEngine.findOne(el.hash, this._element))
.filter(el => el)// filter nulls
if (this._observer) {
this._observer.disconnect()
} else {
this._observer = this._getNewObserver()
}
for (const section of this._observableSections) {
this._observer.observe(section)
}
}
dispose() {
this._observer.disconnect()
super.dispose()
}
// Private
_getConfig(config) {
config = {
...Default,
...Manipulator.getDataAttributes(this._element),
...(typeof config === 'object' && config ? config : {})
}
config.target = getElement(config.target)
typeCheckConfig(NAME, config, DefaultType)
return config
}
_process(target) {
if (this._activeTarget === target) {
return
}
this._clearActiveClass(this._config.target)
if (!target) {
return
}
this._activeTarget = target
target.classList.add(CLASS_NAME_ACTIVE)
if (target.classList.contains(CLASS_NAME_DROPDOWN_ITEM)) { // Activate dropdown parents
SelectorEngine.findOne(SELECTOR_DROPDOWN_TOGGLE, target.closest(SELECTOR_DROPDOWN))
.classList.add(CLASS_NAME_ACTIVE)
} else {
for (const listGroup of SelectorEngine.parents(target, SELECTOR_NAV_LIST_GROUP)) {
// Set triggered links parents as active
// With both <ul> and <nav> markup a parent is the previous sibling of any nav ancestor
for (const item of SelectorEngine.prev(listGroup, `${SELECTOR_NAV_LINKS}, ${SELECTOR_LIST_ITEMS}`)) {
item.classList.add(CLASS_NAME_ACTIVE)
}
// Handle special case when .nav-link is inside .nav-item
for (const navItem of SelectorEngine.prev(listGroup, SELECTOR_NAV_ITEMS)) {
for (const item of SelectorEngine.children(navItem, SELECTOR_NAV_LINKS)) {
item.classList.add(CLASS_NAME_ACTIVE)
}
}
}
}
EventHandler.trigger(this._element, EVENT_ACTIVATE, {
relatedTarget: target
})
}
_clearActiveClass(parent) {
if (parent !== this._config.target) {
parent.classList.remove(CLASS_NAME_ACTIVE)
}
for (const node of SelectorEngine.find(`.${CLASS_NAME_ACTIVE}`, parent)) {
node.classList.remove(CLASS_NAME_ACTIVE)
}
}
_getNewObserver() {
let previousVisibleEntryTop = 0
let previousParentScrollTop = 0
const getTargetLink = entry => this._targetLinks.find(el => el.hash === `#${entry.target.id}`)
const activate = entry => {
previousVisibleEntryTop = entry.target.offsetTop
const targetToActivate = getTargetLink(entry)
this._process(targetToActivate)
}
const callback = entries => {
const parentScrollTop = this._element.scrollTop
let previousIntersectionRatio = 0
for (const entry of entries) {
if (entry.isIntersecting && previousIntersectionRatio < entry.intersectionRatio) {
const { offsetTop } = entry.target
previousIntersectionRatio = entry.intersectionRatio
const userScrollsDown = parentScrollTop >= previousParentScrollTop
if (userScrollsDown && offsetTop >= previousVisibleEntryTop) { // if we are scrolling down, pick the bigger offsetTop
activate(entry)
continue
}
if (!userScrollsDown && offsetTop < previousVisibleEntryTop) { // if we are scrolling up, pick the smallest offsetTop
activate(entry)
}
continue
}
const notVisibleElement = getTargetLink(entry)
this._clearActiveClass(notVisibleElement)
}
previousParentScrollTop = this._element.scrollTop
}
const options = {
root: this._element,
threshold: 0,
rootMargin: this._getRootMargin()
}
return new IntersectionObserver(callback.bind(this), options)
}
_getRootMargin() { // Only for backwards compatibility reasons. Use rootMargin only
const { offset, rootMargin } = this._config
return offset ? `${offset}px 0px 0px` : rootMargin
}
// Static
static jQueryInterface(config) {
return this.each(function () {
const data = ScrollSpy.getOrCreateInstance(this, config)
if (typeof config !== 'string') {
return
}
if (data[config] === undefined || config.startsWith('_') || config === 'constructor') {
throw new TypeError(`No method named "${config}"`)
}
data[config]()
})
}
}
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
EventHandler.on(window, EVENT_LOAD_DATA_API, () => {
for (const spy of SelectorEngine.find(SELECTOR_DATA_SPY)) {
new ScrollSpy(spy) // eslint-disable-line no-new
}
})
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
* add .ScrollSpy to jQuery only if jQuery is present
*/
defineJQueryPlugin(ScrollSpy)
export default ScrollSpy
|