useCollapseHandler.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { useLocalStorage } from '@vueuse/core'
  3. import { onMounted, type Ref, ref, watch } 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. return
  27. }
  28. emit('expand', true)
  29. }
  30. onMounted(() => {
  31. // Set up watcher on the local storage value, so other browser tabs can sync their collapse states.
  32. if (options?.storageKey) {
  33. watch(
  34. isCollapsed,
  35. (newValue) => {
  36. if (newValue) {
  37. emit('collapse', true)
  38. return
  39. }
  40. emit('expand', true)
  41. },
  42. {
  43. immediate: true,
  44. },
  45. )
  46. }
  47. })
  48. return {
  49. isCollapsed,
  50. toggleCollapse,
  51. }
  52. }