Poll history - make poll history independent from dialogs (#10349)

* move pollhistory from dialogs to polls directory

* rename PollHistoryDialog -> PollHistory

* rename references to PollHistoryDialog

* move title to PollHistory

* add option to collapse empty dialog header
This commit is contained in:
Kerry 2023-03-13 09:22:30 +13:00 committed by GitHub
parent 127a3b667c
commit 1e46efe89c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
25 changed files with 290 additions and 251 deletions

View file

@ -0,0 +1,89 @@
/*
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 { Poll } from "matrix-js-sdk/src/matrix";
import { _t } from "../../../../languageHandler";
import dispatcher from "../../../../dispatcher/dispatcher";
import { Action } from "../../../../dispatcher/actions";
import { ViewRoomPayload } from "../../../../dispatcher/payloads/ViewRoomPayload";
import { RoomPermalinkCreator } from "../../../../utils/permalinks/Permalinks";
import { MediaEventHelper } from "../../../../utils/MediaEventHelper";
import AccessibleButton, { ButtonEvent } from "../../elements/AccessibleButton";
import MPollBody from "../../messages/MPollBody";
interface Props {
poll: Poll;
requestModalClose: () => void;
permalinkCreator: RoomPermalinkCreator;
}
const NOOP = (): void => {};
/**
* Content of PollHistory when a specific poll is selected
*/
export const PollDetail: React.FC<Props> = ({ poll, permalinkCreator, requestModalClose }) => {
// link to end event for ended polls
const eventIdToLinkTo = poll.isEnded ? poll.endEventId! : poll.pollId;
const linkToTimeline = permalinkCreator.forEvent(eventIdToLinkTo);
const onLinkClick = (e: ButtonEvent): void => {
if ((e as React.MouseEvent).ctrlKey || (e as React.MouseEvent).metaKey) {
// native behavior for link on ctrl/cmd + click
return;
}
// otherwise handle navigation in the app
e.preventDefault();
dispatcher.dispatch<ViewRoomPayload>({
action: Action.ViewRoom,
event_id: eventIdToLinkTo,
highlighted: true,
room_id: poll.roomId,
metricsTrigger: undefined, // room doesn't change
});
requestModalClose();
};
return (
<>
<MPollBody
mxEvent={poll.rootEvent}
permalinkCreator={permalinkCreator}
onHeightChanged={NOOP}
onMessageAllowed={NOOP}
// MPollBody doesn't use this
// and MessageEvent only defines it for eligible events
// should be fixed on IBodyProps types
// cheat to fulfil the type here
mediaEventHelper={{} as unknown as MediaEventHelper}
/>
<br />
<div>
<AccessibleButton
kind="link_inline"
element="a"
href={linkToTimeline}
onClick={onLinkClick}
rel="noreferrer noopener"
>
{_t("View poll in timeline")}
</AccessibleButton>
</div>
</>
);
};

View file

@ -0,0 +1,36 @@
/*
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 { Icon as LeftCaretIcon } from "../../../../../res/img/element-icons/caret-left.svg";
import { _t } from "../../../../languageHandler";
import AccessibleButton from "../../elements/AccessibleButton";
import { PollHistoryFilter } from "./types";
interface Props {
filter: PollHistoryFilter;
onNavigateBack: () => void;
}
export const PollDetailHeader: React.FC<Props> = ({ filter, onNavigateBack }) => {
return (
<AccessibleButton kind="content_inline" onClick={onNavigateBack} className="mx_PollDetailHeader">
<LeftCaretIcon className="mx_PollDetailHeader_icon" />
{filter === "ACTIVE" ? _t("Active polls") : _t("Past polls")}
</AccessibleButton>
);
};

View file

@ -0,0 +1,91 @@
/*
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, { useState } from "react";
import { MatrixClient } from "matrix-js-sdk/src/client";
import { MatrixEvent, Poll, Room } from "matrix-js-sdk/src/matrix";
import { _t } from "../../../../languageHandler";
import { PollHistoryList } from "./PollHistoryList";
import { PollHistoryFilter } from "./types";
import { PollDetailHeader } from "./PollDetailHeader";
import { PollDetail } from "./PollDetail";
import { RoomPermalinkCreator } from "../../../../utils/permalinks/Permalinks";
import { usePollsWithRelations } from "./usePollHistory";
import { useFetchPastPolls } from "./fetchPastPolls";
import Heading from "../../typography/Heading";
type PollHistoryProps = {
room: Room;
matrixClient: MatrixClient;
permalinkCreator: RoomPermalinkCreator;
onFinished(): void;
};
const sortEventsByLatest = (left: MatrixEvent, right: MatrixEvent): number => right.getTs() - left.getTs();
const filterPolls =
(filter: PollHistoryFilter) =>
(poll: Poll): boolean =>
// exclude polls while they are still loading
// to avoid jitter in list
!poll.isFetchingResponses && (filter === "ACTIVE") !== poll.isEnded;
const filterAndSortPolls = (polls: Map<string, Poll>, filter: PollHistoryFilter): MatrixEvent[] => {
return [...polls.values()]
.filter(filterPolls(filter))
.map((poll) => poll.rootEvent)
.sort(sortEventsByLatest);
};
export const PollHistory: React.FC<PollHistoryProps> = ({ room, matrixClient, permalinkCreator, onFinished }) => {
const { polls } = usePollsWithRelations(room.roomId, matrixClient);
const { isLoading, loadMorePolls, oldestEventTimestamp } = useFetchPastPolls(room, matrixClient);
const [filter, setFilter] = useState<PollHistoryFilter>("ACTIVE");
const [focusedPollId, setFocusedPollId] = useState<string | null>(null);
const pollStartEvents = filterAndSortPolls(polls, filter);
const isLoadingPollResponses = [...polls.values()].some((poll) => poll.isFetchingResponses);
const focusedPoll = focusedPollId ? polls.get(focusedPollId) : undefined;
const title = focusedPoll ? (
<PollDetailHeader filter={filter} onNavigateBack={() => setFocusedPollId(null)} />
) : (
_t("Polls history")
);
return (
<div className="mx_PollHistory_content">
{/* @TODO this probably needs some style */}
<Heading className="mx_PollHistory_header" size="h2">
{title}
</Heading>
{focusedPoll ? (
<PollDetail poll={focusedPoll} permalinkCreator={permalinkCreator} requestModalClose={onFinished} />
) : (
<PollHistoryList
onItemClick={setFocusedPollId}
pollStartEvents={pollStartEvents}
isLoading={isLoading || isLoadingPollResponses}
oldestFetchedEventTimestamp={oldestEventTimestamp}
polls={polls}
filter={filter}
onFilterChange={setFilter}
loadMorePolls={loadMorePolls}
/>
)}
</div>
);
};

View file

@ -0,0 +1,172 @@
/*
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 classNames from "classnames";
import { MatrixEvent, Poll } from "matrix-js-sdk/src/matrix";
import { _t } from "../../../../languageHandler";
import { FilterTabGroup } from "../../elements/FilterTabGroup";
import InlineSpinner from "../../elements/InlineSpinner";
import { PollHistoryFilter } from "./types";
import { PollListItem } from "./PollListItem";
import { PollListItemEnded } from "./PollListItemEnded";
import AccessibleButton from "../../elements/AccessibleButton";
const LoadingPolls: React.FC<{ noResultsYet?: boolean }> = ({ noResultsYet }) => (
<div
className={classNames("mx_PollHistoryList_loading", {
mx_PollHistoryList_noResultsYet: noResultsYet,
})}
>
<InlineSpinner />
{_t("Loading polls")}
</div>
);
const LoadMorePolls: React.FC<{ loadMorePolls?: () => void; isLoading?: boolean }> = ({ isLoading, loadMorePolls }) =>
loadMorePolls ? (
<AccessibleButton
className="mx_PollHistoryList_loadMorePolls"
kind="link_inline"
onClick={() => loadMorePolls()}
>
{_t("Load more polls")}
{isLoading && <InlineSpinner />}
</AccessibleButton>
) : null;
const ONE_DAY_MS = 60000 * 60 * 24;
const getNoResultsMessage = (
filter: PollHistoryFilter,
oldestEventTimestamp?: number,
loadMorePolls?: () => void,
): string => {
if (!loadMorePolls) {
return filter === "ACTIVE"
? _t("There are no active polls in this room")
: _t("There are no past polls in this room");
}
// we don't know how much history has been fetched
if (!oldestEventTimestamp) {
return filter === "ACTIVE"
? _t("There are no active polls. Load more polls to view polls for previous months")
: _t("There are no past polls. Load more polls to view polls for previous months");
}
const fetchedHistoryDaysCount = Math.ceil((Date.now() - oldestEventTimestamp) / ONE_DAY_MS);
return filter === "ACTIVE"
? _t(
"There are no active polls for the past %(count)s days. Load more polls to view polls for previous months",
{ count: fetchedHistoryDaysCount },
)
: _t("There are no past polls for the past %(count)s days. Load more polls to view polls for previous months", {
count: fetchedHistoryDaysCount,
});
};
const NoResults: React.FC<{
filter: PollHistoryFilter;
oldestFetchedEventTimestamp?: number;
loadMorePolls?: () => void;
isLoading?: boolean;
}> = ({ filter, isLoading, oldestFetchedEventTimestamp, loadMorePolls }) => {
// we can't page the timeline anymore
// just use plain loader
if (!loadMorePolls && isLoading) {
return <LoadingPolls noResultsYet />;
}
return (
<span className="mx_PollHistoryList_noResults">
{getNoResultsMessage(filter, oldestFetchedEventTimestamp, loadMorePolls)}
{!!loadMorePolls && <LoadMorePolls loadMorePolls={loadMorePolls} isLoading={isLoading} />}
</span>
);
};
type PollHistoryListProps = {
pollStartEvents: MatrixEvent[];
polls: Map<string, Poll>;
filter: PollHistoryFilter;
/**
* server ts of the oldest fetched poll
* ignoring filter
* used to render no results in last x days message
* undefined when no polls are found
*/
oldestFetchedEventTimestamp?: number;
onFilterChange: (filter: PollHistoryFilter) => void;
onItemClick: (pollId: string) => void;
loadMorePolls?: () => void;
isLoading?: boolean;
};
export const PollHistoryList: React.FC<PollHistoryListProps> = ({
pollStartEvents,
polls,
filter,
isLoading,
oldestFetchedEventTimestamp,
onFilterChange,
loadMorePolls,
onItemClick,
}) => {
return (
<div className="mx_PollHistoryList">
<FilterTabGroup<PollHistoryFilter>
name="PollHistory_filter"
value={filter}
onFilterChange={onFilterChange}
tabs={[
{ id: "ACTIVE", label: "Active polls" },
{ id: "ENDED", label: "Past polls" },
]}
/>
{!!pollStartEvents.length && (
<ol className={classNames("mx_PollHistoryList_list", `mx_PollHistoryList_list_${filter}`)}>
{pollStartEvents.map((pollStartEvent) =>
filter === "ACTIVE" ? (
<PollListItem
key={pollStartEvent.getId()!}
event={pollStartEvent}
onClick={() => onItemClick(pollStartEvent.getId()!)}
/>
) : (
<PollListItemEnded
key={pollStartEvent.getId()!}
event={pollStartEvent}
poll={polls.get(pollStartEvent.getId()!)!}
onClick={() => onItemClick(pollStartEvent.getId()!)}
/>
),
)}
{isLoading && !loadMorePolls && <LoadingPolls />}
{!!loadMorePolls && <LoadMorePolls loadMorePolls={loadMorePolls} isLoading={isLoading} />}
</ol>
)}
{!pollStartEvents.length && (
<NoResults
oldestFetchedEventTimestamp={oldestFetchedEventTimestamp}
isLoading={isLoading}
filter={filter}
loadMorePolls={loadMorePolls}
/>
)}
</div>
);
};

View file

@ -0,0 +1,49 @@
/*
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 { PollStartEvent } from "matrix-js-sdk/src/extensible_events_v1/PollStartEvent";
import { MatrixEvent } from "matrix-js-sdk/src/matrix";
import { Icon as PollIcon } from "../../../../../res/img/element-icons/room/composer/poll.svg";
import { formatLocalDateShort } from "../../../../DateUtils";
import { _t } from "../../../../languageHandler";
import TooltipTarget from "../../elements/TooltipTarget";
import { Alignment } from "../../elements/Tooltip";
interface Props {
event: MatrixEvent;
onClick: () => void;
}
export const PollListItem: React.FC<Props> = ({ event, onClick }) => {
const pollEvent = event.unstableExtensibleEvent as unknown as PollStartEvent;
if (!pollEvent) {
return null;
}
const formattedDate = formatLocalDateShort(event.getTs());
return (
<li data-testid={`pollListItem-${event.getId()!}`} className="mx_PollListItem" onClick={onClick}>
<TooltipTarget label={_t("View poll")} alignment={Alignment.Top}>
<div className="mx_PollListItem_content">
<span>{formattedDate}</span>
<PollIcon className="mx_PollListItem_icon" />
<span className="mx_PollListItem_question">{pollEvent.question.text}</span>
</div>
</TooltipTarget>
</li>
);
};

View file

@ -0,0 +1,134 @@
/*
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";
import TooltipTarget from "../../elements/TooltipTarget";
import { Alignment } from "../../elements/Tooltip";
interface Props {
event: MatrixEvent;
poll: Poll;
onClick: () => void;
}
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, onClick }) => {
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" onClick={onClick}>
<TooltipTarget label={_t("View poll")} alignment={Alignment.Top}>
<div className="mx_PollListItemEnded_content">
<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>
</div>
</TooltipTarget>
</li>
);
};

View file

@ -0,0 +1,222 @@
/*
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 { useCallback, useEffect, useState } from "react";
import { M_POLL_START } from "matrix-js-sdk/src/@types/polls";
import { MatrixClient } from "matrix-js-sdk/src/client";
import { Direction, EventTimeline, EventTimelineSet, Room } from "matrix-js-sdk/src/matrix";
import { Filter, IFilterDefinition } from "matrix-js-sdk/src/filter";
import { logger } from "matrix-js-sdk/src/logger";
const getOldestEventTimestamp = (timelineSet?: EventTimelineSet): number | undefined => {
if (!timelineSet) {
return;
}
const liveTimeline = timelineSet?.getLiveTimeline();
const events = liveTimeline.getEvents();
return events[0]?.getTs();
};
/**
* Page backwards in timeline history
* @param timelineSet - timelineset to page
* @param matrixClient - client
* @param canPageBackward - whether the timeline has more pages
* @param oldestEventTimestamp - server ts of the oldest encountered event
*/
const pagePollHistory = async (
timelineSet: EventTimelineSet,
matrixClient: MatrixClient,
): Promise<{
oldestEventTimestamp?: number;
canPageBackward: boolean;
}> => {
if (!timelineSet) {
return { canPageBackward: false };
}
const liveTimeline = timelineSet.getLiveTimeline();
await matrixClient.paginateEventTimeline(liveTimeline, {
backwards: true,
});
return {
oldestEventTimestamp: getOldestEventTimestamp(timelineSet),
canPageBackward: !!liveTimeline.getPaginationToken(EventTimeline.BACKWARDS),
};
};
/**
* Page timeline backwards until either:
* - event older than timestamp is encountered
* - end of timeline is reached
* @param timelineSet - timeline set to page
* @param matrixClient - client
* @param timestamp - epoch timestamp to page until
* @param canPageBackward - whether the timeline has more pages
* @param oldestEventTimestamp - server ts of the oldest encountered event
*/
const fetchHistoryUntilTimestamp = async (
timelineSet: EventTimelineSet | undefined,
matrixClient: MatrixClient,
timestamp: number,
canPageBackward: boolean,
oldestEventTimestamp?: number,
): Promise<void> => {
if (!timelineSet || !canPageBackward || (oldestEventTimestamp && oldestEventTimestamp < timestamp)) {
return;
}
const result = await pagePollHistory(timelineSet, matrixClient);
return fetchHistoryUntilTimestamp(
timelineSet,
matrixClient,
timestamp,
result.canPageBackward,
result.oldestEventTimestamp,
);
};
const ONE_DAY_MS = 60000 * 60 * 24;
/**
* Fetches timeline history for given number of days in past
* @param timelineSet - timelineset to page
* @param matrixClient - client
* @param historyPeriodDays - number of days of history to fetch, from current day
* @returns isLoading - true while fetching
* @returns oldestEventTimestamp - timestamp of oldest encountered poll, undefined when no polls found in timeline so far
* @returns loadMorePolls - function to page timeline backwards, undefined when timeline cannot be paged backwards
* @returns loadTimelineHistory - loads timeline history for the given history period
*/
const useTimelineHistory = (
timelineSet: EventTimelineSet | undefined,
matrixClient: MatrixClient,
historyPeriodDays: number,
): {
isLoading: boolean;
oldestEventTimestamp?: number;
loadTimelineHistory: () => Promise<void>;
loadMorePolls?: () => Promise<void>;
} => {
const [isLoading, setIsLoading] = useState(true);
const [oldestEventTimestamp, setOldestEventTimestamp] = useState<number | undefined>(undefined);
const [canPageBackward, setCanPageBackward] = useState(false);
const loadTimelineHistory = useCallback(async () => {
const endOfHistoryPeriodTimestamp = Date.now() - ONE_DAY_MS * historyPeriodDays;
setIsLoading(true);
try {
const liveTimeline = timelineSet?.getLiveTimeline();
const canPageBackward = !!liveTimeline?.getPaginationToken(Direction.Backward);
const oldestEventTimestamp = getOldestEventTimestamp(timelineSet);
await fetchHistoryUntilTimestamp(
timelineSet,
matrixClient,
endOfHistoryPeriodTimestamp,
canPageBackward,
oldestEventTimestamp,
);
setCanPageBackward(!!timelineSet?.getLiveTimeline()?.getPaginationToken(EventTimeline.BACKWARDS));
setOldestEventTimestamp(getOldestEventTimestamp(timelineSet));
} catch (error) {
logger.error("Failed to fetch room polls history", error);
} finally {
setIsLoading(false);
}
}, [historyPeriodDays, timelineSet, matrixClient]);
const loadMorePolls = useCallback(async () => {
if (!timelineSet) {
return;
}
setIsLoading(true);
try {
const result = await pagePollHistory(timelineSet, matrixClient);
setCanPageBackward(result.canPageBackward);
setOldestEventTimestamp(result.oldestEventTimestamp);
} catch (error) {
logger.error("Failed to fetch room polls history", error);
} finally {
setIsLoading(false);
}
}, [timelineSet, matrixClient]);
return {
isLoading,
oldestEventTimestamp,
loadTimelineHistory,
loadMorePolls: canPageBackward ? loadMorePolls : undefined,
};
};
const filterDefinition: IFilterDefinition = {
room: {
timeline: {
types: [M_POLL_START.name, M_POLL_START.altName],
},
},
};
/**
* Fetches poll start events in the last N days of room history
* @param room - room to fetch history for
* @param matrixClient - client
* @param historyPeriodDays - number of days of history to fetch, from current day
* @returns isLoading - true while fetching history
* @returns oldestEventTimestamp - timestamp of oldest encountered poll, undefined when no polls found in timeline so far
* @returns loadMorePolls - function to page timeline backwards, undefined when timeline cannot be paged backwards
*/
export const useFetchPastPolls = (
room: Room,
matrixClient: MatrixClient,
historyPeriodDays = 30,
): {
isLoading: boolean;
oldestEventTimestamp?: number;
loadMorePolls?: () => Promise<void>;
} => {
const [timelineSet, setTimelineSet] = useState<EventTimelineSet | undefined>(undefined);
useEffect(() => {
const filter = new Filter(matrixClient.getSafeUserId());
filter.setDefinition(filterDefinition);
const getFilteredTimelineSet = async (): Promise<void> => {
const filterId = await matrixClient.getOrCreateFilter(`POLL_HISTORY_FILTER_${room.roomId}}`, filter);
filter.filterId = filterId;
const timelineSet = room.getOrCreateFilteredTimelineSet(filter);
setTimelineSet(timelineSet);
};
getFilteredTimelineSet();
}, [room, matrixClient]);
const { isLoading, oldestEventTimestamp, loadMorePolls, loadTimelineHistory } = useTimelineHistory(
timelineSet,
matrixClient,
historyPeriodDays,
);
useEffect(() => {
loadTimelineHistory();
}, [loadTimelineHistory]);
return { isLoading, oldestEventTimestamp, loadMorePolls };
};

View file

@ -0,0 +1,22 @@
/*
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.
*/
/**
* Possible values for the "filter" setting in the poll history dialog
*
* Ended polls have a valid M_POLL_END event
*/
export type PollHistoryFilter = "ACTIVE" | "ENDED";

View file

@ -0,0 +1,96 @@
/*
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 { useEffect, useState } from "react";
import { Poll, PollEvent } from "matrix-js-sdk/src/matrix";
import { MatrixClient } from "matrix-js-sdk/src/client";
import { useEventEmitterState } from "../../../../hooks/useEventEmitter";
/**
* Get poll instances from a room
* Updates to include new polls
* @param roomId - id of room to retrieve polls for
* @param matrixClient - client
* @returns {Map<string, Poll>} - Map of Poll instances
*/
export const usePolls = (
roomId: string,
matrixClient: MatrixClient,
): {
polls: Map<string, Poll>;
} => {
const room = matrixClient.getRoom(roomId);
if (!room) {
throw new Error("Cannot find room");
}
// copy room.polls map so changes can be detected
const polls = useEventEmitterState(room, PollEvent.New, () => new Map<string, Poll>(room.polls));
return { polls };
};
/**
* Get all poll instances from a room
* Fetch their responses (using cached poll responses)
* Updates on:
* - new polls added to room
* - new responses added to polls
* - changes to poll ended state
* @param roomId - id of room to retrieve polls for
* @param matrixClient - client
* @returns {Map<string, Poll>} - Map of Poll instances
*/
export const usePollsWithRelations = (
roomId: string,
matrixClient: MatrixClient,
): {
polls: Map<string, Poll>;
} => {
const { polls } = usePolls(roomId, matrixClient);
const [pollsWithRelations, setPollsWithRelations] = useState<Map<string, Poll>>(polls);
useEffect(() => {
const onPollUpdate = async (): Promise<void> => {
// trigger rerender by creating a new poll map
setPollsWithRelations(new Map(polls));
};
if (polls) {
for (const poll of polls.values()) {
// listen to changes in responses and end state
poll.on(PollEvent.End, onPollUpdate);
poll.on(PollEvent.Responses, onPollUpdate);
// trigger request to get all responses
// if they are not already in cache
poll.getResponses();
}
setPollsWithRelations(polls);
}
// unsubscribe
return () => {
if (polls) {
for (const poll of polls.values()) {
poll.off(PollEvent.End, onPollUpdate);
poll.off(PollEvent.Responses, onPollUpdate);
}
}
};
}, [polls, setPollsWithRelations]);
return { polls: pollsWithRelations };
};