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

Starred Messages View Screen #9182

Closed
wants to merge 18 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/PageTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ enum PageType {
RoomView = "room_view",
UserView = "user_view",
LegacyGroupView = "legacy_group_view",
FavouriteMessagesView = "favourite_messages_view"
}

export default PageType;
88 changes: 88 additions & 0 deletions src/components/structures/FavouriteMessagesView.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd
Copyright 2018, 2019 New Vector Ltd
Copyright 2019 - 2022 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 { MatrixClient, MatrixEvent } from 'matrix-js-sdk/src/matrix';
import React, { useContext, useRef } from 'react';

import MatrixClientContext from '../../contexts/MatrixClientContext';
import { _t } from '../../languageHandler';
import FavouriteMessageTile from '../views/rooms/FavouriteMessageTile';
import ScrollPanel from './ScrollPanel';

function getFavouriteMessagesTiles(cli: MatrixClient, favouriteMessageEvents) {
yaya-usman marked this conversation as resolved.
Show resolved Hide resolved
const ret = [];
let lastRoomId: string;

for (let i = (favouriteMessageEvents?.length || 0) - 1; i >= 0; i--) {
const timeline = [] as MatrixEvent[];
const resultObj = favouriteMessageEvents[i];
const roomId = resultObj.roomId;
const room = cli.getRoom(roomId);
const mxEvent = room.findEventById(resultObj.eventId);
timeline.push(mxEvent);

if (roomId !== lastRoomId) {
ret.push(<li key={mxEvent?.getId() + "-room"}>
<h2>{ _t("Room") }: { room.name }</h2>
</li>);
lastRoomId = roomId;
}

const resultLink = "#/room/"+roomId+"/"+mxEvent.getId();

ret.push(
<FavouriteMessageTile
key={mxEvent.getId()}
result={mxEvent}
resultLink={resultLink}
timeline={timeline}
/>,
);
}
return ret;
}

let favouriteMessagesPanel;

const FavouriteMessagesView = () => {
const favouriteMessageEvents= JSON.parse(
yaya-usman marked this conversation as resolved.
Show resolved Hide resolved
localStorage?.getItem("io_element_favouriteMessages") ?? "[]") as any[];

const favouriteMessagesPanelRef = useRef<ScrollPanel>();
const cli = useContext<MatrixClient>(MatrixClientContext);

if (favouriteMessageEvents?.length === 0) {
favouriteMessagesPanel = (<h2 className="mx_RoomView_topMarker">{ _t("No Saved Messages") }</h2>);
} else {
favouriteMessagesPanel = (
<ScrollPanel
ref={favouriteMessagesPanelRef}
className="mx_RoomView_searchResultsPanel "
>
{ getFavouriteMessagesTiles(cli, favouriteMessageEvents) }
</ScrollPanel>
);
}

return (
<> { favouriteMessagesPanel } </>
);
};

export default FavouriteMessagesView;
1 change: 1 addition & 0 deletions src/components/structures/LeftPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,7 @@ export default class LeftPanel extends React.Component<IProps, IState> {
onResize={this.refreshStickyHeaders}
onListCollapse={this.refreshStickyHeaders}
ref={this.roomListRef}
pageType={this.props.pageType}
/>;

const containerClasses = classNames({
Expand Down
5 changes: 5 additions & 0 deletions src/components/structures/LoggedInView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ import LegacyGroupView from "./LegacyGroupView";
import { IConfigOptions } from "../../IConfigOptions";
import LeftPanelLiveShareWarning from '../views/beacon/LeftPanelLiveShareWarning';
import { UserOnboardingPage } from '../views/user-onboarding/UserOnboardingPage';
import FavouriteMessagesView from './FavouriteMessagesView';

// We need to fetch each pinned message individually (if we don't already have it)
// so each pinned message may trigger a request. Limit the number per room for sanity.
Expand Down Expand Up @@ -645,6 +646,10 @@ class LoggedInView extends React.Component<IProps, IState> {
case PageTypes.LegacyGroupView:
pageElement = <LegacyGroupView groupId={this.props.currentGroupId} />;
break;

case PageTypes.FavouriteMessagesView:
pageElement = <FavouriteMessagesView />;
break;
}

const wrapperClasses = classNames({
Expand Down
12 changes: 12 additions & 0 deletions src/components/structures/MatrixChat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -803,6 +803,9 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
hideAnalyticsToast();
SettingsStore.setValue("pseudonymousAnalyticsOptIn", null, SettingLevel.ACCOUNT, true);
break;
case Action.ViewFavouriteMessages:
this.viewFavouriteMessages();
break;
case Action.PseudonymousAnalyticsReject:
hideAnalyticsToast();
SettingsStore.setValue("pseudonymousAnalyticsOptIn", null, SettingLevel.ACCOUNT, false);
Expand Down Expand Up @@ -1007,6 +1010,11 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
this.themeWatcher.recheck();
}

private viewFavouriteMessages() {
this.setPage(PageType.FavouriteMessagesView);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder what method calls from viewHome() should also be here - I think we need the logged in view? What about the theme thing - what does that do?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As for the logged in view, yea i guess it's needed but regarding the theme thing, i am not too sure what it does. But so far in my demo when i switch themes it works correctly, so i don't think it's necessary in this case.

this.notifyNewScreen('favourite_messages');
}

private viewUser(userId: string, subAction: string) {
// Wait for the first sync so that `getRoom` gives us a room object if it's
// in the sync response
Expand Down Expand Up @@ -1704,6 +1712,10 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
dis.dispatch({
action: Action.ViewHomePage,
});
} else if (screen === 'favourite_messages') {
dis.dispatch({
action: Action.ViewFavouriteMessages,
});
} else if (screen === 'start') {
this.showScreen('home');
dis.dispatch({
Expand Down
11 changes: 5 additions & 6 deletions src/components/views/messages/MessageActionBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -258,18 +258,17 @@ interface IFavouriteButtonProp {
}

const FavouriteButton = ({ mxEvent }: IFavouriteButtonProp) => {
const { isFavourite, toggleFavourite } = useFavouriteMessages();
const { isFavourite, toggleFavourite } = useFavouriteMessages({ mxEvent });

const eventId = mxEvent.getId();
const classes = classNames("mx_MessageActionBar_iconButton mx_MessageActionBar_favouriteButton", {
'mx_MessageActionBar_favouriteButton_fillstar': isFavourite(eventId),
const classes = classNames("mx_MessageActionBar_iconButton", {
'mx_MessageActionBar_favouriteButton_fillstar': isFavourite(),
});

return <RovingAccessibleTooltipButton
className={classes}
title={_t("Favourite")}
onClick={() => toggleFavourite(eventId)}
data-testid={eventId}
onClick={() => toggleFavourite()}
data-testid={mxEvent.getId()}
>
<StarIcon />
</RovingAccessibleTooltipButton>;
Expand Down
113 changes: 113 additions & 0 deletions src/components/views/rooms/FavouriteMessageTile.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/*
Copyright 2015 OpenMarket Ltd
Copyright 2019 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 { MatrixEvent } from "matrix-js-sdk/src/models/event";

import RoomContext from "../../../contexts/RoomContext";
import SettingsStore from "../../../settings/SettingsStore";
import { RoomPermalinkCreator } from '../../../utils/permalinks/Permalinks';
import DateSeparator from "../messages/DateSeparator";
import EventTile from "./EventTile";
import { shouldFormContinuation } from "../../structures/MessagePanel";
import { wantsDateSeparator } from "../../../DateUtils";
import { haveRendererForEvent } from "../../../events/EventTileFactory";

interface IProps {
// an event result object
result: MatrixEvent;
// href for the highlights in this result
resultLink?: string;
onHeightChanged?: () => void;
permalinkCreator?: RoomPermalinkCreator;
//a list containing the saved items events
timeline?: MatrixEvent[];
}

export default class FavouriteMessageTile extends React.Component<IProps> {
static contextType = RoomContext;
public context!: React.ContextType<typeof RoomContext>;

constructor(props, context) {
super(props, context);
}

public render() {
const result = this.props.result;
const eventId = result.getId();

const ts1 = result?.getTs();
const ret = [<DateSeparator key={ts1 + "-search"} roomId={result.getRoomId()} ts={ts1} />];
const layout = SettingsStore.getValue("layout");
const isTwelveHour = SettingsStore.getValue("showTwelveHourTimestamps");
const alwaysShowTimestamps = SettingsStore.getValue("alwaysShowTimestamps");
const threadsEnabled = SettingsStore.getValue("feature_thread");

for (let j = 0; j < this.props.timeline.length; j++) {
const mxEv = this.props.timeline[j];

if (haveRendererForEvent(mxEv, this.context?.showHiddenEvents)) {
// do we need a date separator since the last event?
const prevEv = this.props.timeline[j - 1];
// is this a continuation of the previous message?
const continuation = prevEv &&
!wantsDateSeparator(prevEv.getDate(), mxEv.getDate()) &&
shouldFormContinuation(
prevEv,
mxEv,
this.context?.showHiddenEvents,
threadsEnabled,
);

let lastInSection = true;
const nextEv = this.props.timeline[j + 1];
if (nextEv) {
const willWantDateSeparator = wantsDateSeparator(mxEv.getDate(), nextEv.getDate());
lastInSection = (
willWantDateSeparator ||
mxEv.getSender() !== nextEv.getSender() ||
!shouldFormContinuation(
mxEv,
nextEv,
this.context?.showHiddenEvents,
threadsEnabled,
)
);
}

ret.push(
<EventTile
key={`${eventId}+${j}`}
mxEvent={mxEv}
layout={layout}
permalinkCreator={this.props.permalinkCreator}
highlightLink={this.props.resultLink}
onHeightChanged={this.props.onHeightChanged}
isTwelveHour={isTwelveHour}
alwaysShowTimestamps={alwaysShowTimestamps}
lastInSection={lastInSection}
continuation={continuation}
/>,
);
}
}

return <li data-scroll-tokens={eventId}>
<ol>{ ret }</ol>
</li>;
}
}
11 changes: 9 additions & 2 deletions src/components/views/rooms/RoomList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { ViewRoomPayload } from "../../../dispatcher/payloads/ViewRoomPayload";
import { useEventEmitterState } from "../../../hooks/useEventEmitter";
import { _t, _td } from "../../../languageHandler";
import { MatrixClientPeg } from "../../../MatrixClientPeg";
import PageType from "../../../PageTypes";
import PosthogTrackers from "../../../PosthogTrackers";
import SettingsStore from "../../../settings/SettingsStore";
import { UIComponent } from "../../../settings/UIFeature";
Expand Down Expand Up @@ -71,6 +72,7 @@ interface IProps {
resizeNotifier: ResizeNotifier;
isMinimized: boolean;
activeSpace: SpaceKey;
pageType: PageType;
}

interface IState {
Expand Down Expand Up @@ -570,15 +572,20 @@ export default class RoomList extends React.PureComponent<IProps, IState> {
resizeMethod="crop"
/>);

const onFavouriteClicked = () => {
defaultDispatcher.dispatch({ action: Action.ViewFavouriteMessages });
};

return [
<ExtraTile
isMinimized={this.props.isMinimized}
isSelected={false}
isSelected={this.props.pageType === PageType.FavouriteMessagesView}
displayName="Favourite Messages"
andybalaam marked this conversation as resolved.
Show resolved Hide resolved
avatar={avatar}
onClick={() => ""}
onClick={onFavouriteClicked}
key="favMessagesTile_key"
/>,

yaya-usman marked this conversation as resolved.
Show resolved Hide resolved
];
}

Expand Down
5 changes: 5 additions & 0 deletions src/dispatcher/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,4 +331,9 @@ export enum Action {
* Fired when we want to view a thread, either a new one or an existing one
*/
ShowThread = "show_thread",

/**
* Fired when we want to view favourited messages panel
*/
ViewFavouriteMessages = "view_favourite_messages",
}
22 changes: 15 additions & 7 deletions src/hooks/useFavouriteMessages.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

/*
Copyright 2022 The Matrix.org Foundation C.I.C.

Expand All @@ -15,20 +14,29 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import { MatrixEvent } from "matrix-js-sdk/src/models/event";
import { useState } from "react";

interface IButtonProp {
mxEvent: MatrixEvent;
}

const favouriteMessageIds = JSON.parse(
localStorage?.getItem("io_element_favouriteMessages")?? "[]") as string[];
localStorage?.getItem("io_element_favouriteMessages")?? "[]") as any[];

export default function useFavouriteMessages() {
export default function useFavouriteMessages({ mxEvent }: IButtonProp) {
const [, setX] = useState<string[]>();
const eventId = mxEvent.getId();
const roomId = mxEvent.getRoomId();

//checks if an id already exist
const isFavourite = (eventId: string): boolean => favouriteMessageIds.includes(eventId);
const isFavourite = (): boolean => {
return favouriteMessageIds.some(val => val.eventId === eventId);
};

const toggleFavourite = (eventId: string) => {
isFavourite(eventId) ? favouriteMessageIds.splice(favouriteMessageIds.indexOf(eventId), 1)
: favouriteMessageIds.push(eventId);
const toggleFavourite = () => {
isFavourite() ? favouriteMessageIds.splice(favouriteMessageIds.findIndex(val => val.eventId === eventId), 1)
: favouriteMessageIds.push({ eventId, roomId });

//update the local storage
localStorage.setItem('io_element_favouriteMessages', JSON.stringify(favouriteMessageIds));
Expand Down
1 change: 1 addition & 0 deletions src/i18n/strings/en_EN.json
Original file line number Diff line number Diff line change
Expand Up @@ -3109,6 +3109,7 @@
"Pause": "Pause",
"Play": "Play",
"Couldn't load page": "Couldn't load page",
"No Saved Messages": "No Saved Messages",
"Drop file here to upload": "Drop file here to upload",
"You must <a>register</a> to use this functionality": "You must <a>register</a> to use this functionality",
"You must join the room to see its files": "You must join the room to see its files",
Expand Down
Loading