useResizeGridColumns.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { useLocalStorage, useWindowSize } from '@vueuse/core'
  3. import { shallowRef, computed, type Ref } from 'vue'
  4. export const DEFAULT_SIDEBAR_WIDTH = 260
  5. export const MINIMUM_SIDEBAR_WIDTH = 200
  6. export const SIDEBAR_COLLAPSED_WIDTH = 48
  7. export const useResizeGridColumns = (storageKey?: string) => {
  8. const isSidebarCollapsed = shallowRef(false)
  9. let currentSidebarWidth: Ref<number>
  10. const storageId = `${storageKey}-sidebar-width`
  11. if (storageKey) {
  12. currentSidebarWidth = useLocalStorage(storageId, DEFAULT_SIDEBAR_WIDTH)
  13. } else {
  14. currentSidebarWidth = shallowRef(DEFAULT_SIDEBAR_WIDTH)
  15. }
  16. const { width: screenWidth } = useWindowSize()
  17. const maxWidth = computed(() => screenWidth.value / 3)
  18. const gridColumns = computed(() => {
  19. const width = isSidebarCollapsed.value
  20. ? SIDEBAR_COLLAPSED_WIDTH
  21. : currentSidebarWidth.value
  22. return {
  23. gridTemplateColumns: `${width}px 1fr`,
  24. }
  25. })
  26. const resizeSidebar = (width: number) => {
  27. if (width <= MINIMUM_SIDEBAR_WIDTH || width >= maxWidth.value) return
  28. currentSidebarWidth.value = width
  29. }
  30. const collapseSidebar = () => {
  31. isSidebarCollapsed.value = true
  32. }
  33. const expandSidebar = () => {
  34. isSidebarCollapsed.value = false
  35. }
  36. const resetSidebarWidth = () => {
  37. currentSidebarWidth.value = DEFAULT_SIDEBAR_WIDTH
  38. }
  39. return {
  40. currentSidebarWidth,
  41. maxSidebarWidth: maxWidth,
  42. minSidebarWidth: MINIMUM_SIDEBAR_WIDTH,
  43. gridColumns,
  44. isSidebarCollapsed,
  45. resizeSidebar,
  46. collapseSidebar,
  47. expandSidebar,
  48. resetSidebarWidth,
  49. }
  50. }