opnform/client/stores/forms.js

83 lines
2.1 KiB
JavaScript
Raw Normal View History

2023-12-14 15:53:05 +00:00
import {defineStore} from 'pinia'
2023-12-09 14:47:03 +00:00
2023-12-14 15:53:05 +00:00
export const formsEndpoint = '/open/workspaces/{workspaceId}/forms'
2023-12-09 14:47:03 +00:00
export let currentPage = 1
export const useFormsStore = defineStore('forms', {
state: () => ({
content: [],
loading: false
}),
getters: {
getById: (state) => (id) => {
if (state.content.length === 0) return null
return state.content.find(item => item.id === id)
},
getBySlug: (state) => (slug) => {
if (state.content.length === 0) return null
return state.content.find(item => item.slug === slug)
},
getAllTags: (state) => {
if (state.content.length === 0) return []
let allTags = []
state.content.forEach(form => {
2023-12-14 15:53:05 +00:00
if (form.tags && form.tags.length > 0) {
2023-12-09 14:47:03 +00:00
allTags = allTags.concat(form.tags)
}
})
return allTags.filter((item, i, ar) => ar.indexOf(item) === i)
}
},
actions: {
2023-12-14 15:53:05 +00:00
set(items) {
2023-12-09 14:47:03 +00:00
this.content = items
},
2023-12-14 15:53:05 +00:00
append(items) {
2023-12-09 14:47:03 +00:00
this.content = this.content.concat(items)
},
2023-12-14 15:53:05 +00:00
addOrUpdate(item) {
2023-12-09 14:47:03 +00:00
this.content = this.content.filter((val) => val.id !== item.id)
this.content.push(item)
},
2023-12-14 15:53:05 +00:00
remove(item) {
2023-12-09 14:47:03 +00:00
this.content = this.content.filter((val) => val.id !== item.id)
},
2023-12-14 15:53:05 +00:00
startLoading() {
2023-12-09 14:47:03 +00:00
this.loading = true
},
2023-12-14 15:53:05 +00:00
stopLoading() {
2023-12-09 14:47:03 +00:00
this.loading = false
},
2023-12-14 15:53:05 +00:00
resetState() {
2023-12-09 14:47:03 +00:00
this.set([])
this.stopLoading()
currentPage = 1
},
2023-12-14 15:53:05 +00:00
load(workspaceId) {
2023-12-09 14:47:03 +00:00
this.startLoading()
2023-12-16 18:21:03 +00:00
return useOpnApi(formsEndpoint.replace('{workspaceId}', workspaceId) + '?page=' + currentPage)
.then(({data, error}) => {
2023-12-14 15:53:05 +00:00
if (currentPage === 1) {
2023-12-16 18:21:03 +00:00
this.set(data.value.data)
2023-12-09 14:47:03 +00:00
} else {
2023-12-16 18:21:03 +00:00
this.append(data.value.data)
2023-12-09 14:47:03 +00:00
}
2023-12-16 18:21:03 +00:00
if (currentPage < data.value.meta.last_page) {
2023-12-09 14:47:03 +00:00
currentPage += 1
this.load(workspaceId)
} else {
this.stopLoading()
currentPage = 1
}
})
},
2023-12-14 15:53:05 +00:00
loadIfEmpty(workspaceId) {
2023-12-09 14:47:03 +00:00
if (this.content.length === 0) {
return this.load(workspaceId)
}
this.stopLoading()
return Promise.resolve()
}
}
})