adrema/resources/js/composables/useIndex.js

90 lines
2.2 KiB
JavaScript
Raw Normal View History

2023-12-16 13:08:17 +01:00
import {ref, inject, computed, onBeforeUnmount} from 'vue';
2023-07-27 17:22:06 +02:00
import {router} from '@inertiajs/vue3';
2023-08-25 00:23:38 +02:00
import useQueueEvents from './useQueueEvents.js';
2023-07-27 17:22:06 +02:00
2024-08-01 17:30:55 +02:00
export function useIndex(props, siteName = null) {
2023-12-16 13:08:17 +01:00
const axios = inject('axios');
2024-08-01 17:30:55 +02:00
if (siteName !== null) {
var {startListener, stopListener} = useQueueEvents(siteName, () => reload(false));
}
2023-07-27 17:22:06 +02:00
const rawProps = JSON.parse(JSON.stringify(props));
const inner = {
data: ref(rawProps.data),
meta: ref(rawProps.meta),
2024-01-25 23:40:29 +01:00
filter: ref(rawProps.meta.filter ? rawProps.meta.filter : {}),
2023-07-27 17:22:06 +02:00
};
function toFilterString(data) {
return btoa(encodeURIComponent(JSON.stringify(data)));
}
2024-01-25 23:40:29 +01:00
const filterString = computed(() => toFilterString(inner.filter.value));
2023-07-27 17:22:06 +02:00
2024-01-25 23:40:29 +01:00
function reload(resetPage = true, data) {
2023-07-27 17:22:06 +02:00
var data = {
filter: filterString.value,
2023-10-31 10:38:32 +01:00
page: resetPage ? 1 : inner.meta.value.current_page,
...data,
2023-07-27 17:22:06 +02:00
};
router.visit(window.location.pathname, {
data,
preserveState: true,
2023-10-31 10:38:32 +01:00
only: ['data'],
2023-07-27 17:22:06 +02:00
onSuccess: (page) => {
inner.data.value = page.props.data.data;
2024-01-25 23:40:29 +01:00
inner.meta.value = {
...inner.meta.value,
...page.props.data.meta,
};
2023-07-27 17:22:06 +02:00
},
});
}
2023-10-31 10:38:32 +01:00
function reloadPage(page) {
2024-01-25 23:40:29 +01:00
reload(false, {page: page});
2023-10-31 10:38:32 +01:00
}
2023-07-27 17:22:06 +02:00
function can(permission) {
return inner.meta.value.can[permission];
}
function getFilter(value) {
2024-01-25 23:40:29 +01:00
return inner.filter.value[value];
2023-07-27 17:22:06 +02:00
}
function setFilter(key, value) {
2024-01-25 23:40:29 +01:00
inner.filter.value[key] = value;
reload(true);
2023-07-27 17:22:06 +02:00
}
2024-08-01 17:30:55 +02:00
if (siteName !== null) {
startListener();
onBeforeUnmount(() => stopListener());
}
2023-07-27 17:22:06 +02:00
return {
data: inner.data,
can,
getFilter,
setFilter,
meta: inner.meta,
filterString,
router,
toFilterString,
2023-10-31 10:38:32 +01:00
reloadPage,
2023-12-16 13:08:17 +01:00
axios,
2023-07-27 17:22:06 +02:00
};
}
const indexProps = {
data: {
default: () => {
return {data: [], meta: {}};
},
type: Object,
},
};
export {indexProps};