Skip to content

Commit

Permalink
feat: pause the carousel when the page is hidden
Browse files Browse the repository at this point in the history
  • Loading branch information
ubermanu committed Jun 2, 2023
1 parent 916923d commit ceeb64f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
21 changes: 19 additions & 2 deletions src/lib/components/Carousel/carousel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { delegateEventListeners } from '$lib/helpers/events.js'
import { traveller } from '$lib/helpers/traveller.js'
import { generateId } from '$lib/helpers/uuid.js'
import { activeElement } from '$lib/stores/activeElement.js'
import { documentVisible } from '$lib/stores/documentVisible.js'
import { reducedMotion } from '$lib/stores/reducedMotion.js'
import type { Action } from 'svelte/action'
import { derived, get, readable, readonly, writable } from 'svelte/store'
Expand Down Expand Up @@ -198,8 +199,10 @@ export const createCarousel = (config?: CarouselConfig) => {
let wasPlaying = false

const onCarouselMouseEnter = () => {
wasPlaying = get(status$) === 'playing'
pause()
if (!wasPlaying) {
wasPlaying = get(status$) === 'playing'
pause()
}
}

const onCarouselMouseLeave = () => {
Expand Down Expand Up @@ -260,11 +263,25 @@ export const createCarousel = (config?: CarouselConfig) => {
}
})

// Force the carousel to pause when the page is hidden
const unsubscribe3 = documentVisible.subscribe((visible) => {
if (!visible && !wasPlaying) {
if (get(status$) === 'playing') {
pause()
wasPlaying = true
}
} else if (visible && wasPlaying) {
play()
wasPlaying = false
}
})

return {
destroy() {
removeListeners()
unsubscribe()
unsubscribe2()
unsubscribe3()
pause()
rootNode = null
},
Expand Down
19 changes: 19 additions & 0 deletions src/lib/stores/documentVisible.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { browser } from '$lib/helpers/environment.js'
import { readable } from 'svelte/store'

/** A store that tracks whether the document is visible */
export const documentVisible = readable(true, (set) => {
if (!browser) {
return () => {}
}

const setDocumentVisible = () => {
set(!document.hidden)
}

document.addEventListener('visibilitychange', setDocumentVisible)

return () => {
document.removeEventListener('visibilitychange', setDocumentVisible)
}
})

0 comments on commit ceeb64f

Please sign in to comment.