2025-04-18 09:06:30 +01:00

85 lines
2.0 KiB
JavaScript

import { ref, computed, unref } from 'vue';
import { useEventListener } from './useEventListener';
let globalScreenRef = 0;
let globalWidthRef = 0;
let globalRealWidthRef = 0;
const screenMap = new Map();
screenMap.set('XS', 480);
screenMap.set('SM', 576);
screenMap.set('MD', 768);
screenMap.set('LG', 992);
screenMap.set('XL', 1200);
screenMap.set('XXL', 1600);
export function useBreakpoint() {
return {
screenRef: computed(() => unref(globalScreenRef)),
widthRef: globalWidthRef,
realWidthRef: globalRealWidthRef,
};
}
// Just call it once
export function createBreakpointListen(fn) {
const screenRef = ref('XL');
const realWidthRef = ref(window.innerWidth);
function getWindowWidth() {
const width = document.body.clientWidth;
const xs = screenMap.get('XS');
const sm = screenMap.get('SM');
const md = screenMap.get('MD');
const lg = screenMap.get('LG');
const xl = screenMap.get('XL');
const xxl = screenMap.set('XXL', 1600);
if (width < xs) {
screenRef.value = xs;
} else if (width < sm) {
screenRef.value = sm;
} else if (width < md) {
screenRef.value = md;
} else if (width < lg) {
screenRef.value = lg;
} else if (width < xl) {
screenRef.value = xl;
} else {
screenRef.value = xxl;
}
realWidthRef.value = width;
}
useEventListener({
el: window,
name: 'resize',
listener: () => {
getWindowWidth();
resizeFn();
},
// wait: 100,
});
getWindowWidth();
globalScreenRef = computed(() => unref(screenRef));
globalWidthRef = computed(() => screenMap.get(unref(screenRef)));
globalRealWidthRef = computed(() => unref(realWidthRef));
function resizeFn() {
fn?.({
screen: globalScreenRef,
width: globalWidthRef,
realWidth: globalRealWidthRef,
screenMap,
});
}
resizeFn();
return {
screenRef: globalScreenRef,
widthRef: globalWidthRef,
realWidthRef: globalRealWidthRef,
};
}