2024-08-06 11:32:06 +00:00
|
|
|
import { ref, onMounted, onBeforeUnmount } from 'vue'
|
2024-08-06 09:07:36 +00:00
|
|
|
export function useAdaptation(sizes, handleChange) {
|
|
|
|
const mediaQueryLists = sizes.map(size => window.matchMedia(`(max-width: ${size.maxWidth})`));
|
2024-08-06 11:32:06 +00:00
|
|
|
const currentDevice = ref(getCurrentDevice())
|
2024-08-06 09:07:36 +00:00
|
|
|
function getCurrentDevice() {
|
|
|
|
for (let i = 0; i < mediaQueryLists.length; i++) {
|
|
|
|
if (mediaQueryLists[i].matches) {
|
|
|
|
return sizes[i].maxWidth;
|
|
|
|
}
|
|
|
|
}
|
2024-08-06 11:32:06 +00:00
|
|
|
return sizes[sizes.length - 1].maxWidth
|
2024-08-06 09:07:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const changeHandler = (newValue) => {
|
|
|
|
if (typeof handleChange === 'function') {
|
|
|
|
handleChange(newValue);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const mediaQueryChangeHandler = () => {
|
|
|
|
const newDevice = getCurrentDevice();
|
|
|
|
if (currentDevice.value !== newDevice) {
|
|
|
|
currentDevice.value = newDevice;
|
|
|
|
changeHandler(newDevice);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
let cleanupHandlers = [];
|
|
|
|
|
|
|
|
onMounted(() => {
|
|
|
|
mediaQueryLists.forEach(query => {
|
|
|
|
query.addEventListener('change', mediaQueryChangeHandler);
|
|
|
|
cleanupHandlers.push(() => query.removeEventListener('change', mediaQueryChangeHandler));
|
|
|
|
});
|
|
|
|
// Ensure the initial value is correct and trigger the changeHandler with the initial value
|
|
|
|
const initialDevice = getCurrentDevice();
|
|
|
|
currentDevice.value = initialDevice;
|
|
|
|
changeHandler(initialDevice);
|
|
|
|
});
|
|
|
|
|
|
|
|
onBeforeUnmount(() => {
|
|
|
|
cleanupHandlers.forEach(cleanup => cleanup());
|
|
|
|
});
|
|
|
|
|
|
|
|
return { maxWidth: currentDevice };
|
|
|
|
}
|