pleroma-fe/src/stores/polls.js

61 lines
1.7 KiB
JavaScript
Raw Normal View History

2023-04-05 22:30:20 -06:00
import { merge } from 'lodash'
import { defineStore } from 'pinia'
export const usePollsStore = defineStore('polls', {
state: () => ({
// Contains key = id, value = number of trackers for this poll
trackedPolls: {},
2026-01-06 16:22:52 +02:00
pollsObject: {},
2023-04-05 22:30:20 -06:00
}),
actions: {
2026-01-06 16:22:52 +02:00
mergeOrAddPoll(poll) {
2023-04-05 22:30:20 -06:00
const existingPoll = this.pollsObject[poll.id]
// Make expired-state change trigger re-renders properly
poll.expired = Date.now() > Date.parse(poll.expires_at)
if (existingPoll) {
this.pollsObject[poll.id] = merge(existingPoll, poll)
} else {
this.pollsObject[poll.id] = poll
}
},
2026-01-06 16:22:52 +02:00
updateTrackedPoll(pollId) {
window.vuex.state.api.backendInteractor
.fetchPoll({ pollId })
.then((poll) => {
setTimeout(() => {
if (this.trackedPolls[pollId]) {
this.updateTrackedPoll(pollId)
}
}, 30 * 1000)
this.mergeOrAddPoll(poll)
})
2023-04-05 22:30:20 -06:00
},
2026-01-06 16:22:52 +02:00
trackPoll(pollId) {
2023-04-05 22:30:20 -06:00
if (!this.trackedPolls[pollId]) {
setTimeout(() => this.updateTrackedPoll(pollId), 30 * 1000)
}
const currentValue = this.trackedPolls[pollId]
if (currentValue) {
this.trackedPolls[pollId] = currentValue + 1
} else {
this.trackedPolls[pollId] = 1
}
},
2026-01-06 16:22:52 +02:00
untrackPoll(pollId) {
2023-04-05 22:30:20 -06:00
const currentValue = this.trackedPolls[pollId]
if (currentValue) {
this.trackedPolls[pollId] = currentValue - 1
} else {
this.trackedPolls[pollId] = 0
}
},
2026-01-06 16:22:52 +02:00
votePoll({ pollId, choices }) {
return window.vuex.state.api.backendInteractor
.vote({ pollId, choices })
.then((poll) => {
this.mergeOrAddPoll(poll)
return poll
})
},
},
2023-04-05 22:30:20 -06:00
})