@datametria/vue-components
Version:
DATAMETRIA Vue.js 3 Component Library with Multi-Brand Theming - 51 components + 10 composables with theming support, WCAG 2.2 AA, dark mode, responsive system
83 lines (69 loc) • 2.16 kB
text/typescript
import { ref, onMounted, onUnmounted } from 'vue'
export const breakpoints = {
xs: 475,
sm: 640,
md: 768,
lg: 1024,
xl: 1280,
'2xl': 1536
} as const
export type Breakpoint = keyof typeof breakpoints
export function useBreakpoints() {
const windowWidth = ref(0)
const updateWidth = () => {
windowWidth.value = window.innerWidth
}
const isGreaterOrEqual = (breakpoint: Breakpoint) => {
return windowWidth.value >= breakpoints[breakpoint]
}
const isLessOrEqual = (breakpoint: Breakpoint) => {
return windowWidth.value <= breakpoints[breakpoint]
}
const isBetween = (min: Breakpoint, max: Breakpoint) => {
return windowWidth.value >= breakpoints[min] && windowWidth.value <= breakpoints[max]
}
const getCurrentBreakpoint = (): Breakpoint => {
const width = windowWidth.value
if (width >= breakpoints['2xl']) return '2xl'
if (width >= breakpoints.xl) return 'xl'
if (width >= breakpoints.lg) return 'lg'
if (width >= breakpoints.md) return 'md'
if (width >= breakpoints.sm) return 'sm'
return 'xs'
}
// Reactive breakpoint checks
const isXs = () => windowWidth.value < breakpoints.sm
const isSm = () => isGreaterOrEqual('sm') && windowWidth.value < breakpoints.md
const isMd = () => isGreaterOrEqual('md') && windowWidth.value < breakpoints.lg
const isLg = () => isGreaterOrEqual('lg') && windowWidth.value < breakpoints.xl
const isXl = () => isGreaterOrEqual('xl') && windowWidth.value < breakpoints['2xl']
const is2xl = () => isGreaterOrEqual('2xl')
// Mobile/tablet/desktop helpers
const isMobile = () => windowWidth.value < breakpoints.md
const isTablet = () => isBetween('md', 'lg')
const isDesktop = () => isGreaterOrEqual('lg')
onMounted(() => {
updateWidth()
window.addEventListener('resize', updateWidth)
})
onUnmounted(() => {
window.removeEventListener('resize', updateWidth)
})
return {
windowWidth,
breakpoints,
isGreaterOrEqual,
isLessOrEqual,
isBetween,
getCurrentBreakpoint,
isXs,
isSm,
isMd,
isLg,
isXl,
is2xl,
isMobile,
isTablet,
isDesktop
}
}