Skip to content

Instantly share code, notes, and snippets.

@pryley
Last active September 12, 2021 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pryley/3bc6d2f01aa5b68f829a5fbeb19abbd8 to your computer and use it in GitHub Desktop.
Save pryley/3bc6d2f01aa5b68f829a5fbeb19abbd8 to your computer and use it in GitHub Desktop.
tiny-swiper plugin for breakpoints
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