useResizeGridColumns.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. import { SidebarPosition } from '#desktop/components/layout/types.ts'
  5. export const DEFAULT_START_SIDEBAR_WIDTH = 260
  6. export const DEFAULT_END_SIDEBAR_WIDTH = 360
  7. export const MINIMUM_START_SIDEBAR_WIDTH = 200
  8. export const MINIMUM_END_SIDEBAR_WIDTH = 300
  9. export const SIDEBAR_COLLAPSED_WIDTH = 56
  10. export const useResizeGridColumns = (
  11. storageKey?: string,
  12. position: SidebarPosition = SidebarPosition.Start,
  13. ) => {
  14. const defaultSidebarWidth =
  15. position === SidebarPosition.Start
  16. ? DEFAULT_START_SIDEBAR_WIDTH
  17. : DEFAULT_END_SIDEBAR_WIDTH
  18. const minSidebarWidth =
  19. position === SidebarPosition.Start
  20. ? MINIMUM_START_SIDEBAR_WIDTH
  21. : MINIMUM_END_SIDEBAR_WIDTH
  22. const isSidebarCollapsed = shallowRef(false)
  23. let currentSidebarWidth: Ref<number>
  24. const storageId = `${storageKey}-sidebar-width`
  25. if (storageKey) {
  26. currentSidebarWidth = useLocalStorage(storageId, defaultSidebarWidth)
  27. } else {
  28. currentSidebarWidth = shallowRef(defaultSidebarWidth)
  29. }
  30. const { width: screenWidth } = useWindowSize()
  31. const maxWidth = computed(() => screenWidth.value / 3)
  32. const gridColumns = computed(() => {
  33. const width = isSidebarCollapsed.value
  34. ? SIDEBAR_COLLAPSED_WIDTH
  35. : currentSidebarWidth.value
  36. if (position === SidebarPosition.End)
  37. return {
  38. gridTemplateColumns: `1fr ${width}px`,
  39. }
  40. return {
  41. gridTemplateColumns: `${width}px 1fr`,
  42. }
  43. })
  44. const resizeSidebar = (width: number) => {
  45. if (width <= minSidebarWidth || width >= maxWidth.value) return
  46. currentSidebarWidth.value = width
  47. }
  48. const collapseSidebar = () => {
  49. isSidebarCollapsed.value = true
  50. }
  51. const expandSidebar = () => {
  52. isSidebarCollapsed.value = false
  53. }
  54. const resetSidebarWidth = () => {
  55. currentSidebarWidth.value = defaultSidebarWidth
  56. }
  57. return {
  58. currentSidebarWidth,
  59. maxSidebarWidth: maxWidth,
  60. minSidebarWidth,
  61. gridColumns,
  62. isSidebarCollapsed,
  63. resizeSidebar,
  64. collapseSidebar,
  65. expandSidebar,
  66. resetSidebarWidth,
  67. }
  68. }