adrema/resources/js/composables/useInertiaApiIndex.js

125 lines
3.0 KiB
JavaScript
Raw Normal View History

2023-12-16 23:53:18 +01:00
import {computed, ref, inject, onBeforeUnmount} from 'vue';
import {router} from '@inertiajs/vue3';
import useQueueEvents from './useQueueEvents.js';
2024-08-01 18:25:25 +02:00
export function useIndex(props, siteName = null) {
2023-12-16 23:53:18 +01:00
const axios = inject('axios');
2024-08-01 18:25:25 +02:00
if (siteName !== null) {
var {startListener, stopListener} = useQueueEvents(siteName, () => reload(false));
}
2023-12-16 23:53:18 +01:00
const single = ref(null);
const rawProps = JSON.parse(JSON.stringify(props));
const inner = {
data: ref(rawProps.data),
meta: ref(rawProps.meta),
2024-01-29 22:07:33 +01:00
filter: ref(rawProps.meta.filter ? rawProps.meta.filter : {}),
2023-12-16 23:53:18 +01:00
};
function toFilterString(data) {
return btoa(encodeURIComponent(JSON.stringify(data)));
}
2024-01-29 22:07:33 +01:00
const filterString = computed(() => toFilterString(inner.filter.value));
2023-12-16 23:53:18 +01:00
function reload(resetPage = true, withMeta = true, data) {
data = {
filter: filterString.value,
page: resetPage ? 1 : inner.meta.value.current_page,
...data,
};
router.visit(window.location.pathname, {
data,
preserveState: true,
only: ['data'],
onSuccess: (page) => {
inner.data.value = page.props.data.data;
if (withMeta) {
inner.meta.value = {
...inner.meta.value,
...page.props.data.meta,
};
}
},
});
}
function reloadPage(page) {
reload(false, true, {page: page});
}
function can(permission) {
return inner.meta.value.can[permission];
}
function create() {
single.value = JSON.parse(JSON.stringify(inner.meta.value.default));
}
function edit(model) {
single.value = JSON.parse(JSON.stringify(model));
}
async function submit() {
single.value.id ? await axios.patch(single.value.links.update, single.value) : await axios.post(inner.meta.value.links.store, single.value);
reload();
single.value = null;
}
async function remove(model) {
await axios.delete(model.links.destroy);
reload();
}
function can(permission) {
return inner.meta.value.can[permission];
}
function cancel() {
single.value = null;
}
2024-01-29 22:07:33 +01:00
function getFilter(value) {
return inner.filter.value[value];
}
function setFilter(key, value) {
inner.filter.value[key] = value;
reload(true);
}
2024-08-01 18:25:25 +02:00
if (siteName !== null) {
startListener();
onBeforeUnmount(() => stopListener());
}
2023-12-16 23:53:18 +01:00
return {
data: inner.data,
meta: inner.meta,
single,
create,
edit,
reload,
reloadPage,
can,
router,
submit,
remove,
cancel,
axios,
2024-01-29 22:07:33 +01:00
setFilter,
getFilter,
2023-12-16 23:53:18 +01:00
};
}
const indexProps = {
data: {
default: () => {
return {data: [], meta: {}};
},
type: Object,
},
};
export {indexProps};