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
This commit is contained in:
Kerry 2023-02-21 07:19:50 +13:00 committed by GitHub
parent 7e5122b379
commit a06163ee98
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 472 additions and 18 deletions

View file

@ -18,6 +18,7 @@
@import "./components/views/beacon/_StyledLiveBeaconIcon.pcss";
@import "./components/views/context_menus/_KebabContextMenu.pcss";
@import "./components/views/dialogs/polls/_PollListItem.pcss";
@import "./components/views/dialogs/polls/_PollListItemEnded.pcss";
@import "./components/views/elements/_FilterDropdown.pcss";
@import "./components/views/elements/_FilterTabGroup.pcss";
@import "./components/views/elements/_LearnMore.pcss";

View file

@ -0,0 +1,60 @@
/*
Copyright 2023 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
.mx_PollListItemEnded {
width: 100%;
display: flex;
flex-direction: column;
color: $primary-content;
}
.mx_PollListItemEnded_title {
display: grid;
justify-content: left;
align-items: center;
grid-gap: $spacing-8;
grid-template-columns: min-content 1fr min-content;
grid-template-rows: auto;
}
.mx_PollListItemEnded_icon {
height: 14px;
width: 14px;
color: $quaternary-content;
padding-left: $spacing-8;
}
.mx_PollListItemEnded_date {
font-size: $font-12px;
color: $secondary-content;
}
.mx_PollListItemEnded_question {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.mx_PollListItemEnded_answers {
display: grid;
grid-gap: $spacing-8;
margin-top: $spacing-12;
}
.mx_PollListItemEnded_voteCount {
// 6px to match PollOption padding
margin: $spacing-8 0 0 6px;
}

View file

@ -18,7 +18,6 @@ limitations under the License.
border: 1px solid $quinary-content;
border-radius: 8px;
padding: 6px 12px;
max-width: 550px;
background-color: $background;
.mx_StyledRadioButton_content,

View file

@ -32,6 +32,10 @@ limitations under the License.
grid-gap: $spacing-20;
padding-right: $spacing-64;
margin: $spacing-32 0;
&.mx_PollHistoryList_list_ENDED {
grid-gap: $spacing-32;
}
}
.mx_PollHistoryList_noResults {

View file

@ -70,4 +70,5 @@ limitations under the License.
display: grid;
grid-gap: $spacing-16;
margin-bottom: $spacing-8;
max-width: 550px;
}

View file

@ -54,7 +54,12 @@ export const PollHistoryDialog: React.FC<PollHistoryDialogProps> = ({ roomId, ma
return (
<BaseDialog title={_t("Polls history")} onFinished={onFinished}>
<div className="mx_PollHistoryDialog_content">
<PollHistoryList pollStartEvents={pollStartEvents} filter={filter} onFilterChange={setFilter} />
<PollHistoryList
pollStartEvents={pollStartEvents}
polls={polls}
filter={filter}
onFilterChange={setFilter}
/>
</div>
</BaseDialog>
);

View file

@ -15,19 +15,22 @@ limitations under the License.
*/
import React from "react";
import { MatrixEvent } from "matrix-js-sdk/src/matrix";
import classNames from "classnames";
import { MatrixEvent, Poll } from "matrix-js-sdk/src/matrix";
import PollListItem from "./PollListItem";
import { _t } from "../../../../languageHandler";
import { FilterTabGroup } from "../../elements/FilterTabGroup";
import { PollHistoryFilter } from "./types";
import { PollListItem } from "./PollListItem";
import { PollListItemEnded } from "./PollListItemEnded";
import { FilterTabGroup } from "../../elements/FilterTabGroup";
type PollHistoryListProps = {
pollStartEvents: MatrixEvent[];
polls: Map<string, Poll>;
filter: PollHistoryFilter;
onFilterChange: (filter: PollHistoryFilter) => void;
};
export const PollHistoryList: React.FC<PollHistoryListProps> = ({ pollStartEvents, filter, onFilterChange }) => {
export const PollHistoryList: React.FC<PollHistoryListProps> = ({ pollStartEvents, polls, filter, onFilterChange }) => {
return (
<div className="mx_PollHistoryList">
<FilterTabGroup<PollHistoryFilter>
@ -40,10 +43,18 @@ export const PollHistoryList: React.FC<PollHistoryListProps> = ({ pollStartEvent
]}
/>
{!!pollStartEvents.length ? (
<ol className="mx_PollHistoryList_list">
{pollStartEvents.map((pollStartEvent) => (
<PollListItem key={pollStartEvent.getId()!} event={pollStartEvent} />
))}
<ol className={classNames("mx_PollHistoryList_list", `mx_PollHistoryList_list_${filter}`)}>
{pollStartEvents.map((pollStartEvent) =>
filter === "ACTIVE" ? (
<PollListItem key={pollStartEvent.getId()!} event={pollStartEvent} />
) : (
<PollListItemEnded
key={pollStartEvent.getId()!}
event={pollStartEvent}
poll={polls.get(pollStartEvent.getId()!)!}
/>
),
)}
</ol>
) : (
<span className="mx_PollHistoryList_noResults">

View file

@ -25,7 +25,7 @@ interface Props {
event: MatrixEvent;
}
const PollListItem: React.FC<Props> = ({ event }) => {
export const PollListItem: React.FC<Props> = ({ event }) => {
const pollEvent = event.unstableExtensibleEvent as unknown as PollStartEvent;
if (!pollEvent) {
return null;
@ -39,5 +39,3 @@ const PollListItem: React.FC<Props> = ({ event }) => {
</li>
);
};
export default PollListItem;

View file

@ -0,0 +1,127 @@
/*
Copyright 2023 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import React, { useEffect, useState } from "react";
import { PollAnswerSubevent } from "matrix-js-sdk/src/extensible_events_v1/PollStartEvent";
import { MatrixEvent, Poll, PollEvent } from "matrix-js-sdk/src/matrix";
import { Relations } from "matrix-js-sdk/src/models/relations";
import { Icon as PollIcon } from "../../../../../res/img/element-icons/room/composer/poll.svg";
import { _t } from "../../../../languageHandler";
import { formatLocalDateShort } from "../../../../DateUtils";
import { allVotes, collectUserVotes, countVotes } from "../../messages/MPollBody";
import { PollOption } from "../../polls/PollOption";
import { Caption } from "../../typography/Caption";
interface Props {
event: MatrixEvent;
poll: Poll;
}
type EndedPollState = {
winningAnswers: {
answer: PollAnswerSubevent;
voteCount: number;
}[];
totalVoteCount: number;
};
const getWinningAnswers = (poll: Poll, responseRelations: Relations): EndedPollState => {
const userVotes = collectUserVotes(allVotes(responseRelations));
const votes = countVotes(userVotes, poll.pollEvent);
const totalVoteCount = [...votes.values()].reduce((sum, vote) => sum + vote, 0);
const winCount = Math.max(...votes.values());
return {
totalVoteCount,
winningAnswers: poll.pollEvent.answers
.filter((answer) => votes.get(answer.id) === winCount)
.map((answer) => ({
answer,
voteCount: votes.get(answer.id) || 0,
})),
};
};
/**
* Get deduplicated and validated poll responses
* Will use cached responses from Poll instance when existing
* Updates on changes to Poll responses (paging relations or from sync)
* Returns winning answers and total vote count
*/
const usePollVotes = (poll: Poll): Partial<EndedPollState> => {
const [results, setResults] = useState({ totalVoteCount: 0 });
useEffect(() => {
const getResponses = async (): Promise<void> => {
const responseRelations = await poll.getResponses();
setResults(getWinningAnswers(poll, responseRelations));
};
const onPollResponses = (responseRelations: Relations): void =>
setResults(getWinningAnswers(poll, responseRelations));
poll.on(PollEvent.Responses, onPollResponses);
getResponses();
return () => {
poll.off(PollEvent.Responses, onPollResponses);
};
}, [poll]);
return results;
};
/**
* Render an ended poll with the winning answer and vote count
* @param event - the poll start MatrixEvent
* @param poll - Poll instance
*/
export const PollListItemEnded: React.FC<Props> = ({ event, poll }) => {
const pollEvent = poll.pollEvent;
const { winningAnswers, totalVoteCount } = usePollVotes(poll);
if (!pollEvent) {
return null;
}
const formattedDate = formatLocalDateShort(event.getTs());
return (
<li data-testid={`pollListItem-${event.getId()!}`} className="mx_PollListItemEnded">
<div className="mx_PollListItemEnded_title">
<PollIcon className="mx_PollListItemEnded_icon" />
<span className="mx_PollListItemEnded_question">{pollEvent.question.text}</span>
<Caption>{formattedDate}</Caption>
</div>
{!!winningAnswers?.length && (
<div className="mx_PollListItemEnded_answers">
{winningAnswers?.map(({ answer, voteCount }) => (
<PollOption
key={answer.id}
answer={answer}
voteCount={voteCount}
totalVoteCount={totalVoteCount!}
pollId={poll.pollId}
displayVoteCount
isChecked
isEnded
/>
))}
</div>
)}
<div className="mx_PollListItemEnded_voteCount">
<Caption>{_t("Final result based on %(count)s votes", { count: totalVoteCount })}</Caption>
</div>
</li>
);
};

View file

@ -384,7 +384,7 @@ export function allVotes(voteRelations: Relations): Array<UserVote> {
* @param {string?} selected Local echo selected option for the userId
* @returns a Map of user ID to their vote info
*/
function collectUserVotes(
export function collectUserVotes(
userResponses: Array<UserVote>,
userId?: string | null | undefined,
selected?: string | null | undefined,
@ -405,7 +405,7 @@ function collectUserVotes(
return userVotes;
}
function countVotes(userVotes: Map<string, UserVote>, pollStart: PollStartEvent): Map<string, number> {
export function countVotes(userVotes: Map<string, UserVote>, pollStart: PollStartEvent): Map<string, number> {
const collected = new Map<string, number>();
for (const response of userVotes.values()) {

View file

@ -18,7 +18,7 @@ import React from "react";
import { render } from "@testing-library/react";
import { MatrixEvent } from "matrix-js-sdk/src/matrix";
import PollListItem from "../../../../../src/components/views/dialogs/polls/PollListItem";
import { PollListItem } from "../../../../../src/components/views/dialogs/polls/PollListItem";
import { makePollStartEvent, mockIntlDateTimeFormat, unmockIntlDateTimeFormat } from "../../../../test-utils";
describe("<PollListItem />", () => {

View file

@ -0,0 +1,181 @@
/*
Copyright 2023 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import React from "react";
import { render } from "@testing-library/react";
import { MatrixEvent, Poll, Room } from "matrix-js-sdk/src/matrix";
import { M_TEXT } from "matrix-js-sdk/src/@types/extensible_events";
import { PollListItemEnded } from "../../../../../src/components/views/dialogs/polls/PollListItemEnded";
import {
flushPromises,
getMockClientWithEventEmitter,
makePollEndEvent,
makePollResponseEvent,
makePollStartEvent,
mockClientMethodsUser,
mockIntlDateTimeFormat,
setupRoomWithPollEvents,
unmockIntlDateTimeFormat,
} from "../../../../test-utils";
describe("<PollListItemEnded />", () => {
const userId = "@alice:domain.org";
const roomId = "!room:domain.org";
const mockClient = getMockClientWithEventEmitter({
...mockClientMethodsUser(userId),
getRoom: jest.fn(),
relations: jest.fn(),
decryptEventIfNeeded: jest.fn(),
});
const room = new Room(roomId, mockClient, userId);
const timestamp = 1675300825090;
const pollId = "1";
const answerOne = {
id: "answerOneId",
[M_TEXT.name]: "Nissan Silvia S15",
};
const answerTwo = {
id: "answerTwoId",
[M_TEXT.name]: "Mitsubishi Lancer Evolution IX",
};
const pollStartEvent = makePollStartEvent("Question?", userId, [answerOne, answerTwo], {
roomId,
id: pollId,
ts: timestamp,
});
const pollEndEvent = makePollEndEvent(pollId, roomId, userId, timestamp + 60000);
const getComponent = (props: { event: MatrixEvent; poll: Poll }) => render(<PollListItemEnded {...props} />);
beforeAll(() => {
// mock default locale to en-GB and set timezone
// so these tests run the same everywhere
mockIntlDateTimeFormat();
});
afterAll(() => {
unmockIntlDateTimeFormat();
});
it("renders a poll with no responses", async () => {
await setupRoomWithPollEvents([pollStartEvent], [], [pollEndEvent], mockClient, room);
const poll = room.polls.get(pollId)!;
const { container } = getComponent({ event: pollStartEvent, poll });
expect(container).toMatchSnapshot();
});
it("renders a poll with one winning answer", async () => {
const responses = [
makePollResponseEvent(pollId, [answerOne.id], userId, roomId, timestamp + 1),
makePollResponseEvent(pollId, [answerOne.id], "@bob:domain.org", roomId, timestamp + 1),
makePollResponseEvent(pollId, [answerTwo.id], "@charlie:domain.org", roomId, timestamp + 1),
];
await setupRoomWithPollEvents([pollStartEvent], responses, [pollEndEvent], mockClient, room);
const poll = room.polls.get(pollId)!;
const { getByText } = getComponent({ event: pollStartEvent, poll });
// fetch relations
await flushPromises();
expect(getByText("Final result based on 3 votes")).toBeInTheDocument();
// winning answer
expect(getByText("Nissan Silvia S15")).toBeInTheDocument();
});
it("renders a poll with two winning answers", async () => {
const responses = [
makePollResponseEvent(pollId, [answerOne.id], userId, roomId, timestamp + 1),
makePollResponseEvent(pollId, [answerOne.id], "@han:domain.org", roomId, timestamp + 1),
makePollResponseEvent(pollId, [answerTwo.id], "@sean:domain.org", roomId, timestamp + 1),
makePollResponseEvent(pollId, [answerTwo.id], "@dk:domain.org", roomId, timestamp + 1),
];
await setupRoomWithPollEvents([pollStartEvent], responses, [pollEndEvent], mockClient, room);
const poll = room.polls.get(pollId)!;
const { getByText } = getComponent({ event: pollStartEvent, poll });
// fetch relations
await flushPromises();
expect(getByText("Final result based on 4 votes")).toBeInTheDocument();
// both answers answer
expect(getByText("Nissan Silvia S15")).toBeInTheDocument();
expect(getByText("Mitsubishi Lancer Evolution IX")).toBeInTheDocument();
});
it("counts one unique vote per user", async () => {
const responses = [
makePollResponseEvent(pollId, [answerTwo.id], userId, roomId, timestamp + 1),
makePollResponseEvent(pollId, [answerTwo.id], userId, roomId, timestamp + 1),
makePollResponseEvent(pollId, [answerTwo.id], userId, roomId, timestamp + 1),
makePollResponseEvent(pollId, [answerOne.id], userId, roomId, timestamp + 2),
makePollResponseEvent(pollId, [answerOne.id], "@bob:domain.org", roomId, timestamp + 1),
makePollResponseEvent(pollId, [answerTwo.id], "@charlie:domain.org", roomId, timestamp + 1),
];
await setupRoomWithPollEvents([pollStartEvent], responses, [pollEndEvent], mockClient, room);
const poll = room.polls.get(pollId)!;
const { getByText } = getComponent({ event: pollStartEvent, poll });
// fetch relations
await flushPromises();
// still only 3 unique votes
expect(getByText("Final result based on 3 votes")).toBeInTheDocument();
// only latest vote counted
expect(getByText("Nissan Silvia S15")).toBeInTheDocument();
});
it("excludes malformed responses", async () => {
const responses = [
makePollResponseEvent(pollId, ["bad-answer-id"], userId, roomId, timestamp + 1),
makePollResponseEvent(pollId, [answerOne.id], "@bob:domain.org", roomId, timestamp + 1),
makePollResponseEvent(pollId, [answerTwo.id], "@charlie:domain.org", roomId, timestamp + 1),
];
await setupRoomWithPollEvents([pollStartEvent], responses, [pollEndEvent], mockClient, room);
const poll = room.polls.get(pollId)!;
const { getByText } = getComponent({ event: pollStartEvent, poll });
// fetch relations
await flushPromises();
// invalid vote excluded
expect(getByText("Final result based on 2 votes")).toBeInTheDocument();
});
it("updates on new responses", async () => {
const responses = [
makePollResponseEvent(pollId, [answerOne.id], "@bob:domain.org", roomId, timestamp + 1),
makePollResponseEvent(pollId, [answerTwo.id], "@charlie:domain.org", roomId, timestamp + 1),
];
await setupRoomWithPollEvents([pollStartEvent], responses, [pollEndEvent], mockClient, room);
const poll = room.polls.get(pollId)!;
const { getByText, queryByText } = getComponent({ event: pollStartEvent, poll });
// fetch relations
await flushPromises();
expect(getByText("Final result based on 2 votes")).toBeInTheDocument();
await room.processPollEvents([
makePollResponseEvent(pollId, [answerOne.id], "@han:domain.org", roomId, timestamp + 1),
]);
// updated with more responses
expect(getByText("Final result based on 3 votes")).toBeInTheDocument();
expect(getByText("Nissan Silvia S15")).toBeInTheDocument();
expect(queryByText("Mitsubishi Lancer Evolution IX")).not.toBeInTheDocument();
});
});

View file

@ -65,7 +65,7 @@ exports[`<PollHistoryDialog /> renders a list of active polls when there are pol
</label>
</fieldset>
<ol
class="mx_PollHistoryList_list"
class="mx_PollHistoryList_list mx_PollHistoryList_list_ACTIVE"
>
<li
class="mx_PollListItem"

View file

@ -0,0 +1,37 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<PollListItemEnded /> renders a poll with no responses 1`] = `
<div>
<li
class="mx_PollListItemEnded"
data-testid="pollListItem-1"
>
<div
class="mx_PollListItemEnded_title"
>
<div
class="mx_PollListItemEnded_icon"
/>
<span
class="mx_PollListItemEnded_question"
>
Question?
</span>
<span
class="mx_Caption"
>
02/02/23
</span>
</div>
<div
class="mx_PollListItemEnded_voteCount"
>
<span
class="mx_Caption"
>
Final result based on 0 votes
</span>
</div>
</li>
</div>
`;

View file

@ -17,7 +17,13 @@ limitations under the License.
import { Mocked } from "jest-mock";
import { MatrixClient } from "matrix-js-sdk/src/client";
import { MatrixEvent, Room } from "matrix-js-sdk/src/matrix";
import { M_POLL_START, PollAnswer, M_POLL_KIND_DISCLOSED, M_POLL_END } from "matrix-js-sdk/src/@types/polls";
import {
M_POLL_START,
PollAnswer,
M_POLL_KIND_DISCLOSED,
M_POLL_END,
M_POLL_RESPONSE,
} from "matrix-js-sdk/src/@types/polls";
import { M_TEXT } from "matrix-js-sdk/src/@types/extensible_events";
import { uuid4 } from "@sentry/utils";
@ -78,6 +84,30 @@ export const makePollEndEvent = (pollStartEventId: string, roomId: string, sende
});
};
export const makePollResponseEvent = (
pollId: string,
answerIds: string[],
sender: string,
roomId: string,
ts = 0,
): MatrixEvent =>
new MatrixEvent({
event_id: uuid4(),
room_id: roomId,
origin_server_ts: ts,
type: M_POLL_RESPONSE.name,
sender,
content: {
"m.relates_to": {
rel_type: "m.reference",
event_id: pollId,
},
[M_POLL_RESPONSE.name]: {
answers: answerIds,
},
},
});
/**
* Creates a room with attached poll events
* Returns room from mockClient