rewritten scrollspy without jquery

This commit is contained in:
Alessandro Chitolina 2017-09-25 09:09:01 +02:00 committed by XhmikosR
parent 9744886519
commit 0263d1742c
5 changed files with 117 additions and 49 deletions

View File

@ -40,6 +40,22 @@ const Manipulator = {
element.removeAttribute(`data-${key.replace(/[A-Z]/g, (chr) => `-${chr.toLowerCase()}`)}`) element.removeAttribute(`data-${key.replace(/[A-Z]/g, (chr) => `-${chr.toLowerCase()}`)}`)
}, },
offset(element) {
const rect = element.getBoundingClientRect()
return {
top: rect.top + document.body.scrollTop,
left: rect.left + document.body.scrollLeft
}
},
position(element) {
return {
top: element.offsetTop,
left: element.offsetLeft
}
},
toggleClass(element, className) { toggleClass(element, className) {
if (typeof element === 'undefined' || element === null) { if (typeof element === 'undefined' || element === null) {
return return

View File

@ -111,10 +111,6 @@ const SelectorEngine = (() => {
return null return null
} }
if (selector.indexOf('#') === 0) {
return SelectorEngine.findOne(selector, element)
}
return findFn.call(element, selector) return findFn.call(element, selector)
}, },
@ -135,8 +131,46 @@ const SelectorEngine = (() => {
return children.filter((child) => this.matches(child, selector)) return children.filter((child) => this.matches(child, selector))
}, },
parents(element, selector) {
if (typeof selector !== 'string') {
return null
}
const parents = []
let ancestor = element.parentNode
while (ancestor && ancestor.nodeType === Node.ELEMENT_NODE) {
if (fnMatches.call(ancestor, selector)) {
parents.push(ancestor)
}
ancestor = ancestor.parentNode
}
return parents
},
closest(element, selector) { closest(element, selector) {
return fnClosest(element, selector) return fnClosest(element, selector)
},
prev(element, selector) {
if (typeof selector !== 'string') {
return null
}
const siblings = []
let previous = element.previousSibling
while (previous) {
if (fnMatches.call(previous, selector)) {
siblings.push(previous)
}
previous = previous.previousSibling
}
return siblings
} }
} }
})() })()

View File

@ -5,7 +5,10 @@
* -------------------------------------------------------------------------- * --------------------------------------------------------------------------
*/ */
import $ from 'jquery' import Data from './dom/data'
import EventHandler from './dom/eventHandler'
import Manipulator from './dom/manipulator'
import SelectorEngine from './dom/selectorEngine'
import Util from './util' import Util from './util'
/** /**
@ -19,7 +22,6 @@ const VERSION = '4.3.1'
const DATA_KEY = 'bs.scrollspy' const DATA_KEY = 'bs.scrollspy'
const EVENT_KEY = `.${DATA_KEY}` const EVENT_KEY = `.${DATA_KEY}`
const DATA_API_KEY = '.data-api' const DATA_API_KEY = '.data-api'
const JQUERY_NO_CONFLICT = $.fn[NAME]
const Default = { const Default = {
offset : 10, offset : 10,
@ -81,10 +83,12 @@ class ScrollSpy {
this._activeTarget = null this._activeTarget = null
this._scrollHeight = 0 this._scrollHeight = 0
$(this._scrollElement).on(Event.SCROLL, (event) => this._process(event)) EventHandler.on(this._scrollElement, Event.SCROLL, (event) => this._process(event))
this.refresh() this.refresh()
this._process() this._process()
Data.setData(element, DATA_KEY, this)
} }
// Getters // Getters
@ -114,7 +118,7 @@ class ScrollSpy {
this._scrollHeight = this._getScrollHeight() this._scrollHeight = this._getScrollHeight()
const targets = [].slice.call(document.querySelectorAll(this._selector)) const targets = Util.makeArray(document.querySelectorAll(this._selector))
targets targets
.map((element) => { .map((element) => {
@ -130,7 +134,7 @@ class ScrollSpy {
if (targetBCR.width || targetBCR.height) { if (targetBCR.width || targetBCR.height) {
// TODO (fat): remove sketch reliance on jQuery position/offset // TODO (fat): remove sketch reliance on jQuery position/offset
return [ return [
$(target)[offsetMethod]().top + offsetBase, Manipulator[offsetMethod](target).top + offsetBase,
targetSelector targetSelector
] ]
} }
@ -146,8 +150,8 @@ class ScrollSpy {
} }
dispose() { dispose() {
$.removeData(this._element, DATA_KEY) Data.removeData(this._element, DATA_KEY)
$(this._scrollElement).off(EVENT_KEY) EventHandler.off(this._scrollElement, EVENT_KEY)
this._element = null this._element = null
this._scrollElement = null this._scrollElement = null
@ -168,10 +172,10 @@ class ScrollSpy {
} }
if (typeof config.target !== 'string') { if (typeof config.target !== 'string') {
let id = $(config.target).attr('id') let id = config.target.id
if (!id) { if (!id) {
id = Util.getUID(NAME) id = Util.getUID(NAME)
$(config.target).attr('id', id) config.target.id = id
} }
config.target = `#${id}` config.target = `#${id}`
} }
@ -242,32 +246,45 @@ class ScrollSpy {
this._clear() this._clear()
const queries = this._selector const queries = this._selector.split(',')
.split(',')
.map((selector) => `${selector}[data-target="${target}"],${selector}[href="${target}"]`) .map((selector) => `${selector}[data-target="${target}"],${selector}[href="${target}"]`)
const $link = $([].slice.call(document.querySelectorAll(queries.join(',')))) const link = SelectorEngine.findOne(queries.join(','))
if ($link.hasClass(ClassName.DROPDOWN_ITEM)) { if (link.classList.contains(ClassName.DROPDOWN_ITEM)) {
$link.closest(Selector.DROPDOWN).find(Selector.DROPDOWN_TOGGLE).addClass(ClassName.ACTIVE) SelectorEngine
$link.addClass(ClassName.ACTIVE) .findOne(Selector.DROPDOWN_TOGGLE, SelectorEngine.closest(link, Selector.DROPDOWN))
.classList.add(ClassName.ACTIVE)
link.classList.add(ClassName.ACTIVE)
} else { } else {
// Set triggered link as active // Set triggered link as active
$link.addClass(ClassName.ACTIVE) link.classList.add(ClassName.ACTIVE)
// Set triggered links parents as active
// With both <ul> and <nav> markup a parent is the previous sibling of any nav ancestor SelectorEngine
$link.parents(Selector.NAV_LIST_GROUP).prev(`${Selector.NAV_LINKS}, ${Selector.LIST_ITEMS}`).addClass(ClassName.ACTIVE) .parents(link, Selector.NAV_LIST_GROUP)
// Handle special case when .nav-link is inside .nav-item .forEach((listGroup) => {
$link.parents(Selector.NAV_LIST_GROUP).prev(Selector.NAV_ITEMS).children(Selector.NAV_LINKS).addClass(ClassName.ACTIVE) // Set triggered links parents as active
// With both <ul> and <nav> markup a parent is the previous sibling of any nav ancestor
SelectorEngine.prev(listGroup, `${Selector.NAV_LINKS}, ${Selector.LIST_ITEMS}`)
.forEach((item) => item.classList.add(ClassName.ACTIVE))
// Handle special case when .nav-link is inside .nav-item
SelectorEngine.prev(listGroup, Selector.NAV_ITEMS)
.forEach((navItem) => {
SelectorEngine.children(navItem, Selector.NAV_LINKS)
.forEach((item) => item.classList.add(ClassName.ACTIVE))
})
})
} }
$(this._scrollElement).trigger(Event.ACTIVATE, { EventHandler.trigger(this._scrollElement, Event.ACTIVATE, {
relatedTarget: target relatedTarget: target
}) })
} }
_clear() { _clear() {
[].slice.call(document.querySelectorAll(this._selector)) Util.makeArray(document.querySelectorAll(this._selector))
.filter((node) => node.classList.contains(ClassName.ACTIVE)) .filter((node) => node.classList.contains(ClassName.ACTIVE))
.forEach((node) => node.classList.remove(ClassName.ACTIVE)) .forEach((node) => node.classList.remove(ClassName.ACTIVE))
} }
@ -276,12 +293,11 @@ class ScrollSpy {
static _jQueryInterface(config) { static _jQueryInterface(config) {
return this.each(function () { return this.each(function () {
let data = $(this).data(DATA_KEY) let data = Data.getData(this, DATA_KEY)
const _config = typeof config === 'object' && config const _config = typeof config === 'object' && config
if (!data) { if (!data) {
data = new ScrollSpy(this, _config) data = new ScrollSpy(this, _config)
$(this).data(DATA_KEY, data)
} }
if (typeof config === 'string') { if (typeof config === 'string') {
@ -300,14 +316,9 @@ class ScrollSpy {
* ------------------------------------------------------------------------ * ------------------------------------------------------------------------
*/ */
$(window).on(Event.LOAD_DATA_API, () => { EventHandler.on(window, Event.LOAD_DATA_API, () => {
const scrollSpys = [].slice.call(document.querySelectorAll(Selector.DATA_SPY)) Util.makeArray(SelectorEngine.find(Selector.DATA_SPY))
const scrollSpysLength = scrollSpys.length .forEach((spy) => new ScrollSpy(spy, Util.getDataAttributes(spy)))
for (let i = scrollSpysLength; i--;) {
const $spy = $(scrollSpys[i])
ScrollSpy._jQueryInterface.call($spy, $spy.data())
}
}) })
/** /**
@ -316,11 +327,15 @@ $(window).on(Event.LOAD_DATA_API, () => {
* ------------------------------------------------------------------------ * ------------------------------------------------------------------------
*/ */
$.fn[NAME] = ScrollSpy._jQueryInterface const $ = Util.jQuery
$.fn[NAME].Constructor = ScrollSpy if (typeof $ !== 'undefined') {
$.fn[NAME].noConflict = () => { const JQUERY_NO_CONFLICT = $.fn[NAME]
$.fn[NAME] = JQUERY_NO_CONFLICT $.fn[NAME] = ScrollSpy._jQueryInterface
return ScrollSpy._jQueryInterface $.fn[NAME].Constructor = ScrollSpy
$.fn[NAME].noConflict = () => {
$.fn[NAME] = JQUERY_NO_CONFLICT
return ScrollSpy._jQueryInterface
}
} }
export default ScrollSpy export default ScrollSpy

View File

@ -80,7 +80,7 @@ $(function () {
.show() .show()
.find('#scrollspy-example') .find('#scrollspy-example')
.bootstrapScrollspy({ .bootstrapScrollspy({
target: '#ss-target' target: 'ss-target'
}) })
$scrollspy.one('scroll', function () { $scrollspy.one('scroll', function () {
@ -127,7 +127,7 @@ $(function () {
.show() .show()
.find('#scrollspy-example') .find('#scrollspy-example')
.bootstrapScrollspy({ .bootstrapScrollspy({
target: document.getElementById('#ss-target') target: document.getElementById('ss-target')
}) })
$scrollspy.one('scroll', function () { $scrollspy.one('scroll', function () {
@ -557,7 +557,7 @@ $(function () {
$scrollspy $scrollspy
.bootstrapScrollspy({ .bootstrapScrollspy({
target: '#navigation', target: '#navigation',
offset: $scrollspy.position().top offset: $scrollspy[0].offsetTop
}) })
.one('scroll', function () { .one('scroll', function () {
assert.strictEqual($('.active').length, 1, '"active" class on only one element present') assert.strictEqual($('.active').length, 1, '"active" class on only one element present')
@ -663,11 +663,11 @@ $(function () {
method: 'offset' method: 'offset'
}) })
} else if (type === 'data') { } else if (type === 'data') {
$(window).trigger('load') EventHandler.trigger(window, 'load')
} }
var $target = $('#div-' + type + 'm-2') var $target = $('#div-' + type + 'm-2')
var scrollspy = $content.data('bs.scrollspy') var scrollspy = Data.getData($content[0], 'bs.scrollspy')
assert.ok(scrollspy._offsets[1] === $target.offset().top, 'offset method with ' + type + ' option') assert.ok(scrollspy._offsets[1] === $target.offset().top, 'offset method with ' + type + ' option')
assert.ok(scrollspy._offsets[1] !== $target.position().top, 'position method with ' + type + ' option') assert.ok(scrollspy._offsets[1] !== $target.position().top, 'position method with ' + type + ' option')
@ -710,11 +710,11 @@ $(function () {
method: 'position' method: 'position'
}) })
} else if (type === 'data') { } else if (type === 'data') {
$(window).trigger('load') EventHandler.trigger(window, 'load')
} }
var $target = $('#div-' + type + 'm-2') var $target = $('#div-' + type + 'm-2')
var scrollspy = $content.data('bs.scrollspy') var scrollspy = Data.getData($content[0], 'bs.scrollspy')
assert.ok(scrollspy._offsets[1] !== $target.offset().top, 'offset method with ' + type + ' option') assert.ok(scrollspy._offsets[1] !== $target.offset().top, 'offset method with ' + type + ' option')
assert.ok(scrollspy._offsets[1] === $target.position().top, 'position method with ' + type + ' option') assert.ok(scrollspy._offsets[1] === $target.position().top, 'position method with ' + type + ' option')

View File

@ -88,7 +88,10 @@
<script src="../../../node_modules/jquery/dist/jquery.slim.min.js"></script> <script src="../../../node_modules/jquery/dist/jquery.slim.min.js"></script>
<script src="../../../site/docs/4.2/assets/js/vendor/popper.min.js"></script> <script src="../../../site/docs/4.2/assets/js/vendor/popper.min.js"></script>
<script src="../../dist/dom/data.js"></script>
<script src="../../dist/dom/eventHandler.js"></script> <script src="../../dist/dom/eventHandler.js"></script>
<script src="../../dist/dom/manipulator.js"></script>
<script src="../../dist/dom/selectorEngine.js"></script>
<script src="../../dist/util.js"></script> <script src="../../dist/util.js"></script>
<script src="../../dist/scrollspy.js"></script> <script src="../../dist/scrollspy.js"></script>
<script src="../../dist/dropdown.js"></script> <script src="../../dist/dropdown.js"></script>