File size: 1,167 Bytes
c6535db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { breakpointsTailwind, useBreakpoints } from '@vueuse/core'
import { ref, watch } from 'vue'

/**
 * Composable for element with responsive collapsed state
 * @param {string} breakpointThreshold - Breakpoint at which the element should become collapsible
 */
export const useResponsiveCollapse = (
    breakpointThreshold = 'lg'
) => {
    const breakpoints = useBreakpoints(breakpointsTailwind)

    const isSmallScreen = breakpoints.smallerOrEqual(breakpointThreshold)
    const isOpen = ref(!isSmallScreen.value)

    /**
     * Handles screen size changes to automatically open/close the element
     * when crossing the breakpoint threshold
     */
    const onIsSmallScreenChange = () => {
        if (isSmallScreen.value && isOpen.value) {
            isOpen.value = false
        } else if (!isSmallScreen.value && !isOpen.value) {
            isOpen.value = true
        }
    }

    watch(isSmallScreen, onIsSmallScreenChange)

    return {
        breakpoints,
        isOpen,
        isSmallScreen,

        open: () => (isOpen.value = true),
        close: () => (isOpen.value = false),
        toggle: () => (isOpen.value = !isOpen.value)
    }
}