useCollapseHandler.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { useLocalStorage } from '@vueuse/core'
  3. import { nextTick, onMounted, type Ref, ref } from 'vue'
  4. interface Emits {
  5. (event: 'collapse', arg: boolean): void
  6. (event: 'expand', arg: boolean): void
  7. }
  8. /**
  9. * @args emit - The emit function from the setup function
  10. * @args options.storageKey - The key to store the collapse state in local storage
  11. * * */
  12. export const useCollapseHandler = (
  13. emit: Emits,
  14. options?: { storageKey: string },
  15. ) => {
  16. let isCollapsed: Ref<boolean>
  17. if (options?.storageKey) {
  18. isCollapsed = useLocalStorage(options.storageKey, false)
  19. } else {
  20. isCollapsed = ref(false)
  21. }
  22. const toggleCollapse = () => {
  23. isCollapsed.value = !isCollapsed.value
  24. if (isCollapsed.value) {
  25. emit('collapse', true)
  26. } else {
  27. emit('expand', true)
  28. }
  29. }
  30. onMounted(() => {
  31. if (options?.storageKey) {
  32. nextTick(() => {
  33. // Share state on initial load
  34. if (isCollapsed.value) emit('collapse', true)
  35. else emit('expand', true)
  36. })
  37. }
  38. })
  39. return {
  40. isCollapsed,
  41. toggleCollapse,
  42. }
  43. }