pleroma-fe/src/stores/polls.js

68 lines
1.9 KiB
JavaScript
Raw Normal View History

2023-04-05 22:30:20 -06:00
import { merge } from 'lodash'
import { defineStore } from 'pinia'
2026-06-15 20:02:22 +03:00
import { useCredentialsStore } from 'src/stores/credentials.js'
import { fetchPoll, vote } from 'src/services/api/api.service.js'
2023-04-05 22:30:20 -06:00
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) {
2026-06-15 20:02:22 +03:00
fetchPoll({
pollId,
credentials: useCredentialsStore().current,
}).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 }) {
2026-06-15 20:02:22 +03:00
return vote({
pollId,
choices,
credentials: useCredentialsStore().current,
}).then((poll) => {
this.mergeOrAddPoll(poll)
return poll
})
2026-01-06 16:22:52 +02:00
},
},
2023-04-05 22:30:20 -06:00
})