Skip to content
This repository was archived by the owner on Sep 11, 2024. It is now read-only.

Commit a06163e

Browse files
author
Kerry
authored
Poll history - ended polls list items (#10119)
* wip * remove dupe * use poll model relations in all cases * update mpollbody tests to use poll instance * update poll fetching login in pinned messages card * add pinned polls to room polls state * add spinner while relations are still loading * handle no poll in end poll dialog * strict errors * render a poll body that errors for poll end events * add fetching logic to pollend tile * extract poll testing utilities * test mpollend * strict fix * more strict fix * strict fix for forwardref * add filter component * update poll test utils * add unstyled filter tab group * filtertabgroup snapshot * lint * update test util setupRoomWithPollEvents to allow testing multiple polls in one room * style filter tabs * test error message for past polls * sort polls list by latest * extract poll option display components from pollbody * add ended poll list item component * use named export for polllistitem * test POllListItemEnded * comments * strict fixes * extract poll option display components * strict fixes * strict
1 parent 7e5122b commit a06163e

File tree

15 files changed

+472
-18
lines changed

15 files changed

+472
-18
lines changed

res/css/_components.pcss

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
@import "./components/views/beacon/_StyledLiveBeaconIcon.pcss";
1919
@import "./components/views/context_menus/_KebabContextMenu.pcss";
2020
@import "./components/views/dialogs/polls/_PollListItem.pcss";
21+
@import "./components/views/dialogs/polls/_PollListItemEnded.pcss";
2122
@import "./components/views/elements/_FilterDropdown.pcss";
2223
@import "./components/views/elements/_FilterTabGroup.pcss";
2324
@import "./components/views/elements/_LearnMore.pcss";
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
Copyright 2023 The Matrix.org Foundation C.I.C.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
.mx_PollListItemEnded {
18+
width: 100%;
19+
display: flex;
20+
flex-direction: column;
21+
color: $primary-content;
22+
}
23+
24+
.mx_PollListItemEnded_title {
25+
display: grid;
26+
justify-content: left;
27+
align-items: center;
28+
grid-gap: $spacing-8;
29+
grid-template-columns: min-content 1fr min-content;
30+
grid-template-rows: auto;
31+
}
32+
33+
.mx_PollListItemEnded_icon {
34+
height: 14px;
35+
width: 14px;
36+
color: $quaternary-content;
37+
padding-left: $spacing-8;
38+
}
39+
40+
.mx_PollListItemEnded_date {
41+
font-size: $font-12px;
42+
color: $secondary-content;
43+
}
44+
45+
.mx_PollListItemEnded_question {
46+
white-space: nowrap;
47+
overflow: hidden;
48+
text-overflow: ellipsis;
49+
}
50+
51+
.mx_PollListItemEnded_answers {
52+
display: grid;
53+
grid-gap: $spacing-8;
54+
margin-top: $spacing-12;
55+
}
56+
57+
.mx_PollListItemEnded_voteCount {
58+
// 6px to match PollOption padding
59+
margin: $spacing-8 0 0 6px;
60+
}

res/css/components/views/polls/_PollOption.pcss

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ limitations under the License.
1818
border: 1px solid $quinary-content;
1919
border-radius: 8px;
2020
padding: 6px 12px;
21-
max-width: 550px;
2221
background-color: $background;
2322

2423
.mx_StyledRadioButton_content,

res/css/views/dialogs/polls/_PollHistoryList.pcss

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@ limitations under the License.
3232
grid-gap: $spacing-20;
3333
padding-right: $spacing-64;
3434
margin: $spacing-32 0;
35+
36+
&.mx_PollHistoryList_list_ENDED {
37+
grid-gap: $spacing-32;
38+
}
3539
}
3640

3741
.mx_PollHistoryList_noResults {

res/css/views/messages/_MPollBody.pcss

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,4 +70,5 @@ limitations under the License.
7070
display: grid;
7171
grid-gap: $spacing-16;
7272
margin-bottom: $spacing-8;
73+
max-width: 550px;
7374
}

src/components/views/dialogs/polls/PollHistoryDialog.tsx

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,12 @@ export const PollHistoryDialog: React.FC<PollHistoryDialogProps> = ({ roomId, ma
5454
return (
5555
<BaseDialog title={_t("Polls history")} onFinished={onFinished}>
5656
<div className="mx_PollHistoryDialog_content">
57-
<PollHistoryList pollStartEvents={pollStartEvents} filter={filter} onFilterChange={setFilter} />
57+
<PollHistoryList
58+
pollStartEvents={pollStartEvents}
59+
polls={polls}
60+
filter={filter}
61+
onFilterChange={setFilter}
62+
/>
5863
</div>
5964
</BaseDialog>
6065
);

src/components/views/dialogs/polls/PollHistoryList.tsx

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,19 +15,22 @@ limitations under the License.
1515
*/
1616

1717
import React from "react";
18-
import { MatrixEvent } from "matrix-js-sdk/src/matrix";
18+
import classNames from "classnames";
19+
import { MatrixEvent, Poll } from "matrix-js-sdk/src/matrix";
1920

20-
import PollListItem from "./PollListItem";
2121
import { _t } from "../../../../languageHandler";
22-
import { FilterTabGroup } from "../../elements/FilterTabGroup";
2322
import { PollHistoryFilter } from "./types";
23+
import { PollListItem } from "./PollListItem";
24+
import { PollListItemEnded } from "./PollListItemEnded";
25+
import { FilterTabGroup } from "../../elements/FilterTabGroup";
2426

2527
type PollHistoryListProps = {
2628
pollStartEvents: MatrixEvent[];
29+
polls: Map<string, Poll>;
2730
filter: PollHistoryFilter;
2831
onFilterChange: (filter: PollHistoryFilter) => void;
2932
};
30-
export const PollHistoryList: React.FC<PollHistoryListProps> = ({ pollStartEvents, filter, onFilterChange }) => {
33+
export const PollHistoryList: React.FC<PollHistoryListProps> = ({ pollStartEvents, polls, filter, onFilterChange }) => {
3134
return (
3235
<div className="mx_PollHistoryList">
3336
<FilterTabGroup<PollHistoryFilter>
@@ -40,10 +43,18 @@ export const PollHistoryList: React.FC<PollHistoryListProps> = ({ pollStartEvent
4043
]}
4144
/>
4245
{!!pollStartEvents.length ? (
43-
<ol className="mx_PollHistoryList_list">
44-
{pollStartEvents.map((pollStartEvent) => (
45-
<PollListItem key={pollStartEvent.getId()!} event={pollStartEvent} />
46-
))}
46+
<ol className={classNames("mx_PollHistoryList_list", `mx_PollHistoryList_list_${filter}`)}>
47+
{pollStartEvents.map((pollStartEvent) =>
48+
filter === "ACTIVE" ? (
49+
<PollListItem key={pollStartEvent.getId()!} event={pollStartEvent} />
50+
) : (
51+
<PollListItemEnded
52+
key={pollStartEvent.getId()!}
53+
event={pollStartEvent}
54+
poll={polls.get(pollStartEvent.getId()!)!}
55+
/>
56+
),
57+
)}
4758
</ol>
4859
) : (
4960
<span className="mx_PollHistoryList_noResults">

src/components/views/dialogs/polls/PollListItem.tsx

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ interface Props {
2525
event: MatrixEvent;
2626
}
2727

28-
const PollListItem: React.FC<Props> = ({ event }) => {
28+
export const PollListItem: React.FC<Props> = ({ event }) => {
2929
const pollEvent = event.unstableExtensibleEvent as unknown as PollStartEvent;
3030
if (!pollEvent) {
3131
return null;
@@ -39,5 +39,3 @@ const PollListItem: React.FC<Props> = ({ event }) => {
3939
</li>
4040
);
4141
};
42-
43-
export default PollListItem;
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
/*
2+
Copyright 2023 The Matrix.org Foundation C.I.C.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
import React, { useEffect, useState } from "react";
18+
import { PollAnswerSubevent } from "matrix-js-sdk/src/extensible_events_v1/PollStartEvent";
19+
import { MatrixEvent, Poll, PollEvent } from "matrix-js-sdk/src/matrix";
20+
import { Relations } from "matrix-js-sdk/src/models/relations";
21+
22+
import { Icon as PollIcon } from "../../../../../res/img/element-icons/room/composer/poll.svg";
23+
import { _t } from "../../../../languageHandler";
24+
import { formatLocalDateShort } from "../../../../DateUtils";
25+
import { allVotes, collectUserVotes, countVotes } from "../../messages/MPollBody";
26+
import { PollOption } from "../../polls/PollOption";
27+
import { Caption } from "../../typography/Caption";
28+
29+
interface Props {
30+
event: MatrixEvent;
31+
poll: Poll;
32+
}
33+
34+
type EndedPollState = {
35+
winningAnswers: {
36+
answer: PollAnswerSubevent;
37+
voteCount: number;
38+
}[];
39+
totalVoteCount: number;
40+
};
41+
const getWinningAnswers = (poll: Poll, responseRelations: Relations): EndedPollState => {
42+
const userVotes = collectUserVotes(allVotes(responseRelations));
43+
const votes = countVotes(userVotes, poll.pollEvent);
44+
const totalVoteCount = [...votes.values()].reduce((sum, vote) => sum + vote, 0);
45+
const winCount = Math.max(...votes.values());
46+
47+
return {
48+
totalVoteCount,
49+
winningAnswers: poll.pollEvent.answers
50+
.filter((answer) => votes.get(answer.id) === winCount)
51+
.map((answer) => ({
52+
answer,
53+
voteCount: votes.get(answer.id) || 0,
54+
})),
55+
};
56+
};
57+
58+
/**
59+
* Get deduplicated and validated poll responses
60+
* Will use cached responses from Poll instance when existing
61+
* Updates on changes to Poll responses (paging relations or from sync)
62+
* Returns winning answers and total vote count
63+
*/
64+
const usePollVotes = (poll: Poll): Partial<EndedPollState> => {
65+
const [results, setResults] = useState({ totalVoteCount: 0 });
66+
67+
useEffect(() => {
68+
const getResponses = async (): Promise<void> => {
69+
const responseRelations = await poll.getResponses();
70+
setResults(getWinningAnswers(poll, responseRelations));
71+
};
72+
const onPollResponses = (responseRelations: Relations): void =>
73+
setResults(getWinningAnswers(poll, responseRelations));
74+
poll.on(PollEvent.Responses, onPollResponses);
75+
76+
getResponses();
77+
78+
return () => {
79+
poll.off(PollEvent.Responses, onPollResponses);
80+
};
81+
}, [poll]);
82+
83+
return results;
84+
};
85+
86+
/**
87+
* Render an ended poll with the winning answer and vote count
88+
* @param event - the poll start MatrixEvent
89+
* @param poll - Poll instance
90+
*/
91+
export const PollListItemEnded: React.FC<Props> = ({ event, poll }) => {
92+
const pollEvent = poll.pollEvent;
93+
const { winningAnswers, totalVoteCount } = usePollVotes(poll);
94+
if (!pollEvent) {
95+
return null;
96+
}
97+
const formattedDate = formatLocalDateShort(event.getTs());
98+
99+
return (
100+
<li data-testid={`pollListItem-${event.getId()!}`} className="mx_PollListItemEnded">
101+
<div className="mx_PollListItemEnded_title">
102+
<PollIcon className="mx_PollListItemEnded_icon" />
103+
<span className="mx_PollListItemEnded_question">{pollEvent.question.text}</span>
104+
<Caption>{formattedDate}</Caption>
105+
</div>
106+
{!!winningAnswers?.length && (
107+
<div className="mx_PollListItemEnded_answers">
108+
{winningAnswers?.map(({ answer, voteCount }) => (
109+
<PollOption
110+
key={answer.id}
111+
answer={answer}
112+
voteCount={voteCount}
113+
totalVoteCount={totalVoteCount!}
114+
pollId={poll.pollId}
115+
displayVoteCount
116+
isChecked
117+
isEnded
118+
/>
119+
))}
120+
</div>
121+
)}
122+
<div className="mx_PollListItemEnded_voteCount">
123+
<Caption>{_t("Final result based on %(count)s votes", { count: totalVoteCount })}</Caption>
124+
</div>
125+
</li>
126+
);
127+
};

src/components/views/messages/MPollBody.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -384,7 +384,7 @@ export function allVotes(voteRelations: Relations): Array<UserVote> {
384384
* @param {string?} selected Local echo selected option for the userId
385385
* @returns a Map of user ID to their vote info
386386
*/
387-
function collectUserVotes(
387+
export function collectUserVotes(
388388
userResponses: Array<UserVote>,
389389
userId?: string | null | undefined,
390390
selected?: string | null | undefined,
@@ -405,7 +405,7 @@ function collectUserVotes(
405405
return userVotes;
406406
}
407407

408-
function countVotes(userVotes: Map<string, UserVote>, pollStart: PollStartEvent): Map<string, number> {
408+
export function countVotes(userVotes: Map<string, UserVote>, pollStart: PollStartEvent): Map<string, number> {
409409
const collected = new Map<string, number>();
410410

411411
for (const response of userVotes.values()) {

0 commit comments

Comments
 (0)