useScrollPosition.ts 875 B

123456789101112131415161718192021222324252627282930
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { onActivated, ref, type ShallowRef } from 'vue'
  3. import { onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router'
  4. export const useScrollPosition = (
  5. scrollContainer?: ShallowRef<HTMLElement | null>,
  6. ) => {
  7. const scrollPosition = ref<number>()
  8. const storeScrollPosition = () => {
  9. if (!scrollContainer?.value) return
  10. scrollPosition.value = scrollContainer.value?.scrollTop
  11. }
  12. const restoreScrollPosition = () => {
  13. if (!scrollContainer?.value || scrollPosition.value === undefined) return
  14. scrollContainer.value.scrollTop = scrollPosition.value
  15. }
  16. onActivated(restoreScrollPosition)
  17. onBeforeRouteLeave(storeScrollPosition)
  18. onBeforeRouteUpdate(storeScrollPosition)
  19. return {
  20. scrollPosition,
  21. storeScrollPosition,
  22. restoreScrollPosition,
  23. }
  24. }