Skip to content

Commit

Permalink
feat: add top bar composables
Browse files Browse the repository at this point in the history
  • Loading branch information
manuelodelain committed Jun 13, 2024
1 parent a3f5c23 commit b028d64
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
45 changes: 45 additions & 0 deletions composables/use-top-bar-scroll.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import throttle from 'lodash/throttle'

export function useTopBarScroll(hiddenThresholdDown = 130, hiddenThresholdUp = 30) {
const { isHidden, isOnPageTop } = useTopBarState()

let scrollY = 0
let scrollDirection = 1
let scrollOffset = 0
let scrollCallback: null | EventListener = null

function update() {
const newScrollY = Math.abs(window.scrollY)
isOnPageTop.value = newScrollY < hiddenThresholdDown

const newScrollDirection = newScrollY === scrollY ? scrollDirection : newScrollY >= scrollY ? 1 : -1

if (newScrollDirection !== scrollDirection) scrollOffset = 0

// scroll dist from last reset
scrollOffset += Math.abs(newScrollY - scrollY)
scrollY = newScrollY
scrollDirection = newScrollDirection

const hidden
= scrollDirection === 1
? scrollOffset > hiddenThresholdDown
: newScrollY > hiddenThresholdDown && scrollOffset < hiddenThresholdUp

if (hidden !== isHidden.value) isHidden.value = hidden
}

onMounted(() => {
scrollY = window.scrollY
scrollCallback = throttle(update, 150)

update()
window.addEventListener('scroll', scrollCallback, { passive: true })
})

onBeforeUnmount(() => {
scrollCallback && window.removeEventListener('scroll', scrollCallback)
})

return { isHidden, isOnPageTop }
}
6 changes: 6 additions & 0 deletions composables/use-top-bar-state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export function useTopBarState() {
const isHidden = useState('topBarIsHidden', () => false)
const isOnPageTop = useState('topBarIsOnPageTop', () => false)

return { isHidden, isOnPageTop }
}

0 comments on commit b028d64

Please sign in to comment.