Skip to content

A platform for community discussion. Free, open, simple.

UX: Show voters their choices after voting in hidden-results polls (#42622)

Régis Hanol05e9a90a3e9c
diff --git a/plugins/poll/assets/javascripts/discourse/components/poll-info.gjs b/plugins/poll/assets/javascripts/discourse/components/poll-info.gjs
index d112d6d5021..79d68eb64b9 100644
--- a/plugins/poll/assets/javascripts/discourse/components/poll-info.gjs
+++ b/plugins/poll/assets/javascripts/discourse/components/poll-info.gjs
@@ -62,43 +62,40 @@ export default class PollInfoComponent extends Component {
return i18n("poll.total_votes", { count: this.totalVotes });
}
- get automaticCloseAgeLabel() {
- return i18n("poll.automatic_close.age", this.age);
+ get showAutomaticClose() {
+ return (
+ this.args.isAutomaticallyClosed ||
+ (!!this.args.closesAt && !this.args.closed)
+ );
}
- get automaticCloseClosesInLabel() {
- return i18n("poll.automatic_close.closes_in", this.timeLeft);
+ get automaticCloseLabel() {
+ return trustHTML(
+ this.args.isAutomaticallyClosed
+ ? i18n("poll.automatic_close.age", { age: this.age })
+ : i18n("poll.automatic_close.closes_in", { timeLeft: this.timeLeft })
+ );
}
get showMultipleHelpText() {
- return this.args.isMultiple && !this.args.showResults && !this.args.closed;
+ return (
+ this.args.isMultiple &&
+ !this.args.showResults &&
+ !this.args.showingVotedChoices &&
+ !this.args.closed
+ );
}
get closeTitle() {
- const closeDate = moment.utc(this.args.close, "YYYY-MM-DD HH:mm:ss Z");
- if (closeDate.isValid()) {
- return closeDate.format("LLL");
- } else {
- return "";
- }
+ return this.args.closesAt?.format("LLL") ?? "";
}
get age() {
- const closeDate = moment.utc(this.args.close, "YYYY-MM-DD HH:mm:ss Z");
- if (closeDate.isValid()) {
- return relativeAge(closeDate.toDate(), { addAgo: true });
- } else {
- return 0;
- }
+ return relativeAge(this.args.closesAt.toDate(), { addAgo: true });
}
get timeLeft() {
- const closeDate = moment.utc(this.args.close, "YYYY-MM-DD HH:mm:ss Z");
- if (closeDate.isValid()) {
- return moment().to(closeDate, true);
- } else {
- return 0;
- }
+ return moment().to(this.args.closesAt, true);
}
get resultsOnVote() {
@@ -147,8 +144,9 @@ export default class PollInfoComponent extends Component {
get showInstructionsSection() {
return (
+ this.args.showingVotedChoices ||
this.showMultipleHelpText ||
- this.args.close ||
+ this.showAutomaticClose ||
this.args.closedBy ||
this.resultsOnVote ||
this.resultsOnClose ||
@@ -178,30 +176,29 @@ export default class PollInfoComponent extends Component {
</div>
{{#if this.showInstructionsSection}}
<ul class="poll-info_instructions">
- {{#if (if @isDynamic true this.poll.dynamic)}}
+ {{#if @isDynamic}}
<li class="is-dynamic">
{{dIcon "shuffle"}}
<span>{{i18n "poll.dynamic.enabled_hint"}}</span>
</li>
{{/if}}
+ {{#if @showingVotedChoices}}
+ <li class="vote-recorded">
+ {{dIcon "check"}}
+ <span>{{i18n "poll.vote_recorded"}}</span>
+ </li>
+ {{/if}}
{{#if this.showMultipleHelpText}}
<li class="multiple-help-text">
{{dIcon "list-ul"}}
<span>{{this.multipleHelpText}}</span>
</li>
{{/if}}
- {{#if this.poll.close}}
- {{#if this.isAutomaticallyClosed}}
- <li title={{this.title}}>
- {{dIcon "lock"}}
- <span>{{this.automaticCloseAgeLabel}}</span>
- </li>
- {{else}}
- <li title={{this.title}}>
- {{dIcon "far-clock"}}
- <span>{{this.automaticCloseClosesInLabel}}</span>
- </li>
- {{/if}}
+ {{#if this.showAutomaticClose}}
+ <li title={{this.closeTitle}}>
+ {{dIcon (if @isAutomaticallyClosed "lock" "far-clock")}}
+ <span>{{this.automaticCloseLabel}}</span>
+ </li>
{{/if}}
{{#if @closedBy}}
<li class="poll-info_closed-by">
diff --git a/plugins/poll/assets/javascripts/discourse/components/poll-voted-choices.gjs b/plugins/poll/assets/javascripts/discourse/components/poll-voted-choices.gjs
new file mode 100644
index 00000000000..e93c97be308
--- /dev/null
+++ b/plugins/poll/assets/javascripts/discourse/components/poll-voted-choices.gjs
@@ -0,0 +1,50 @@
+import Component from "@glimmer/component";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import decoratePollOption from "../modifiers/decorate-poll-option";
+
+export default class PollVotedChoicesComponent extends Component {
+ get chosenOptions() {
+ const { options, votes, isRankedChoice } = this.args;
+
+ if (isRankedChoice) {
+ const ranks = new Map(
+ votes
+ .filter((vote) => vote.rank > 0)
+ .map((vote) => [vote.digest, vote.rank])
+ );
+
+ return options
+ .filter((option) => ranks.has(option.id))
+ .map((option) => ({ option, rank: ranks.get(option.id) }))
+ .sort((a, b) => a.rank - b.rank);
+ }
+
+ return options
+ .filter((option) => votes.includes(option.id))
+ .map((option) => ({ option }));
+ }
+
+ <template>
+ <div class="poll-voted-choices">
+ <span class="poll-voted-choices__title">
+ {{i18n "poll.voted_choices.title"}}
+ </span>
+ <ul class="poll-voted-choices__list">
+ {{#each this.chosenOptions as |choice|}}
+ <li class="poll-voted-choices__choice">
+ {{#if @isRankedChoice}}
+ <span class="poll-voted-choices__rank">{{choice.rank}}</span>
+ {{else}}
+ {{dIcon "check"}}
+ {{/if}}
+ <span
+ class="option-text"
+ {{decoratePollOption choice.option.html}}
+ ></span>
+ </li>
+ {{/each}}
+ </ul>
+ </div>
+ </template>
+}
diff --git a/plugins/poll/assets/javascripts/discourse/components/poll.gjs b/plugins/poll/assets/javascripts/discourse/components/poll.gjs
index f492d8c9b28..9f58346a490 100644
--- a/plugins/poll/assets/javascripts/discourse/components/poll.gjs
+++ b/plugins/poll/assets/javascripts/discourse/components/poll.gjs
@@ -1,5 +1,5 @@
import Component from "@glimmer/component";
-import { tracked } from "@glimmer/tracking";
+import { cached, tracked } from "@glimmer/tracking";
import { on } from "@ember/modifier";
import { action } from "@ember/object";
import { getOwner } from "@ember/owner";
@@ -12,6 +12,7 @@ import { trustHTML } from "@ember/template";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { deferAnonymousAction } from "discourse/lib/anonymous-action";
+import { afterRender } from "discourse/lib/decorators";
import round from "discourse/lib/round";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import { i18n } from "discourse-i18n";
@@ -26,6 +27,7 @@ import PollInfo from "../components/poll-info";
import PollOptions from "../components/poll-options";
import PollResultsPie from "../components/poll-results-pie";
import PollResultsTabs from "../components/poll-results-tabs";
+import PollVotedChoices from "../components/poll-voted-choices";
const FETCH_VOTERS_COUNT = 25;
const STAFF_ONLY = "staff_only";
@@ -49,8 +51,9 @@ export default class PollComponent extends Component {
@tracked preloadedVoters = this.defaultPreloadedVoters();
@tracked voterListExpanded = false;
- @tracked hasSavedVote = this.savedVote.length > 0;
+ @tracked hasSavedVote = this.rawSavedVote.length > 0;
@tracked showTally = false;
+ @tracked castingVote = false;
registerPollButtons = (element) => {
this.pollButtonsElement = element;
@@ -93,6 +96,8 @@ export default class PollComponent extends Component {
@tracked _showResults = this.initialShowResults();
+ @tracked _isAmendingVote = this.poll.amendingVoteToggle;
+
_toggleOption = (option, rank = 0) => {
if (this.isMultiple) {
const chosenIdx = this.vote.indexOf(option.id);
@@ -126,8 +131,16 @@ export default class PollComponent extends Component {
this.vote = [...this.vote];
};
+ get resultsRevealedByClose() {
+ return (
+ this.poll.results === ON_CLOSE &&
+ this.closed &&
+ this.poll.options.every((option) => option.votes !== undefined)
+ );
+ }
+
get showResults() {
- return this._showResults;
+ return this._showResults || this.resultsRevealedByClose;
}
set showResults(value) {
@@ -142,6 +155,29 @@ export default class PollComponent extends Component {
);
}
+ get isAmendingVote() {
+ return this._isAmendingVote;
+ }
+
+ set isAmendingVote(value) {
+ this._isAmendingVote = value;
+ this.poll.amendingVoteToggle = value;
+ }
+
+ get hasHiddenSavedVote() {
+ return (
+ this.hasSavedVote && !this.showResults && !this.resultsVisibilityAllowed
+ );
+ }
+
+ get showVotedChoices() {
+ return this.hasHiddenSavedVote && !this.isAmendingVote;
+ }
+
+ get votedChoices() {
+ return this.hasSavedVote ? this.rawSavedVote : [];
+ }
+
get resultsToggleAllowed() {
return !this.hideResultsDisabled && this.resultsVisibilityAllowed;
}
@@ -177,8 +213,12 @@ export default class PollComponent extends Component {
return this.savedVote;
}
+ get rawSavedVote() {
+ return this.args.post.polls_votes?.[this.poll.name] || [];
+ }
+
get savedVote() {
- return this.copyVote(this.args.post.polls_votes?.[this.poll.name] || []);
+ return this.copyVote(this.rawSavedVote);
}
copyVote(votes) {
@@ -271,9 +311,8 @@ export default class PollComponent extends Component {
return;
}
- if (!this.currentUser) {
- return;
- }
+ this.castingVote = true;
+ const castVote = this.copyVote(this.vote);
try {
const { poll } = await ajax("/polls/vote", {
@@ -281,7 +320,7 @@ export default class PollComponent extends Component {
data: {
post_id: this.post.id,
poll_name: this.poll.name,
- options: this.vote,
+ options: castVote,
},
});
@@ -289,11 +328,11 @@ export default class PollComponent extends Component {
if (!this.args.post.polls_votes) {
this.args.post.polls_votes = trackedObject();
}
- this.args.post.polls_votes[this.poll.name] = this.copyVote(this.vote);
+ this.args.post.polls_votes[this.poll.name] = castVote;
this.poll.inProgressVote = undefined;
Object.assign(this.poll, poll);
- this.appEvents.trigger("poll:voted", poll, this.post, this.vote);
+ this.appEvents.trigger("poll:voted", poll, this.post, castVote);
if (this.poll.results !== ON_CLOSE) {
this.showResults = true;
@@ -306,6 +345,9 @@ export default class PollComponent extends Component {
this.showResults = false;
}
}
+
+ this.isAmendingVote = false;
+ this.focusCurrentView();
} catch (error) {
if (error) {
if (!this.isMultiple && !this.isRankedChoice) {
@@ -315,6 +357,8 @@ export default class PollComponent extends Component {
} else {
this.dialog.alert(i18n("poll.error_while_casting_votes"));
}
+ } finally {
+ this.castingVote = false;
}
}
@@ -367,11 +411,15 @@ export default class PollComponent extends Component {
return this.status === CLOSED_STATUS || this.isAutomaticallyClosed;
}
+ @cached
+ get closesAt() {
+ return this.poll.close
+ ? moment.utc(this.poll.close, "YYYY-MM-DD HH:mm:ss Z")
+ : null;
+ }
+
get isAutomaticallyClosed() {
- return (
- (this.poll.close ?? false) &&
- moment.utc(this.poll.close, "YYYY-MM-DD HH:mm:ss Z") <= moment()
- );
+ return this.closesAt !== null && this.closesAt.valueOf() <= Date.now();
}
get hasVoted() {
@@ -418,6 +466,9 @@ export default class PollComponent extends Component {
this.vote.length === 1 &&
this.vote[0] === option.id
) {
+ if (this.isAmendingVote) {
+ return this.keepVote();
+ }
return this.removeVote();
}
@@ -432,12 +483,21 @@ export default class PollComponent extends Component {
}
}
- @action
- toggleResults() {
+ @afterRender
+ focusCurrentView() {
+ this.pollButtonsElement
+ ?.closest(".poll")
+ ?.querySelector(
+ this.showVotedChoices ? ".amend-vote" : "[data-poll-option-id] button"
+ )
+ ?.focus();
+ }
+
+ preserveButtonsPosition(callback) {
const anchor = this.pollButtonsElement;
const anchorTop = anchor?.getBoundingClientRect().top;
- this.showResults = !this.showResults;
+ callback();
if (anchorTop == null) {
return;
@@ -455,8 +515,51 @@ export default class PollComponent extends Component {
});
}
+ @action
+ toggleResults() {
+ this.preserveButtonsPosition(() => {
+ this.showResults = !this.showResults;
+ });
+ }
+
+ @action
+ amendVote() {
+ this.preserveButtonsPosition(() => {
+ this.isAmendingVote = true;
+ });
+ this.focusCurrentView();
+ }
+
+ @action
+ keepVote() {
+ this.preserveButtonsPosition(() => {
+ this._vote = this.savedVote;
+ this.poll.inProgressVote = undefined;
+ this.isAmendingVote = false;
+ });
+ this.focusCurrentView();
+ }
+
+ get isVoteDirty() {
+ const key = (votes) =>
+ (this.isRankedChoice
+ ? votes
+ .filter((vote) => vote.rank !== 0)
+ .map((vote) => `${vote.digest}:${vote.rank}`)
+ : [...votes]
+ )
+ .sort()
+ .join();
+
+ return key(this.rawSavedVote) !== key(this.vote);
+ }
+
get canCastVotes() {
- if (this.closed || !this.currentUser) {
+ if (this.closed || this.castingVote || !this.currentUser) {
+ return false;
+ }
+
+ if (this.hasSavedVote && !this.isVoteDirty) {
return false;
}
@@ -485,7 +588,11 @@ export default class PollComponent extends Component {
}
get showCastVotesButton() {
- return (this.isMultiple || this.isRankedChoice) && !this.showResults;
+ return (
+ (this.isMultiple || this.isRankedChoice) &&
+ !this.showResults &&
+ !this.showVotedChoices
+ );
}
get castVotesButtonClass() {
@@ -498,6 +605,22 @@ export default class PollComponent extends Component {
return !this.castVotesDisabled ? "check" : "far-square";
}
+ get castVotesButtonLabel() {
+ return i18n(
+ this.hasSavedVote
+ ? "poll.cast-votes.update_label"
+ : "poll.cast-votes.label"
+ );
+ }
+
+ get castVotesButtonTitle() {
+ return i18n(
+ this.hasSavedVote
+ ? "poll.cast-votes.update_title"
+ : "poll.cast-votes.title"
+ );
+ }
+
get castVotesDisabled() {
return !this.canCastVotes;
}
@@ -509,23 +632,33 @@ export default class PollComponent extends Component {
get showShowResultsButton() {
return (
!this.showResults &&
- !this.hideResultsDisabled &&
+ this.resultsToggleAllowed &&
!(this.poll.results === ON_VOTE && !this.hasSavedVote && !this.isMe) &&
- !(this.poll.results === ON_CLOSE && !this.closed) &&
- !(this.poll.results === STAFF_ONLY && !this.isStaff) &&
this.voters > 0
);
}
+ get canChangeVote() {
+ return !this.closed && !this.hideResultsDisabled;
+ }
+
get showRemoveVoteButton() {
return (
+ this.canChangeVote &&
!this.showResults &&
- !this.closed &&
- !this.hideResultsDisabled &&
- this.hasSavedVote
+ this.hasSavedVote &&
+ !this.showVotedChoices
);
}
+ get showAmendVoteButton() {
+ return this.canChangeVote && this.showVotedChoices;
+ }
+
+ get showKeepVoteButton() {
+ return this.hasHiddenSavedVote && this.isAmendingVote;
+ }
+
get isCheckbox() {
return this.isMultiple;
}
@@ -669,6 +802,8 @@ export default class PollComponent extends Component {
this.poll.inProgressVote = undefined;
this.appEvents.trigger("poll:voted", poll, this.post, this.vote);
this.showResults = false;
+ this.isAmendingVote = false;
+ this.focusCurrentView();
})
.catch((error) => popupAjaxError(error));
}
@@ -815,6 +950,12 @@ export default class PollComponent extends Component {
{{/if}}
{{/if}}
</div>
+ {{else if this.showVotedChoices}}
+ <PollVotedChoices
+ @options={{this.options}}
+ @votes={{this.votedChoices}}
+ @isRankedChoice={{this.isRankedChoice}}
+ />
{{else}}
<PollOptions
@isCheckbox={{this.isCheckbox}}
@@ -830,11 +971,13 @@ export default class PollComponent extends Component {
@min={{this.min}}
@max={{this.max}}
@isMultiple={{this.isMultiple}}
- @close={{this.close}}
+ @closesAt={{this.closesAt}}
@closed={{this.closed}}
@closedBy={{this.poll.closed_by}}
+ @isAutomaticallyClosed={{this.isAutomaticallyClosed}}
@results={{this.poll.results}}
@showResults={{this.showResults}}
+ @showingVotedChoices={{this.showVotedChoices}}
@postUserId={{this.poll.post.user_id}}
@isPublic={{this.poll.public}}
@isDynamic={{if @isDynamic true this.poll.dynamic}}
@@ -842,15 +985,50 @@ export default class PollComponent extends Component {
@voters={{this.voters}}
/>
<div class="poll-buttons" {{didInsert this.registerPollButtons}}>
+ {{#if this.showKeepVoteButton}}
+ <button
+ class="btn btn-default keep-vote"
+ title={{i18n "poll.keep-vote.title"}}
+ {{on "click" this.keepVote}}
+ >
+ {{dIcon "chevron-left"}}
+ <span class="d-button-label">{{i18n "poll.keep-vote.label"}}</span>
+ </button>
+ {{/if}}
+
{{#if this.showCastVotesButton}}
<button
class={{this.castVotesButtonClass}}
- title={{i18n "poll.cast-votes.title"}}
+ title={{this.castVotesButtonTitle}}
disabled={{this.castVotesDisabled}}
{{on "click" this.castVotes}}
>
{{dIcon this.castVotesButtonIcon}}
- <span class="d-button-label">{{i18n "poll.cast-votes.label"}}</span>
+ <span class="d-button-label">{{this.castVotesButtonLabel}}</span>
+ </button>
+ {{/if}}
+
+ {{#if this.showRemoveVoteButton}}
+ <button
+ class="btn btn-default remove-vote"
+ title={{i18n "poll.remove-vote.title"}}
+ {{on "click" this.removeVote}}
+ >
+ {{dIcon "arrow-rotate-left"}}
+ <span class="d-button-label">{{i18n
+ "poll.remove-vote.label"
+ }}</span>
+ </button>
+ {{/if}}
+
+ {{#if this.showAmendVoteButton}}
+ <button
+ class="btn btn-default amend-vote"
+ title={{i18n "poll.amend-vote.title"}}
+ {{on "click" this.amendVote}}
+ >
+ {{dIcon "pencil"}}
+ <span class="d-button-label">{{i18n "poll.amend-vote.label"}}</span>
</button>
{{/if}}
@@ -880,19 +1058,6 @@ export default class PollComponent extends Component {
</button>
{{/if}}
- {{#if this.showRemoveVoteButton}}
- <button
- class="btn btn-default remove-vote"
- title={{i18n "poll.remove-vote.title"}}
- {{on "click" this.removeVote}}
- >
- {{dIcon "arrow-rotate-left"}}
- <span class="d-button-label">{{i18n
- "poll.remove-vote.label"
- }}</span>
- </button>
- {{/if}}
-
<PollButtonsDropdown
@closed={{this.closed}}
@voters={{this.voters}}
diff --git a/plugins/poll/assets/stylesheets/common/poll.scss b/plugins/poll/assets/stylesheets/common/poll.scss
index e37338b7320..337eb1815e9 100644
--- a/plugins/poll/assets/stylesheets/common/poll.scss
+++ b/plugins/poll/assets/stylesheets/common/poll.scss
@@ -244,6 +244,10 @@ div.poll-outer {
display: flex;
gap: 0.5em;
+ &.vote-recorded .d-icon {
+ color: var(--success);
+ }
+
&:not(:last-child) {
margin-bottom: 0.5em;
}
@@ -310,6 +314,45 @@ div.poll-outer {
.poll-results-number-rating {
font-size: var(--font-up-5);
}
+
+ .poll-voted-choices {
+ &__title {
+ color: var(--primary-medium);
+ }
+
+ &__list {
+ margin-top: 0.5em;
+ }
+
+ &__choice {
+ display: flex;
+ align-items: flex-start;
+ gap: 0.5em;
+ padding: 0.25em 0;
+ cursor: default;
+ word-break: break-word;
+
+ .d-icon,
+ .poll-voted-choices__rank {
+ flex: 0 0 auto;
+ }
+
+ .d-icon {
+ margin-top: 0.3em;
+ color: var(--success);
+ }
+
+ .poll-voted-choices__rank {
+ min-width: 1.5em;
+ margin-top: 0.15em;
+ text-align: center;
+ background: var(--primary-low);
+ border-radius: var(--d-border-radius);
+ font-size: var(--font-down-1);
+ line-height: 1.6em;
+ }
+ }
+ }
}
.poll-title {
@@ -345,7 +388,8 @@ div.poll-outer {
flex: 0 1 auto;
}
- &.toggle-results:first-child {
+ &.toggle-results:first-child,
+ &.keep-vote:first-child {
// don't expand the back button
flex: 0 1 auto;
margin-right: auto;
diff --git a/plugins/poll/config/locales/client.en.yml b/plugins/poll/config/locales/client.en.yml
index 249f594b0ec..9f382f545ce 100644
--- a/plugins/poll/config/locales/client.en.yml
+++ b/plugins/poll/config/locales/client.en.yml
@@ -55,9 +55,24 @@ en:
other: "Choose <strong>%{count} options</strong>."
between_min_and_max_options: "Choose between <strong>%{min} and %{max} options</strong>."
+ vote_recorded: "Your vote has been recorded."
+
+ voted_choices:
+ title: "You voted for:"
+
cast-votes:
title: "Cast your votes"
label: "Vote now!"
+ update_title: "Update your vote"
+ update_label: "Update vote"
+
+ amend-vote:
+ title: "Change your vote"
+ label: "Change vote"
+
+ keep-vote:
+ title: "Go back without changing your vote"
+ label: "Back"
show-results:
title: "Display the poll results"
diff --git a/plugins/poll/test/javascripts/component/poll-info-test.gjs b/plugins/poll/test/javascripts/component/poll-info-test.gjs
index f89c4fa20c5..fa0f2fcb8dd 100644
--- a/plugins/poll/test/javascripts/component/poll-info-test.gjs
+++ b/plugins/poll/test/javascripts/component/poll-info-test.gjs
@@ -19,7 +19,7 @@ module("Component | PollInfo", function (hooks) {
min: 1,
max: 2,
options: OPTIONS,
- close: null,
+ closesAt: null,
closed: false,
results: [],
showResults: false,
@@ -36,7 +36,7 @@ module("Component | PollInfo", function (hooks) {
@min={{this.min}}
@max={{this.max}}
@isMultiple={{this.isMultiple}}
- @close={{this.close}}
+ @closesAt={{this.closesAt}}
@closed={{this.closed}}
@results={{this.results}}
@showResults={{this.showResults}}
@@ -69,7 +69,7 @@ module("Component | PollInfo", function (hooks) {
min: 1,
max: 2,
options: OPTIONS,
- close: null,
+ closesAt: null,
closed: false,
results: "on_vote",
showResults: false,
@@ -86,7 +86,7 @@ module("Component | PollInfo", function (hooks) {
@min={{this.min}}
@max={{this.max}}
@isMultiple={{this.isMultiple}}
- @close={{this.close}}
+ @closesAt={{this.closesAt}}
@closed={{this.closed}}
@results={{this.results}}
@showResults={{this.showResults}}
@@ -123,7 +123,7 @@ module("Component | PollInfo", function (hooks) {
test("displays who closed the poll", async function (assert) {
this.setProperties({
options: OPTIONS,
- close: null,
+ closesAt: null,
closed: true,
closedBy: { username: "jane" },
results: [],
@@ -138,7 +138,7 @@ module("Component | PollInfo", function (hooks) {
<template>
<PollInfo
@options={{this.options}}
- @close={{this.close}}
+ @closesAt={{this.closesAt}}
@closed={{this.closed}}
@closedBy={{this.closedBy}}
@results={{this.results}}
diff --git a/plugins/poll/test/javascripts/component/poll-test.gjs b/plugins/poll/test/javascripts/component/poll-test.gjs
index 7200840c555..5650bc9b577 100644
--- a/plugins/poll/test/javascripts/component/poll-test.gjs
+++ b/plugins/poll/test/javascripts/component/poll-test.gjs
@@ -1,6 +1,6 @@
import EmberObject from "@ember/object";
import { trackedObject } from "@ember/reactive/collections";
-import { click, render, settled } from "@ember/test-helpers";
+import { click, render, settled, waitUntil } from "@ember/test-helpers";
import { module, test } from "qunit";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
import pretender, { response } from "discourse/tests/helpers/create-pretender";
@@ -100,8 +100,35 @@ module("Component | Poll", function (hooks) {
<template><Poll @post={{this.post}} @poll={{this.poll}} /></template>
);
- assert.dom(".poll-buttons .cast-votes:disabled").doesNotExist();
+ assert
+ .dom(".poll-voted-choices__choice")
+ .exists({ count: 3 }, "the saved ranked choices are shown");
+
+ await click(".poll-buttons .amend-vote");
+
assert.dom(".poll-buttons .cast-votes").exists();
+ assert
+ .dom(".poll-buttons .cast-votes")
+ .hasText(
+ i18n("poll.cast-votes.update_label"),
+ "the cast button offers to update the existing vote"
+ );
+ assert
+ .dom(".poll-buttons .cast-votes")
+ .isDisabled("an unchanged selection cannot be re-cast");
+
+ await click(
+ ".ranked-choice-poll-option[data-poll-option-id='1f972d1df351de3ce35a787c89faad29'] button"
+ );
+ await click(".dropdown-menu__item:nth-child(3) button");
+ await click(
+ ".ranked-choice-poll-option[data-poll-option-id='d7ebc3a9beea2e680815a1e4f57d6db6'] button"
+ );
+ await click(".dropdown-menu__item:nth-child(2) button");
+
+ assert
+ .dom(".poll-buttons .cast-votes")
+ .isEnabled("a changed valid selection can be cast");
});
test("invalid ranks with which you cannot vote", async function (assert) {
@@ -276,9 +303,15 @@ module("Component | Poll", function (hooks) {
assert
.dom(".results-staff-only")
.exists("the staff-only results notice is shown instead");
+ assert
+ .dom(".poll-voted-choices__choice")
+ .exists({ count: 2 }, "the voter sees their recorded choices");
+
+ await click(".poll-buttons .amend-vote");
+
assert
.dom(".ranked-choice-poll-option")
- .exists("the ballot options are shown to the voter");
+ .exists("the ballot options are shown when changing the vote");
});
test("can vote", async function (assert) {
@@ -709,4 +742,307 @@ module("Component | Poll", function (hooks) {
await click(".poll-buttons .cast-votes");
assert.dom(".chosen").exists();
});
+
+ const YES = "1f972d1df351de3ce35a787c89faad29";
+ const NO = "d7ebc3a9beea2e680815a1e4f57d6db6";
+ const optionButton = (id) => `li[data-poll-option-id='${id}'] button`;
+ const optionCheckedIcon = (id) =>
+ `li[data-poll-option-id='${id}'] .d-icon-far-square-check`;
+
+ function hiddenResultsPoll(overrides = {}) {
+ return trackedObject({
+ name: "poll",
+ type: "multiple",
+ status: "open",
+ results: "on_close",
+ min: 1,
+ max: 2,
+ options: [
+ { id: YES, html: "yes" },
+ { id: NO, html: "no" },
+ ],
+ voters: 0,
+ chart_type: "bar",
+ ...overrides,
+ });
+ }
+
+ function hiddenResultsPost(votes) {
+ return EmberObject.create({
+ id: 42,
+ topic: { archived: false },
+ user_id: 29,
+ ...(votes ? { polls_votes: { poll: votes } } : {}),
+ });
+ }
+
+ function stubHiddenResultsVote(overrides = {}) {
+ pretender.put("/polls/vote", () =>
+ response({ poll: hiddenResultsPoll({ voters: 1, ...overrides }) })
+ );
+ }
+
+ async function renderHiddenResultsPoll(ctx, { votes, ...overrides } = {}) {
+ ctx.setProperties({
+ post: hiddenResultsPost(votes),
+ poll: hiddenResultsPoll(overrides),
+ });
+
+ await render(
+ <template><Poll @post={{ctx.post}} @poll={{ctx.poll}} /></template>
+ );
+ }
+
+ test("shows the voted choices instead of the ballot after voting on a hidden-results poll", async function (assert) {
+ stubHiddenResultsVote();
+ await renderHiddenResultsPoll(this);
+
+ assert.dom("ul.options").exists();
+ assert
+ .dom(".poll-buttons .cast-votes")
+ .hasText(i18n("poll.cast-votes.label"));
+
+ await click(optionButton(YES));
+ await click(".poll-buttons .cast-votes");
+
+ assert.dom("ul.options").doesNotExist("the ballot is replaced");
+ assert.dom("ul.results").doesNotExist("results stay hidden");
+ assert
+ .dom(".poll-voted-choices__choice")
+ .exists({ count: 1 }, "the recorded choice is shown");
+ assert.dom(".poll-voted-choices__choice").hasText("yes");
+ assert.dom(".poll-buttons .cast-votes").doesNotExist();
+ assert.dom(".poll-buttons .amend-vote").exists();
+ assert
+ .dom(".poll-buttons .remove-vote")
+ .doesNotExist("undo only appears while changing the vote");
+ assert
+ .dom(".poll-info_instructions .vote-recorded")
+ .exists("the info column confirms the recorded vote");
+ assert
+ .dom(".poll-info_instructions .multiple-help-text")
+ .doesNotExist("the confirmation takes the help text's slot");
+ assert
+ .dom(".results-on-close")
+ .exists("the results hint is unchanged by voting");
+ });
+
+ test("can change the vote from the voted choices view", async function (assert) {
+ stubHiddenResultsVote();
+ await renderHiddenResultsPoll(this, { votes: [YES], voters: 1 });
+
+ assert.dom(".poll-voted-choices__choice").exists({ count: 1 });
+
+ await click(".poll-buttons .amend-vote");
+
+ assert.dom("ul.options").exists("the ballot is shown again");
+ assert
+ .dom(optionCheckedIcon(YES))
+ .exists("the saved choice is preselected");
+ assert
+ .dom(".poll-buttons .cast-votes")
+ .hasText(i18n("poll.cast-votes.update_label"));
+ assert
+ .dom(".poll-buttons .cast-votes")
+ .isDisabled("an unchanged selection cannot be re-cast");
+
+ await click(optionButton(NO));
+
+ assert.dom(".poll-buttons .cast-votes").isEnabled();
+
+ await click(".poll-buttons .cast-votes");
+
+ assert
+ .dom(".poll-voted-choices__choice")
+ .exists({ count: 2 }, "the updated choices are shown");
+ });
+
+ test("keeps the current vote when going back from the ballot", async function (assert) {
+ await renderHiddenResultsPoll(this, { votes: [YES], voters: 1 });
+
+ requests = 0;
+
+ await click(".poll-buttons .amend-vote");
+ await click(optionButton(NO));
+ await click(".poll-buttons .keep-vote");
+
+ assert.strictEqual(requests, 0, "no vote is cast");
+ assert
+ .dom(".poll-voted-choices__choice")
+ .exists({ count: 1 }, "the recorded vote is unchanged");
+
+ await click(".poll-buttons .amend-vote");
+
+ assert
+ .dom(optionCheckedIcon(NO))
+ .doesNotExist("the abandoned selection is discarded");
+ });
+
+ test("returns to the ballot after undoing the vote", async function (assert) {
+ pretender.delete("/polls/vote", () =>
+ response({ poll: hiddenResultsPoll() })
+ );
+
+ await renderHiddenResultsPoll(this, { votes: [YES], voters: 1 });
+
+ await click(".poll-buttons .amend-vote");
+
+ assert
+ .dom(".poll-buttons .remove-vote")
+ .exists("undo is available while changing the vote");
+
+ await click(".poll-buttons .remove-vote");
+
+ assert.dom(".poll-voted-choices__choice").doesNotExist();
+ assert.dom("ul.options").exists("the pristine ballot is shown");
+ assert
+ .dom(".poll-buttons .cast-votes")
+ .hasText(i18n("poll.cast-votes.label"));
+ assert.dom(".poll-buttons .keep-vote").doesNotExist();
+ });
+
+ test("keeps the voted choices view after the poll component is re-rendered", async function (assert) {
+ await renderHiddenResultsPoll(this, { votes: [YES], voters: 1 });
+
+ assert.dom(".poll-voted-choices__choice").exists({ count: 1 });
+
+ await render(
+ <template><Poll @post={{this.post}} @poll={{this.poll}} /></template>
+ );
+
+ assert
+ .dom(".poll-voted-choices__choice")
+ .exists({ count: 1 }, "the voted choices survive a re-render");
+
+ await click(".poll-buttons .amend-vote");
+
+ await render(
+ <template><Poll @post={{this.post}} @poll={{this.poll}} /></template>
+ );
+
+ assert
+ .dom("ul.options")
+ .exists("an in-progress vote change survives a re-render");
+ });
+
+ test("shows the voted choices after voting on a staff_only poll as non-staff", async function (assert) {
+ stubHiddenResultsVote({ results: "staff_only" });
+ await renderHiddenResultsPoll(this, { results: "staff_only" });
+
+ await click(optionButton(YES));
+ await click(".poll-buttons .cast-votes");
+
+ assert.dom("ul.results").doesNotExist("results stay hidden");
+ assert.dom(".poll-voted-choices__choice").exists({ count: 1 });
+ assert.dom(".poll-info_instructions .vote-recorded").exists();
+ assert.dom(".results-staff-only").exists();
+ });
+
+ test("casts a single vote when the cast button is clicked twice quickly", async function (assert) {
+ let voteRequests = 0;
+ let resolveVote;
+ pretender.put("/polls/vote", () => {
+ voteRequests++;
+ return new Promise((resolve) => {
+ resolveVote = resolve;
+ });
+ });
+
+ await renderHiddenResultsPoll(this);
+
+ await click(optionButton(YES));
+
+ const castButton = document.querySelector(".poll-buttons .cast-votes");
+ castButton.click();
+ castButton.click();
+
+ await waitUntil(() => resolveVote);
+ resolveVote(response({ poll: hiddenResultsPoll({ voters: 1 }) }));
+ await settled();
+
+ assert.strictEqual(voteRequests, 1, "only one vote request is sent");
+ assert.dom(".poll-voted-choices__choice").exists({ count: 1 });
+ });
+
+ test("moves focus to the change vote button after casting", async function (assert) {
+ stubHiddenResultsVote();
+ await renderHiddenResultsPoll(this);
+
+ await click(optionButton(YES));
+ await click(".poll-buttons .cast-votes");
+
+ assert.dom(".poll-buttons .amend-vote").isFocused();
+ });
+
+ test("keeps the vote when re-clicking the current choice while changing a single-choice vote", async function (assert) {
+ let deleteRequests = 0;
+ pretender.delete("/polls/vote", () => {
+ deleteRequests++;
+ return response({ poll: hiddenResultsPoll({ type: "regular" }) });
+ });
+
+ await renderHiddenResultsPoll(this, {
+ votes: [YES],
+ type: "regular",
+ voters: 1,
+ });
+
+ await click(".poll-buttons .amend-vote");
+ await click(optionButton(YES));
+
+ assert.strictEqual(deleteRequests, 0, "the vote is not deleted");
+ assert
+ .dom(".poll-voted-choices__choice")
+ .exists({ count: 1 }, "the recorded vote is kept");
+ });
+
+ test("shows the results when a hidden-results poll is closed while displayed", async function (assert) {
+ await renderHiddenResultsPoll(this, { votes: [YES], voters: 1 });
+
+ assert.dom(".poll-voted-choices__choice").exists({ count: 1 });
+
+ Object.assign(this.poll, {
+ status: "closed",
+ options: [
+ { id: YES, html: "yes", votes: 1 },
+ { id: NO, html: "no", votes: 0 },
+ ],
+ });
+ await settled();
+
+ assert
+ .dom("ul.results")
+ .exists("the summary flips to results once counts arrive");
+ });
+
+ test("shows the automatic close countdown only while the poll is open", async function (assert) {
+ await renderHiddenResultsPoll(this, { close: "2035-01-01 12:00:00 UTC" });
+
+ assert
+ .dom(".poll-info_instructions li .d-icon-far-clock")
+ .exists("an open poll with a close date shows the countdown");
+
+ this.poll.status = "closed";
+ await settled();
+
+ assert
+ .dom(".poll-info_instructions li .d-icon-far-clock")
+ .doesNotExist("a manually closed poll does not promise a countdown");
+ });
+
+ test("shows the voted choice after voting on a single-choice hidden-results poll", async function (assert) {
+ stubHiddenResultsVote({ type: "regular" });
+ await renderHiddenResultsPoll(this, {
+ type: "regular",
+ min: null,
+ max: null,
+ });
+
+ await click(optionButton(YES));
+
+ assert
+ .dom(".poll-voted-choices__choice")
+ .exists({ count: 1 }, "the recorded choice replaces the ballot");
+ assert.dom(".poll-buttons .amend-vote").exists();
+ });
});