Created
April 28, 2022 07:46
-
-
Save loilo/f229e20870228dca6d866b748cb07061 to your computer and use it in GitHub Desktop.
useElementBreakpoints – Vue Composable for Element breakpoints
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// useElementBreakpoints is a Vue 3 composable that matches an element's width (or height) against a set of predefined breakpoints | |
// It needs @vueuse/core to be installed and uses an equivalent breakpoints input as well as an equivalent returned API | |
import { computed, Ref } from 'vue' | |
import { useElementSize, MaybeElementRef } from '@vueuse/core' | |
export type Breakpoints<K extends string = string> = Record<K, number> | |
export type ElementBreakpointsOptions = { dimension: 'width' | 'height' } | |
/** | |
* Reactive element breakpoints | |
*/ | |
export function useElementBreakpoints<K extends string>( | |
target: MaybeElementRef, | |
breakpoints: Breakpoints<K>, | |
{ dimension = 'width' }: Partial<ElementBreakpointsOptions> = {} | |
) { | |
let size = useElementSize(target)[dimension] | |
let shortcutMethods = Object.keys(breakpoints).reduce( | |
(shortcuts, breakpoint) => { | |
Object.defineProperty(shortcuts, breakpoint, { | |
get: () => computed(() => size.value >= breakpoints[breakpoint as K]), | |
enumerable: true, | |
configurable: true, | |
}) | |
return shortcuts | |
}, | |
{} as Record<K, Ref<boolean>> | |
) | |
return { | |
greater: (breakpoint: K) => | |
computed(() => size.value >= breakpoints[breakpoint]), | |
smaller: (breakpoint: K) => | |
computed(() => size.value < breakpoints[breakpoint]), | |
between: (lowerBreakpoint: K, upperBreakpoint: K) => | |
computed( | |
() => | |
size.value >= breakpoints[lowerBreakpoint] && | |
size.value < breakpoints[upperBreakpoint] | |
), | |
isGreater: (breakpoint: K) => size.value >= breakpoints[breakpoint], | |
isSmaller: (breakpoint: K) => size.value < breakpoints[breakpoint], | |
isInBetween: (lowerBreakpoint: K, upperBreakpoint: K) => | |
size.value >= breakpoints[lowerBreakpoint] && | |
size.value < breakpoints[upperBreakpoint], | |
...shortcutMethods, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment