Last active
September 12, 2021 17:51
-
-
Save pryley/3bc6d2f01aa5b68f829a5fbeb19abbd8 to your computer and use it in GitHub Desktop.
tiny-swiper plugin for breakpoints
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { SwiperInstance, SwiperPlugin } from '../core/index' | |
import { Options } from '../core/options' | |
export default <SwiperPlugin>function SwiperPluginBreakpoints ( | |
instance: SwiperInstance, | |
options: Options, | |
) { | |
const isEnabled = Boolean(options.breakpoints) | |
if (!isEnabled) return | |
let timerId | |
let lastCallTime = 0 | |
let wait = 200 | |
const resizeListener = () => { | |
lastCallTime = Date.now() | |
if (timerId === undefined) { | |
timerId = startTimer(timerExpired) | |
} | |
} | |
const startTimer = (pendingFunc) => { | |
stopTimer() | |
return window.requestAnimationFrame(pendingFunc) | |
} | |
const stopTimer = () => { | |
window.cancelAnimationFrame(timerId) | |
timerId = undefined | |
} | |
const timerExpired = () => { | |
const timeSinceLastCall = Date.now() - lastCallTime | |
if (timeSinceLastCall >= wait || timeSinceLastCall < 0) { | |
stopTimer() | |
return updateSize() | |
} | |
timerId = startTimer(timerExpired) | |
} | |
const updateSize = () => { | |
for (const [breakpoint, values] of Object.entries(options.breakpoints)) { | |
if (instance.env.element.$el.offsetWidth >= +breakpoint) { | |
instance.options = Object.assign(instance.options, values) | |
} | |
} | |
instance.updateSize() | |
} | |
instance.on('after-init', () => { | |
window.addEventListener('resize', resizeListener, { passive: true }) | |
window.requestAnimationFrame(updateSize) | |
}) | |
instance.on('before-destroy', () => { | |
stopTimer() | |
window.removeEventListener('resize', resizeListener) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment