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

Commit

Permalink
Add mark as read option in room setting (#9798)
Browse files Browse the repository at this point in the history
  • Loading branch information
Germain authored Dec 22, 2022
1 parent ce75d33 commit e9224f6
Show file tree
Hide file tree
Showing 9 changed files with 378 additions and 37 deletions.
4 changes: 4 additions & 0 deletions res/css/views/context_menus/_RoomGeneralContextMenu.pcss
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@
mask-image: url("$(res)/img/element-icons/roomlist/low-priority.svg");
}

.mx_RoomGeneralContextMenu_iconMarkAsRead::before {
mask-image: url("$(res)/img/element-icons/roomlist/mark-as-read.svg");
}

.mx_RoomGeneralContextMenu_iconNotificationsDefault::before {
mask-image: url("$(res)/img/element-icons/notifications.svg");
}
Expand Down
3 changes: 3 additions & 0 deletions res/img/element-icons/roomlist/mark-as-read.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
48 changes: 34 additions & 14 deletions src/components/views/context_menus/RoomGeneralContextMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,14 @@ import RoomListActions from "../../../actions/RoomListActions";
import MatrixClientContext from "../../../contexts/MatrixClientContext";
import dis from "../../../dispatcher/dispatcher";
import { useEventEmitterState } from "../../../hooks/useEventEmitter";
import { useUnreadNotifications } from "../../../hooks/useUnreadNotifications";
import { getKeyBindingsManager } from "../../../KeyBindingsManager";
import { _t } from "../../../languageHandler";
import { NotificationColor } from "../../../stores/notifications/NotificationColor";
import { DefaultTagID, TagID } from "../../../stores/room-list/models";
import RoomListStore, { LISTS_UPDATE_EVENT } from "../../../stores/room-list/RoomListStore";
import DMRoomMap from "../../../utils/DMRoomMap";
import { clearRoomNotification } from "../../../utils/notifications";
import { IProps as IContextMenuProps } from "../../structures/ContextMenu";
import IconizedContextMenu, {
IconizedContextMenuCheckbox,
Expand All @@ -36,7 +39,7 @@ import IconizedContextMenu, {
} from "../context_menus/IconizedContextMenu";
import { ButtonEvent } from "../elements/AccessibleButton";

interface IProps extends IContextMenuProps {
export interface RoomGeneralContextMenuProps extends IContextMenuProps {
room: Room;
onPostFavoriteClick?: (event: ButtonEvent) => void;
onPostLowPriorityClick?: (event: ButtonEvent) => void;
Expand All @@ -58,7 +61,7 @@ export const RoomGeneralContextMenu = ({
onPostLeaveClick,
onPostForgetClick,
...props
}: IProps) => {
}: RoomGeneralContextMenuProps) => {
const cli = useContext(MatrixClientContext);
const roomTags = useEventEmitterState(RoomListStore.instance, LISTS_UPDATE_EVENT, () =>
RoomListStore.instance.getTagsForRoom(room),
Expand Down Expand Up @@ -115,8 +118,8 @@ export const RoomGeneralContextMenu = ({
/>
);

let inviteOption: JSX.Element;
if (room.canInvite(cli.getUserId()) && !isDm) {
let inviteOption: JSX.Element | null = null;
if (room.canInvite(cli.getUserId()!) && !isDm) {
inviteOption = (
<IconizedContextMenuOption
onClick={wrapHandler(
Expand All @@ -133,7 +136,7 @@ export const RoomGeneralContextMenu = ({
);
}

let copyLinkOption: JSX.Element;
let copyLinkOption: JSX.Element | null = null;
if (!isDm) {
copyLinkOption = (
<IconizedContextMenuOption
Expand Down Expand Up @@ -201,17 +204,34 @@ export const RoomGeneralContextMenu = ({
);
}

const { color } = useUnreadNotifications(room);
const markAsReadOption: JSX.Element | null =
color > NotificationColor.None ? (
<IconizedContextMenuCheckbox
onClick={() => {
clearRoomNotification(room, cli);
onFinished?.();
}}
active={false}
label={_t("Mark as read")}
iconClassName="mx_RoomGeneralContextMenu_iconMarkAsRead"
/>
) : null;

return (
<IconizedContextMenu {...props} onFinished={onFinished} className="mx_RoomGeneralContextMenu" compact>
{!roomTags.includes(DefaultTagID.Archived) && (
<IconizedContextMenuOptionList>
{favoriteOption}
{lowPriorityOption}
{inviteOption}
{copyLinkOption}
{settingsOption}
</IconizedContextMenuOptionList>
)}
<IconizedContextMenuOptionList>
{markAsReadOption}
{!roomTags.includes(DefaultTagID.Archived) && (
<>
{favoriteOption}
{lowPriorityOption}
{inviteOption}
{copyLinkOption}
{settingsOption}
</>
)}
</IconizedContextMenuOptionList>
<IconizedContextMenuOptionList red>{leaveOption}</IconizedContextMenuOptionList>
</IconizedContextMenu>
);
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 @@ -3187,6 +3187,7 @@
"Copy room link": "Copy room link",
"Low Priority": "Low Priority",
"Forget Room": "Forget Room",
"Mark as read": "Mark as read",
"Use default": "Use default",
"Mentions & Keywords": "Mentions & Keywords",
"See room timeline (devtools)": "See room timeline (devtools)",
Expand Down
72 changes: 51 additions & 21 deletions src/utils/notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { MatrixClient } from "matrix-js-sdk/src/client";
import { LOCAL_NOTIFICATION_SETTINGS_PREFIX } from "matrix-js-sdk/src/@types/event";
import { LocalNotificationSettings } from "matrix-js-sdk/src/@types/local_notifications";
import { ReceiptType } from "matrix-js-sdk/src/@types/read_receipts";
import { Room } from "matrix-js-sdk/src/models/room";
import { NotificationCountType, Room } from "matrix-js-sdk/src/models/room";

import SettingsStore from "../settings/SettingsStore";

Expand Down Expand Up @@ -59,27 +59,57 @@ export function localNotificationsAreSilenced(cli: MatrixClient): boolean {
return event?.getContent<LocalNotificationSettings>()?.is_silenced ?? false;
}

export function clearAllNotifications(client: MatrixClient): Promise<Array<{}>> {
const receiptPromises = client.getRooms().reduce((promises, room: Room) => {
/**
* Mark a room as read
* @param room
* @param client
* @returns a promise that resolves when the room has been marked as read
*/
export async function clearRoomNotification(room: Room, client: MatrixClient): Promise<{} | undefined> {
const roomEvents = room.getLiveTimeline().getEvents();
const lastThreadEvents = room.lastThread?.events;

const lastRoomEvent = roomEvents?.[roomEvents?.length - 1];
const lastThreadLastEvent = lastThreadEvents?.[lastThreadEvents?.length - 1];

const lastEvent =
(lastRoomEvent?.getTs() ?? 0) > (lastThreadLastEvent?.getTs() ?? 0) ? lastRoomEvent : lastThreadLastEvent;

try {
if (lastEvent) {
const receiptType = SettingsStore.getValue("sendReadReceipts", room.roomId)
? ReceiptType.Read
: ReceiptType.ReadPrivate;
return await client.sendReadReceipt(lastEvent, receiptType, true);
} else {
return {};
}
} finally {
// We've had a lot of stuck unread notifications that in e2ee rooms
// They occur on event decryption when clients try to replicate the logic
//
// This resets the notification on a room, even though no read receipt
// has been sent, particularly useful when the clients has incorrectly
// notified a user.
room.setUnreadNotificationCount(NotificationCountType.Highlight, 0);
room.setUnreadNotificationCount(NotificationCountType.Total, 0);
for (const thread of room.getThreads()) {
room.setThreadUnreadNotificationCount(thread.id, NotificationCountType.Highlight, 0);
room.setThreadUnreadNotificationCount(thread.id, NotificationCountType.Total, 0);
}
}
}

/**
* Marks all rooms with an unread counter as read
* @param client The matrix client
* @returns a promise that resolves when all rooms have been marked as read
*/
export function clearAllNotifications(client: MatrixClient): Promise<Array<{} | undefined>> {
const receiptPromises = client.getRooms().reduce((promises: Array<Promise<{} | undefined>>, room: Room) => {
if (room.getUnreadNotificationCount() > 0) {
const roomEvents = room.getLiveTimeline().getEvents();
const lastThreadEvents = room.lastThread?.events;

const lastRoomEvent = roomEvents?.[roomEvents?.length - 1];
const lastThreadLastEvent = lastThreadEvents?.[lastThreadEvents?.length - 1];

const lastEvent =
(lastRoomEvent?.getTs() ?? 0) > (lastThreadLastEvent?.getTs() ?? 0)
? lastRoomEvent
: lastThreadLastEvent;

if (lastEvent) {
const receiptType = SettingsStore.getValue("sendReadReceipts", room.roomId)
? ReceiptType.Read
: ReceiptType.ReadPrivate;
const promise = client.sendReadReceipt(lastEvent, receiptType, true);
promises.push(promise);
}
const promise = clearRoomNotification(room, client);
promises.push(promise);
}

return promises;
Expand Down
113 changes: 113 additions & 0 deletions test/components/views/context_menus/RoomGeneralContextMenu-test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/*
Copyright 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 { fireEvent, getByLabelText, render } from "@testing-library/react";
import { mocked } from "jest-mock";
import { ReceiptType } from "matrix-js-sdk/src/@types/read_receipts";
import { MatrixClient, PendingEventOrdering } from "matrix-js-sdk/src/client";
import { Room } from "matrix-js-sdk/src/models/room";
import React from "react";

import { ChevronFace } from "../../../../src/components/structures/ContextMenu";
import {
RoomGeneralContextMenu,
RoomGeneralContextMenuProps,
} from "../../../../src/components/views/context_menus/RoomGeneralContextMenu";
import MatrixClientContext from "../../../../src/contexts/MatrixClientContext";
import { MatrixClientPeg } from "../../../../src/MatrixClientPeg";
import { DefaultTagID } from "../../../../src/stores/room-list/models";
import RoomListStore from "../../../../src/stores/room-list/RoomListStore";
import DMRoomMap from "../../../../src/utils/DMRoomMap";
import { mkMessage, stubClient } from "../../../test-utils/test-utils";

describe("RoomGeneralContextMenu", () => {
const ROOM_ID = "!123:matrix.org";

let room: Room;
let mockClient: MatrixClient;

let onFinished: () => void;

function getComponent(props?: Partial<RoomGeneralContextMenuProps>) {
return render(
<MatrixClientContext.Provider value={mockClient}>
<RoomGeneralContextMenu
room={room}
onFinished={onFinished}
{...props}
managed={true}
mountAsChild={true}
left={1}
top={1}
chevronFace={ChevronFace.Left}
/>
</MatrixClientContext.Provider>,
);
}

beforeEach(() => {
jest.clearAllMocks();

stubClient();
mockClient = mocked(MatrixClientPeg.get());

room = new Room(ROOM_ID, mockClient, mockClient.getUserId() ?? "", {
pendingEventOrdering: PendingEventOrdering.Detached,
});

const dmRoomMap = {
getUserIdForRoomId: jest.fn(),
} as unknown as DMRoomMap;
DMRoomMap.setShared(dmRoomMap);

jest.spyOn(RoomListStore.instance, "getTagsForRoom").mockReturnValueOnce([
DefaultTagID.DM,
DefaultTagID.Favourite,
]);

onFinished = jest.fn();
});

it("renders an empty context menu for archived rooms", async () => {
jest.spyOn(RoomListStore.instance, "getTagsForRoom").mockReturnValueOnce([DefaultTagID.Archived]);

const { container } = getComponent({});
expect(container).toMatchSnapshot();
});

it("renders the default context menu", async () => {
const { container } = getComponent({});
expect(container).toMatchSnapshot();
});

it("marks the room as read", async () => {
const event = mkMessage({
event: true,
room: "!room:id",
user: "@user:id",
ts: 1000,
});
room.addLiveEvents([event], {});

const { container } = getComponent({});

const markAsReadBtn = getByLabelText(container, "Mark as read");
fireEvent.click(markAsReadBtn);

expect(mockClient.sendReadReceipt).toHaveBeenCalledWith(event, ReceiptType.Read, true);
expect(onFinished).toHaveBeenCalled();
});
});
Loading

0 comments on commit e9224f6

Please sign in to comment.