From a7ae1a4451482206eeded81daeacc9d2bee10e44 Mon Sep 17 00:00:00 2001 From: Shea Date: Mon, 1 Jun 2026 21:23:30 +0300 Subject: [PATCH] optimizations Signed-off-by: Shea --- src/app/components/RenderMessageContent.tsx | 6 +- src/app/components/message/PollEvent.tsx | 91 ++++++++++++------- src/app/components/message/Reply.tsx | 17 ++-- src/app/features/room/add-poll/PollDialog.tsx | 42 ++++++--- .../room/room-pin-menu/RoomPinMenu.tsx | 2 +- 5 files changed, 104 insertions(+), 54 deletions(-) diff --git a/src/app/components/RenderMessageContent.tsx b/src/app/components/RenderMessageContent.tsx index 321d04296..c3b95a04d 100644 --- a/src/app/components/RenderMessageContent.tsx +++ b/src/app/components/RenderMessageContent.tsx @@ -46,6 +46,7 @@ import { TextViewer } from './text-viewer'; import { ClientSideHoverFreeze } from './ClientSideHoverFreeze'; import { CuteEventType, MCuteEvent } from './message/MCuteEvent'; import { PollEvent } from './message/PollEvent'; +import { M_TEXT } from 'matrix-js-sdk'; type RenderMessageContentProps = { displayName: string; @@ -457,9 +458,8 @@ function RenderMessageContentInternal({ diff --git a/src/app/components/message/PollEvent.tsx b/src/app/components/message/PollEvent.tsx index 2f404f826..fa014a883 100644 --- a/src/app/components/message/PollEvent.tsx +++ b/src/app/components/message/PollEvent.tsx @@ -1,5 +1,6 @@ import { Box, Button, Checkbox, Line, ProgressBar, RadioButton, Text } from 'folds'; -import type { MatrixClient, Room, TimelineEvents } from 'matrix-js-sdk'; +import type { MatrixClient, PollStartSubtype, Room, TimelineEvents } from 'matrix-js-sdk'; +import { M_TEXT } from 'matrix-js-sdk'; import { EventTimeline, M_POLL_END, @@ -10,6 +11,7 @@ import { type MatrixEvent, } from 'matrix-js-sdk'; import * as css from './PollEvent.css'; +import { useCallback, useEffect, useState } from 'react'; type PollEventProps = { content: Record; @@ -20,7 +22,7 @@ type PollEventProps = { export type PollAnswerItem = { id: string; - 'org.matrix.msc1767.text': string; + [M_TEXT.name]: string; }; type PollVotes = { @@ -37,15 +39,13 @@ type PollResponse = { }; }; export function PollEvent({ content, mEvent, mx, room }: PollEventProps) { - if (!content) return null; const eventId = mEvent.getId(); const userId = mx.getUserId() ?? ''; const roomId = room.roomId; const roomState = room.getLiveTimeline()?.getState(EventTimeline.FORWARDS); - const poll = content[M_POLL_START.name]; - const question = (poll as { question?: string })?.question; - const questionBody = (question as { body?: string })?.body ?? ''; + const poll = content[M_POLL_START.name] as PollStartSubtype; + const questionBody = (poll?.question as { body?: string })?.body ?? ''; const answers = (poll as { answers: PollAnswerItem[] })?.answers; const maxSelections = (poll as { max_selections: number })?.max_selections; const isDisclosed = (poll as { kind: string })?.kind === M_POLL_KIND_DISCLOSED.name; @@ -55,46 +55,75 @@ export function PollEvent({ content, mEvent, mx, room }: PollEventProps) { let votes: PollVotes = {}; answers.forEach((item) => (votes[item.id] = 0)); + // This should technically request the permissions at the time of the end of the event but that doesnt seem to be supported by the sdk + const getEndIndex = useCallback( + (events: MatrixEvent[]) => { + return events.findLastIndex( + (item) => + item.getContent()[M_POLL_END.name] && + (item.sender?.userId === mEvent.sender?.userId || + roomState?.maySendRedactionForEvent(mEvent, mEvent.sender?.userId ?? '')) + ); + }, + [roomState, mEvent] + ); + + const sortChildEvents = useCallback((events: MatrixEvent[]) => { + if (!events) return []; + + const sortedArray = events.toSorted((a: MatrixEvent, b: MatrixEvent) => + a.event.origin_server_ts && b.event.origin_server_ts + ? b.event.origin_server_ts - a.event.origin_server_ts + : 0 + ); + + return sortedArray; + }, []); + const childEvents = room ?.getUnfilteredTimelineSet() .relations.getAllChildEventsForEvent(eventId ?? '') .filter((event) => event.getRelation()?.rel_type === REFERENCE_RELATION.name); // manual sorting because the timeline is sometimes sent stupidly <3 - let sortedChildEvents = childEvents - ? childEvents.toSorted((a: MatrixEvent, b: MatrixEvent) => - a.event.origin_server_ts && b.event.origin_server_ts - ? b.event.origin_server_ts - a.event.origin_server_ts - : 0 - ) - : []; + const [sortedChildEvents, setSortedChildEvents] = useState(sortChildEvents(childEvents)); + const [isEnded, setIsEnded] = useState(getEndIndex(sortedChildEvents) !== -1); - // This should technically request the permissions at the time of the end of the event but that doesnt seem to be supported by the sdk - const endIndex = sortedChildEvents.findLastIndex( - (item) => - item.getContent()[M_POLL_END.name] && - (item.sender?.userId === mEvent.sender?.userId || - roomState?.maySendRedactionForEvent(mEvent, mEvent.sender?.userId ?? '')) - ); - const isEnded = endIndex !== -1; + // ensure a new sorted array is only generated when a new list is made + useEffect(() => { + let newChildEvents = childEvents ? sortChildEvents(childEvents) : []; + const newEndIndex = getEndIndex(newChildEvents); - if (isEnded) sortedChildEvents = sortedChildEvents.slice(endIndex + 1); + setSortedChildEvents(newChildEvents); + setIsEnded(newEndIndex !== -1); + // This is to avoid recomputation for anything but the childEvents changing + // oxlint-disable-next-line eslint-plugin-react-hooks/exhaustive-deps + }, [childEvents.length, sortChildEvents, getEndIndex]); + + if (!content) return null; + const finalArray = isEnded + ? sortedChildEvents.slice(getEndIndex(sortedChildEvents) + 1) + : sortedChildEvents; //filter for a unique event from each sender let voters = new Set(); let filteredChildEvents: MatrixEvent[] = []; - sortedChildEvents?.forEach((item) => { - if (item.event.sender && !voters.has(item.event.sender)) { - voters.add(item.event.sender); - filteredChildEvents.push(item); - } - }); + if (isDisclosed || isEnded) + finalArray?.forEach((item) => { + if (item.event.sender && !voters.has(item.event.sender)) { + voters.add(item.event.sender); + filteredChildEvents.push(item); + } + }); filteredChildEvents?.forEach((item) => { const VoteContent = item.getContent(); const response = VoteContent[M_POLL_RESPONSE.name]; const selections = response?.answers; - if (!selections || selections?.length > maxSelections) return; + if (selections.length > maxSelections || selections.length === 0) { + if (item.event.sender) voters.delete(item.event.sender); + return; + } selections.forEach((selection: string) => { if (votes[selection] !== undefined) votes[selection] += 1; @@ -141,7 +170,7 @@ export function PollEvent({ content, mEvent, mx, room }: PollEventProps) { event_id: eventId, }, 'org.matrix.msc3381.poll.end': {}, - 'org.matrix.msc1767.text': 'The Poll has ended', + [M_TEXT.name]: 'The Poll has ended', body: 'The poll has ended', msgtype: 'm.text', }; @@ -160,7 +189,7 @@ export function PollEvent({ content, mEvent, mx, room }: PollEventProps) { {answers.map((item) => { - const optionBody = item['org.matrix.msc1767.text']; + const optionBody = item[M_TEXT.name]; const voteCount = votes[item.id]; const isSelected = userSelection?.includes(item.id); return ( diff --git a/src/app/components/message/Reply.tsx b/src/app/components/message/Reply.tsx index fb418c1d7..c32e1c6ab 100644 --- a/src/app/components/message/Reply.tsx +++ b/src/app/components/message/Reply.tsx @@ -44,7 +44,7 @@ import { } from './content'; import * as css from './Reply.css'; import { LinePlaceholder } from './placeholder'; -import { M_POLL_START } from 'matrix-js-sdk'; +import { M_POLL_START, M_TEXT } from 'matrix-js-sdk'; const ROOM_REPLY_TIMELINE_EVENT_TYPES = new Set([ EventType.RoomMessage as string, @@ -204,7 +204,7 @@ export const Reply = as<'div', ReplyProps>( const mx = useMatrixClient(); const { body, formatted_body: formattedBody, format } = replyEvent?.getContent() ?? {}; - const extensibleContent = replyEvent?.getContent()['org.matrix.msc1767.text'] as + const extensibleContent = replyEvent?.getContent()[M_TEXT.name] as | string | { body: string } | undefined; @@ -273,12 +273,15 @@ export const Reply = as<'div', ReplyProps>( }), [mx, room.roomId, mentionClickHandler, nicknames, settingsLinkBaseUrl] ); - if(eventType === M_POLL_START.name){ - const question = (replyEvent?.getContent()[M_POLL_START.name] as {question: {'org.matrix.msc1767.text'?: string, body?: string}})?.question; + if (eventType === M_POLL_START.name) { + const question = ( + replyEvent?.getContent()[M_POLL_START.name] as { + question: { [M_TEXT.name]?: string; body?: string }; + } + )?.question; image = Icons.UnorderList; - bodyJSX = `'s poll asking ${question['org.matrix.msc1767.text'] ?? question.body ?? ''}` - } - else if (isFormattedReply && formattedBody !== '') { + bodyJSX = `'s poll asking ${(question[M_TEXT.name] as string) ?? question.body ?? ''}`; + } else if (isFormattedReply && formattedBody !== '') { const sanitizedHtml = sanitizeReplyFormattedPreview(formattedBody); if (shouldParseReplyFormattedPreview(sanitizedHtml)) { const parserOpts = getReactCustomHtmlParser(mx, room.roomId, { diff --git a/src/app/features/room/add-poll/PollDialog.tsx b/src/app/features/room/add-poll/PollDialog.tsx index cb66c852c..9dd567411 100644 --- a/src/app/features/room/add-poll/PollDialog.tsx +++ b/src/app/features/room/add-poll/PollDialog.tsx @@ -24,7 +24,12 @@ import { SettingTile } from '$components/setting-tile'; import { SequenceCard } from '$components/sequence-card'; import { SequenceCardStyle } from '$features/settings/styles.css'; import type { IContent, MatrixClient, Room, TimelineEvents } from 'matrix-js-sdk'; -import { M_POLL_KIND_DISCLOSED, M_POLL_KIND_UNDISCLOSED, M_POLL_START } from 'matrix-js-sdk'; +import { + M_POLL_KIND_DISCLOSED, + M_POLL_KIND_UNDISCLOSED, + M_POLL_START, + M_TEXT, +} from 'matrix-js-sdk'; import { isKeyHotkey } from 'is-hotkey'; import * as css from './PollDialog.css'; import type { IReplyDraft } from '$state/room/roomInputDrafts'; @@ -47,30 +52,46 @@ export function PollDialog({ onCancel, mx, room, replyDraft, clearReplyDraft }: const [answers, setAnswers] = useState([ { id: randomStr(), - 'org.matrix.msc1767.text': '', + [M_TEXT.name]: '', }, { id: randomStr(), - 'org.matrix.msc1767.text': '', + [M_TEXT.name]: '', }, ]); const addOption = useCallback(() => { - if (maxSelections === answers.length) setMaxSelections(maxSelections + 1); + if (maxSelections === answers.length) { + setMaxSelections(maxSelections + 1); + setInputValue(maxSelections + 1); + } setAnswers([ ...answers, { id: randomStr(), - 'org.matrix.msc1767.text': '', + [M_TEXT.name]: '', }, ]); }, [answers, setAnswers, maxSelections, setMaxSelections]); + const delOption = useCallback( + (id: string) => { + if (answers.length > 2) { + if (maxSelections === answers.length) { + setMaxSelections(maxSelections - 1); + setInputValue(maxSelections - 1); + } + setAnswers(answers.filter((answer) => answer.id !== id)); + } + }, + [answers, setAnswers, maxSelections, setMaxSelections] + ); const handleSubmit = () => { + if (!title) return; // its an IContent instead of the proper object because the proper object doesnt work w other clients :> const pollContent: IContent = { [M_POLL_START.name]: { question: { - 'org.matrix.msc1767.text': title.current, + [M_TEXT.name]: title.current, body: title.current, msgtype: 'm.text', }, @@ -78,7 +99,7 @@ export function PollDialog({ onCancel, mx, room, replyDraft, clearReplyDraft }: max_selections: maxSelections, answers: answers, }, - 'org.matrix.msc1767.text': `New poll\n Question: ${title.current}\nAnswers:\n ${answers.map((item) => item['org.matrix.msc1767.text']).join('\n')}`, + [M_TEXT.name]: `New poll\n Question: ${title.current}\nAnswers:\n ${answers.map((item) => item[M_TEXT.name]).join('\n')}`, }; if (replyDraft && clearReplyDraft) { pollContent['m.relates_to'] = getReplyContent(replyDraft, room); @@ -170,7 +191,7 @@ export function PollDialog({ onCancel, mx, room, replyDraft, clearReplyDraft }: let newAnswers = answers; newAnswers[index] = { id: answers[index]?.id ?? randomStr(), - 'org.matrix.msc1767.text': evt.currentTarget.value.trim() ?? '', + [M_TEXT.name]: evt.currentTarget.value.trim() ?? '', }; setAnswers(newAnswers); }} @@ -182,10 +203,7 @@ export function PollDialog({ onCancel, mx, room, replyDraft, clearReplyDraft }: disabled={answers.length <= 2} aria-disabled={answers.length <= 2} aria-label="Remove Option" - onClick={() => { - if (answers.length > 2) - setAnswers(answers.filter((answer) => answer.id !== item.id)); - }} + onClick={() => delOption(item.id)} > diff --git a/src/app/features/room/room-pin-menu/RoomPinMenu.tsx b/src/app/features/room/room-pin-menu/RoomPinMenu.tsx index 1bbdb3bb6..25bc658df 100644 --- a/src/app/features/room/room-pin-menu/RoomPinMenu.tsx +++ b/src/app/features/room/room-pin-menu/RoomPinMenu.tsx @@ -197,7 +197,7 @@ function PinnedMessageActiveContent( /> )} - {renderContent(pinnedEvent.getType(), false, pinnedEvent, displayName, getContent)} + {renderContent(pinnedEvent.getType(), false, pinnedEvent, displayName, getContent)} );