Add mark as read option in room setting (#9798)

This commit is contained in:
Germain 2022-12-22 13:18:38 +00:00 committed by GitHub
parent ce75d3381f
commit e9224f6fce
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 378 additions and 37 deletions

View file

@ -6,6 +6,10 @@
mask-image: url("$(res)/img/element-icons/roomlist/low-priority.svg"); 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 { .mx_RoomGeneralContextMenu_iconNotificationsDefault::before {
mask-image: url("$(res)/img/element-icons/notifications.svg"); mask-image: url("$(res)/img/element-icons/notifications.svg");
} }

View file

@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M3.34474 4.9093C3.03141 5.10514 3.03141 5.56147 3.34474 5.7573L7.73468 8.50101C7.89681 8.60234 8.10254 8.60234 8.26467 8.50101L12.6546 5.7573C12.9679 5.56147 12.9679 5.10514 12.6546 4.9093L8.26467 2.16559C8.10254 2.06426 7.89681 2.06426 7.73468 2.16559L3.34474 4.9093ZM14.6663 5.3333V12C14.6663 12.3536 14.5259 12.6927 14.2758 12.9428C14.0258 13.1928 13.6866 13.3333 13.333 13.3333H2.66634C2.31272 13.3333 1.97358 13.1928 1.72353 12.9428C1.47348 12.6927 1.33301 12.3536 1.33301 12V5.3333C1.33301 4.84664 1.59301 4.42664 1.97967 4.1933L7.99967 0.426636L14.0197 4.1933C14.4063 4.42664 14.6663 4.84664 14.6663 5.3333Z" fill="currentColor"/>
</svg>

After

Width:  |  Height:  |  Size: 750 B

View file

@ -23,11 +23,14 @@ import RoomListActions from "../../../actions/RoomListActions";
import MatrixClientContext from "../../../contexts/MatrixClientContext"; import MatrixClientContext from "../../../contexts/MatrixClientContext";
import dis from "../../../dispatcher/dispatcher"; import dis from "../../../dispatcher/dispatcher";
import { useEventEmitterState } from "../../../hooks/useEventEmitter"; import { useEventEmitterState } from "../../../hooks/useEventEmitter";
import { useUnreadNotifications } from "../../../hooks/useUnreadNotifications";
import { getKeyBindingsManager } from "../../../KeyBindingsManager"; import { getKeyBindingsManager } from "../../../KeyBindingsManager";
import { _t } from "../../../languageHandler"; import { _t } from "../../../languageHandler";
import { NotificationColor } from "../../../stores/notifications/NotificationColor";
import { DefaultTagID, TagID } from "../../../stores/room-list/models"; import { DefaultTagID, TagID } from "../../../stores/room-list/models";
import RoomListStore, { LISTS_UPDATE_EVENT } from "../../../stores/room-list/RoomListStore"; import RoomListStore, { LISTS_UPDATE_EVENT } from "../../../stores/room-list/RoomListStore";
import DMRoomMap from "../../../utils/DMRoomMap"; import DMRoomMap from "../../../utils/DMRoomMap";
import { clearRoomNotification } from "../../../utils/notifications";
import { IProps as IContextMenuProps } from "../../structures/ContextMenu"; import { IProps as IContextMenuProps } from "../../structures/ContextMenu";
import IconizedContextMenu, { import IconizedContextMenu, {
IconizedContextMenuCheckbox, IconizedContextMenuCheckbox,
@ -36,7 +39,7 @@ import IconizedContextMenu, {
} from "../context_menus/IconizedContextMenu"; } from "../context_menus/IconizedContextMenu";
import { ButtonEvent } from "../elements/AccessibleButton"; import { ButtonEvent } from "../elements/AccessibleButton";
interface IProps extends IContextMenuProps { export interface RoomGeneralContextMenuProps extends IContextMenuProps {
room: Room; room: Room;
onPostFavoriteClick?: (event: ButtonEvent) => void; onPostFavoriteClick?: (event: ButtonEvent) => void;
onPostLowPriorityClick?: (event: ButtonEvent) => void; onPostLowPriorityClick?: (event: ButtonEvent) => void;
@ -58,7 +61,7 @@ export const RoomGeneralContextMenu = ({
onPostLeaveClick, onPostLeaveClick,
onPostForgetClick, onPostForgetClick,
...props ...props
}: IProps) => { }: RoomGeneralContextMenuProps) => {
const cli = useContext(MatrixClientContext); const cli = useContext(MatrixClientContext);
const roomTags = useEventEmitterState(RoomListStore.instance, LISTS_UPDATE_EVENT, () => const roomTags = useEventEmitterState(RoomListStore.instance, LISTS_UPDATE_EVENT, () =>
RoomListStore.instance.getTagsForRoom(room), RoomListStore.instance.getTagsForRoom(room),
@ -115,8 +118,8 @@ export const RoomGeneralContextMenu = ({
/> />
); );
let inviteOption: JSX.Element; let inviteOption: JSX.Element | null = null;
if (room.canInvite(cli.getUserId()) && !isDm) { if (room.canInvite(cli.getUserId()!) && !isDm) {
inviteOption = ( inviteOption = (
<IconizedContextMenuOption <IconizedContextMenuOption
onClick={wrapHandler( onClick={wrapHandler(
@ -133,7 +136,7 @@ export const RoomGeneralContextMenu = ({
); );
} }
let copyLinkOption: JSX.Element; let copyLinkOption: JSX.Element | null = null;
if (!isDm) { if (!isDm) {
copyLinkOption = ( copyLinkOption = (
<IconizedContextMenuOption <IconizedContextMenuOption
@ -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 ( return (
<IconizedContextMenu {...props} onFinished={onFinished} className="mx_RoomGeneralContextMenu" compact> <IconizedContextMenu {...props} onFinished={onFinished} className="mx_RoomGeneralContextMenu" compact>
{!roomTags.includes(DefaultTagID.Archived) && ( <IconizedContextMenuOptionList>
<IconizedContextMenuOptionList> {markAsReadOption}
{favoriteOption} {!roomTags.includes(DefaultTagID.Archived) && (
{lowPriorityOption} <>
{inviteOption} {favoriteOption}
{copyLinkOption} {lowPriorityOption}
{settingsOption} {inviteOption}
</IconizedContextMenuOptionList> {copyLinkOption}
)} {settingsOption}
</>
)}
</IconizedContextMenuOptionList>
<IconizedContextMenuOptionList red>{leaveOption}</IconizedContextMenuOptionList> <IconizedContextMenuOptionList red>{leaveOption}</IconizedContextMenuOptionList>
</IconizedContextMenu> </IconizedContextMenu>
); );

View file

@ -3187,6 +3187,7 @@
"Copy room link": "Copy room link", "Copy room link": "Copy room link",
"Low Priority": "Low Priority", "Low Priority": "Low Priority",
"Forget Room": "Forget Room", "Forget Room": "Forget Room",
"Mark as read": "Mark as read",
"Use default": "Use default", "Use default": "Use default",
"Mentions & Keywords": "Mentions & Keywords", "Mentions & Keywords": "Mentions & Keywords",
"See room timeline (devtools)": "See room timeline (devtools)", "See room timeline (devtools)": "See room timeline (devtools)",

View file

@ -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 { LOCAL_NOTIFICATION_SETTINGS_PREFIX } from "matrix-js-sdk/src/@types/event";
import { LocalNotificationSettings } from "matrix-js-sdk/src/@types/local_notifications"; import { LocalNotificationSettings } from "matrix-js-sdk/src/@types/local_notifications";
import { ReceiptType } from "matrix-js-sdk/src/@types/read_receipts"; 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"; import SettingsStore from "../settings/SettingsStore";
@ -59,27 +59,57 @@ export function localNotificationsAreSilenced(cli: MatrixClient): boolean {
return event?.getContent<LocalNotificationSettings>()?.is_silenced ?? false; 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) { if (room.getUnreadNotificationCount() > 0) {
const roomEvents = room.getLiveTimeline().getEvents(); const promise = clearRoomNotification(room, client);
const lastThreadEvents = room.lastThread?.events; promises.push(promise);
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);
}
} }
return promises; return promises;

View file

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

View file

@ -0,0 +1,135 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`RoomGeneralContextMenu renders an empty context menu for archived rooms 1`] = `
<div>
<div
class="mx_ContextualMenu_wrapper"
style="top: 1px; left: 1px;"
>
<div
class="mx_ContextualMenu_background"
/>
<div
class="mx_ContextualMenu mx_ContextualMenu_withChevron_left"
role="menu"
>
<div
class="mx_ContextualMenu_chevron_left"
/>
<div
class="mx_IconizedContextMenu mx_RoomGeneralContextMenu mx_IconizedContextMenu_compact"
>
<div
class="mx_IconizedContextMenu_optionList mx_IconizedContextMenu_optionList_notFirst"
>
<div
aria-checked="false"
aria-label="Mark as read"
class="mx_AccessibleButton mx_IconizedContextMenu_item"
role="menuitemcheckbox"
tabindex="0"
>
<span
class="mx_IconizedContextMenu_icon mx_RoomGeneralContextMenu_iconMarkAsRead"
/>
<span
class="mx_IconizedContextMenu_label"
>
Mark as read
</span>
<span
class="mx_IconizedContextMenu_icon mx_IconizedContextMenu_unchecked"
/>
</div>
</div>
<div
class="mx_IconizedContextMenu_optionList mx_IconizedContextMenu_optionList_notFirst mx_IconizedContextMenu_optionList_red"
>
<div
aria-label="Forget Room"
class="mx_AccessibleButton mx_IconizedContextMenu_option_red mx_IconizedContextMenu_item"
role="menuitem"
tabindex="-1"
>
<span
class="mx_IconizedContextMenu_icon mx_RoomGeneralContextMenu_iconSignOut"
/>
<span
class="mx_IconizedContextMenu_label"
>
Forget Room
</span>
</div>
</div>
</div>
</div>
</div>
</div>
`;
exports[`RoomGeneralContextMenu renders the default context menu 1`] = `
<div>
<div
class="mx_ContextualMenu_wrapper"
style="top: 1px; left: 1px;"
>
<div
class="mx_ContextualMenu_background"
/>
<div
class="mx_ContextualMenu mx_ContextualMenu_withChevron_left"
role="menu"
>
<div
class="mx_ContextualMenu_chevron_left"
/>
<div
class="mx_IconizedContextMenu mx_RoomGeneralContextMenu mx_IconizedContextMenu_compact"
>
<div
class="mx_IconizedContextMenu_optionList mx_IconizedContextMenu_optionList_notFirst"
>
<div
aria-checked="false"
aria-label="Mark as read"
class="mx_AccessibleButton mx_IconizedContextMenu_item"
role="menuitemcheckbox"
tabindex="0"
>
<span
class="mx_IconizedContextMenu_icon mx_RoomGeneralContextMenu_iconMarkAsRead"
/>
<span
class="mx_IconizedContextMenu_label"
>
Mark as read
</span>
<span
class="mx_IconizedContextMenu_icon mx_IconizedContextMenu_unchecked"
/>
</div>
</div>
<div
class="mx_IconizedContextMenu_optionList mx_IconizedContextMenu_optionList_notFirst mx_IconizedContextMenu_optionList_red"
>
<div
aria-label="Forget Room"
class="mx_AccessibleButton mx_IconizedContextMenu_option_red mx_IconizedContextMenu_item"
role="menuitem"
tabindex="-1"
>
<span
class="mx_IconizedContextMenu_icon mx_RoomGeneralContextMenu_iconSignOut"
/>
<span
class="mx_IconizedContextMenu_label"
>
Forget Room
</span>
</div>
</div>
</div>
</div>
</div>
</div>
`;

View file

@ -467,7 +467,7 @@ describe("<Notifications />", () => {
expect(mockClient.sendReadReceipt).toHaveBeenCalled(); expect(mockClient.sendReadReceipt).toHaveBeenCalled();
await waitFor(() => { await waitFor(() => {
expect(clearNotificationEl.className).not.toContain("mx_AccessibleButton_disabled"); expect(clearNotificationEl).not.toBeInTheDocument();
}); });
}); });
}); });

View file

@ -26,6 +26,7 @@ import {
createLocalNotificationSettingsIfNeeded, createLocalNotificationSettingsIfNeeded,
deviceNotificationSettingsKeys, deviceNotificationSettingsKeys,
clearAllNotifications, clearAllNotifications,
clearRoomNotification,
} from "../../src/utils/notifications"; } from "../../src/utils/notifications";
import SettingsStore from "../../src/settings/SettingsStore"; import SettingsStore from "../../src/settings/SettingsStore";
import { getMockClientWithEventEmitter } from "../test-utils/client"; import { getMockClientWithEventEmitter } from "../test-utils/client";
@ -107,10 +108,44 @@ describe("notifications", () => {
}); });
}); });
describe("clearRoomNotification", () => {
let client: MatrixClient;
let room: Room;
let sendReadReceiptSpy: jest.SpyInstance;
const ROOM_ID = "123";
const USER_ID = "@bob:example.org";
beforeEach(() => {
stubClient();
client = mocked(MatrixClientPeg.get());
room = new Room(ROOM_ID, client, USER_ID);
sendReadReceiptSpy = jest.spyOn(client, "sendReadReceipt").mockResolvedValue({});
jest.spyOn(client, "getRooms").mockReturnValue([room]);
jest.spyOn(SettingsStore, "getValue").mockImplementation((name) => {
return name === "sendReadReceipts";
});
});
it("sends a request even if everything has been read", () => {
clearRoomNotification(room, client);
expect(sendReadReceiptSpy).not.toBeCalled();
});
it("marks the room as read even if the receipt failed", async () => {
room.setUnreadNotificationCount(NotificationCountType.Total, 5);
sendReadReceiptSpy = jest.spyOn(client, "sendReadReceipt").mockReset().mockRejectedValue({});
try {
await clearRoomNotification(room, client);
} finally {
expect(room.getUnreadNotificationCount(NotificationCountType.Total)).toBe(0);
}
});
});
describe("clearAllNotifications", () => { describe("clearAllNotifications", () => {
let client: MatrixClient; let client: MatrixClient;
let room: Room; let room: Room;
let sendReadReceiptSpy; let sendReadReceiptSpy: jest.SpyInstance;
const ROOM_ID = "123"; const ROOM_ID = "123";
const USER_ID = "@bob:example.org"; const USER_ID = "@bob:example.org";