fix: 🐛 when editing polls, keep votes for unmodified choices

This commit is contained in:
ThatOneCalculator 2023-06-18 18:36:26 -07:00
parent 10b9030368
commit 6fd240a764
No known key found for this signature in database
GPG Key ID: 8703CACD01000000

View File

@ -33,6 +33,7 @@ import { renderActivity } from "@/remote/activitypub/renderer/index.js";
import renderNote from "@/remote/activitypub/renderer/note.js";
import renderUpdate from "@/remote/activitypub/renderer/update.js";
import { deliverToRelays } from "@/services/relay.js";
import { deliverQuestionUpdate } from "@/services/note/polls/update.js";
import { fetchMeta } from "@/misc/fetch-meta.js";
export const meta = {
@ -476,14 +477,19 @@ export default define(meta, paramDef, async (ps, user) => {
if (poll.noteVisibility !== ps.visibility) {
pollUpdate.noteVisibility = ps.visibility;
}
// We can't do an unordered equal check because the order of choices
// is important and if it changes, we need to reset the votes.
if (JSON.stringify(poll.choices) !== JSON.stringify(pp.choices)) {
pollUpdate.choices = pp.choices;
pollUpdate.votes = new Array(pp.choices.length).fill(0);
// Keep votes for unmodified choices, reset votes if choice is modified or new
const oldVoteCounts = new Map<string, number>();
for (let i = 0; i < poll.choices.length; i++) {
oldVoteCounts.set(poll.choices[i], poll.votes[i]);
}
const newVotes = pp.choices.map(
(choice) => oldVoteCounts.get(choice) || 0,
);
pollUpdate.choices = pp.choices;
pollUpdate.votes = newVotes;
if (notEmpty(pollUpdate)) {
await Polls.update(note.id, pollUpdate);
await deliverQuestionUpdate(note.id);
}
publishing = true;
}