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

Add mark as read option in room setting #9798

Merged
merged 10 commits into from
Dec 22, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
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
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 {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This should be done using the SVG icon approach but would warrant too large of a refactor on an untested part of the codebase that I do not want to test right now.

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.
38 changes: 27 additions & 11 deletions src/components/views/context_menus/RoomGeneralContextMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { _t } from "../../../languageHandler";
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 +37,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 +59,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 @@ -201,17 +202,32 @@ export const RoomGeneralContextMenu = ({
);
}

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

return (
<IconizedContextMenu {...props} onFinished={onFinished} className="mx_RoomGeneralContextMenu" compact>
{!roomTags.includes(DefaultTagID.Archived) && (
<IconizedContextMenuOptionList>
{favoriteOption}
{lowPriorityOption}
{inviteOption}
{copyLinkOption}
{settingsOption}
</IconizedContextMenuOptionList>
)}
<IconizedContextMenuOptionList>
{!roomTags.includes(DefaultTagID.Archived) && (
<>
{favoriteOption}
{lowPriorityOption}
{inviteOption}
{copyLinkOption}
{settingsOption}
</>
)}
{markAsReadOption}
</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 @@ -3182,6 +3182,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: 53 additions & 19 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,61 @@ export function localNotificationsAreSilenced(cli: MatrixClient): boolean {
return event?.getContent<LocalNotificationSettings>()?.is_silenced ?? false;
}

/**
* 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<{}> {
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;

let promise: Promise<{}>;
germain-gg marked this conversation as resolved.
Show resolved Hide resolved

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);
}
}

return promise ?? {};
germain-gg marked this conversation as resolved.
Show resolved Hide resolved
}

/**
* 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<{}>> {
const receiptPromises = client.getRooms().reduce((promises, 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;

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