Refactor DateSeparator using MVVM and move to shared-components (#32482)

* Refactor DateSeparator using MVVM and move to shared-components

* Add a few more stories, tests and screenshots

* Use the shared component and viewmodel in element-web

* Renaming custom content property an updating snapshots

* Fix lint errors and update snapshot after merge

* Change lifecycle handling for DateSeparatoreViewModel in components where manual handling is preferrable over wrapper component.

* Move context menu from viewmodel to shared components - step 1

* Create a jump to date picker component in shared components

* Add tests for coverage and fix layout issues and roving indexes

* Make element-web use the new component

* Simplify context menu and adjusting tests

* The HTMLExport now render shared components and need a I18nContext.Provider

* Updating unit tests for context menu

* Changed to {translate: _t} to let scripts pick up translations

* Fix lint issue and updating screenshots after merge

* Update snaps for element web components

* Renaming MVVM view components with suffix View.

* Fixing problem with input date calendar icon and system dark theme

* Changed the rendering of the menu and added a separate button component

* Handle input control with useRef in onKeyDown

* Updating DateSeparator snapshots on unit tests

* Updating layout after compound Menu got a className property

* Move files to new subfolder after merge

* Updated snapshot after merge

* Updating lock file

* Updates to styling from PR review

* Updates to focus/blur functionality

* Fixed tabbing and export documentation to stories

* Updated snapshots

---------

Co-authored-by: Zack <zazi21@student.bth.se>
This commit is contained in:
rbondesson
2026-03-02 12:18:51 +00:00
committed by GitHub
co-authored by Zack
parent 76cbfb1ae4
commit 11030ae68d
48 changed files with 1819 additions and 1048 deletions
@@ -47,11 +47,11 @@ exports[`MessagePanel should handle lots of membership events quickly 1`] = `
role="none"
/>
<div
class="mx_DateSeparator_dateContent"
class="_flex_4dswl_9 _content_5dcky_8"
style="--mx-flex-display: flex; --mx-flex-direction: row; --mx-flex-align: start; --mx-flex-justify: start; --mx-flex-gap: 0; --mx-flex-wrap: nowrap;"
>
<h2
aria-hidden="true"
class="mx_DateSeparator_dateHeading"
>
Thu, Jan 1, 1970
</h2>
@@ -49,11 +49,11 @@ exports[`<MessageEditHistory /> should match the snapshot 1`] = `
role="none"
/>
<div
class="mx_DateSeparator_dateContent"
class="_flex_4dswl_9 _content_5dcky_8"
style="--mx-flex-display: flex; --mx-flex-direction: row; --mx-flex-align: start; --mx-flex-justify: start; --mx-flex-gap: 0; --mx-flex-wrap: nowrap;"
>
<h2
aria-hidden="true"
class="mx_DateSeparator_dateHeading"
>
Thu, Jan 1, 1970
</h2>
@@ -180,11 +180,11 @@ exports[`<MessageEditHistory /> should support events with 1`] = `
role="none"
/>
<div
class="mx_DateSeparator_dateContent"
class="_flex_4dswl_9 _content_5dcky_8"
style="--mx-flex-display: flex; --mx-flex-direction: row; --mx-flex-align: start; --mx-flex-justify: start; --mx-flex-gap: 0; --mx-flex-wrap: nowrap;"
>
<h2
aria-hidden="true"
class="mx_DateSeparator_dateHeading"
>
Thu, Jan 1, 1970
</h2>
@@ -1,322 +0,0 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2021 The Matrix.org Foundation C.I.C.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import React from "react";
import { mocked } from "jest-mock";
import { fireEvent, render, screen, waitFor } from "jest-matrix-react";
import { type TimestampToEventResponse, ConnectionError, HTTPError, MatrixError } from "matrix-js-sdk/src/matrix";
import dispatcher from "../../../../../src/dispatcher/dispatcher";
import { Action } from "../../../../../src/dispatcher/actions";
import { type ViewRoomPayload } from "../../../../../src/dispatcher/payloads/ViewRoomPayload";
import { formatFullDateNoTime } from "../../../../../src/DateUtils";
import SettingsStore from "../../../../../src/settings/SettingsStore";
import { UIFeature } from "../../../../../src/settings/UIFeature";
import MatrixClientContext from "../../../../../src/contexts/MatrixClientContext";
import {
clearAllModals,
flushPromisesWithFakeTimers,
getMockClientWithEventEmitter,
waitEnoughCyclesForModal,
} from "../../../../test-utils";
import DateSeparator from "../../../../../src/components/views/messages/DateSeparator";
import { ScopedRoomContextProvider } from "../../../../../src/contexts/ScopedRoomContext";
import RoomContext, { type RoomContextType } from "../../../../../src/contexts/RoomContext";
jest.mock("../../../../../src/settings/SettingsStore");
describe("DateSeparator", () => {
const HOUR_MS = 3600000;
const DAY_MS = HOUR_MS * 24;
// Friday Dec 17 2021, 9:09am
const nowDate = new Date("2021-12-17T08:09:00.000Z");
const roomId = "!unused:example.org";
const defaultProps = {
ts: nowDate.getTime(),
roomId,
};
const mockRoomViewStore = {
getRoomId: jest.fn().mockReturnValue(roomId),
};
const defaultRoomContext = {
...RoomContext,
roomId,
roomViewStore: mockRoomViewStore,
} as unknown as RoomContextType;
const mockClient = getMockClientWithEventEmitter({
timestampToEvent: jest.fn(),
});
const getComponent = (props = {}) =>
render(
<MatrixClientContext.Provider value={mockClient}>
<ScopedRoomContextProvider {...defaultRoomContext}>
<DateSeparator {...defaultProps} {...props} />
</ScopedRoomContextProvider>
</MatrixClientContext.Provider>,
);
type TestCase = [string, number, string];
const testCases: TestCase[] = [
["the exact same moment", nowDate.getTime(), "today"],
["same day as current day", nowDate.getTime() - HOUR_MS, "today"],
["day before the current day", nowDate.getTime() - HOUR_MS * 12, "yesterday"],
["2 days ago", nowDate.getTime() - DAY_MS * 2, "Wednesday"],
["144 hours ago", nowDate.getTime() - HOUR_MS * 144, "Sat, Dec 11, 2021"],
[
"6 days ago, but less than 144h",
new Date("Saturday Dec 11 2021 23:59:00 GMT+0100 (Central European Standard Time)").getTime(),
"Saturday",
],
];
beforeEach(() => {
// Set a consistent fake time here so the test is always consistent
jest.useFakeTimers();
jest.setSystemTime(nowDate.getTime());
(SettingsStore.getValue as jest.Mock) = jest.fn((arg) => {
if (arg === UIFeature.TimelineEnableRelativeDates) {
return true;
}
});
mockRoomViewStore.getRoomId.mockReturnValue(roomId);
});
afterAll(() => {
jest.useRealTimers();
});
it("renders the date separator correctly", () => {
const { asFragment } = getComponent();
expect(asFragment()).toMatchSnapshot();
expect(SettingsStore.getValue).toHaveBeenCalledWith(UIFeature.TimelineEnableRelativeDates);
});
it.each(testCases)("formats date correctly when current time is %s", (_d, ts, result) => {
expect(getComponent({ ts, forExport: false }).container.textContent).toEqual(result);
});
it("renders invalid date separator correctly", () => {
const ts = new Date(-8640000000000004).getTime();
const { asFragment } = getComponent({ ts });
expect(asFragment()).toMatchSnapshot();
});
describe("when forExport is true", () => {
it.each(testCases)("formats date in full when current time is %s", (_d, ts) => {
expect(getComponent({ ts, forExport: true }).container.textContent).toEqual(
formatFullDateNoTime(new Date(ts)),
);
});
});
describe("when Settings.TimelineEnableRelativeDates is falsy", () => {
beforeEach(() => {
(SettingsStore.getValue as jest.Mock) = jest.fn((arg) => {
if (arg === UIFeature.TimelineEnableRelativeDates) {
return false;
}
});
});
it.each(testCases)("formats date in full when current time is %s", (_d, ts) => {
expect(getComponent({ ts, forExport: false }).container.textContent).toEqual(
formatFullDateNoTime(new Date(ts)),
);
});
});
describe("when feature_jump_to_date is enabled", () => {
beforeEach(() => {
jest.clearAllMocks();
mocked(SettingsStore).getValue.mockImplementation((arg): any => {
if (arg === "feature_jump_to_date") {
return true;
}
});
jest.spyOn(dispatcher, "dispatch").mockImplementation(() => {});
});
afterEach(async () => {
await clearAllModals();
});
it("renders the date separator correctly", () => {
const { asFragment } = getComponent();
expect(asFragment()).toMatchSnapshot();
});
[
{
timeDescriptor: "last week",
jumpButtonTestId: "jump-to-date-last-week",
},
{
timeDescriptor: "last month",
jumpButtonTestId: "jump-to-date-last-month",
},
{
timeDescriptor: "the beginning",
jumpButtonTestId: "jump-to-date-beginning",
},
].forEach((testCase) => {
it(`can jump to ${testCase.timeDescriptor}`, async () => {
// Render the component
getComponent();
// Open the jump to date context menu
fireEvent.click(screen.getByTestId("jump-to-date-separator-button"));
// Jump to "x"
const returnedDate = new Date();
// Just an arbitrary date before "now"
returnedDate.setDate(nowDate.getDate() - 100);
const returnedEventId = "$abc";
mockClient.timestampToEvent.mockResolvedValue({
event_id: returnedEventId,
origin_server_ts: returnedDate.getTime(),
} satisfies TimestampToEventResponse);
const jumpToXButton = await screen.findByTestId(testCase.jumpButtonTestId);
fireEvent.click(jumpToXButton);
// Flush out the dispatcher which uses `window.setTimeout(...)` since we're
// using `jest.useFakeTimers()` in these tests.
await flushPromisesWithFakeTimers();
// Ensure that we're jumping to the event at the given date
expect(dispatcher.dispatch).toHaveBeenCalledWith({
action: Action.ViewRoom,
event_id: returnedEventId,
highlighted: true,
room_id: roomId,
metricsTrigger: undefined,
} satisfies ViewRoomPayload);
});
});
it("should not jump to date if we already switched to another room", async () => {
// Render the component
getComponent();
// Open the jump to date context menu
fireEvent.click(screen.getByTestId("jump-to-date-separator-button"));
// Mimic the outcome of switching rooms while waiting for the jump to date
// request to finish. Imagine that we started jumping to "last week", the
// network request is taking a while, so we got bored, switched rooms; we
// shouldn't jump back to the previous room after the network request
// happens to finish later.
mockRoomViewStore.getRoomId.mockReturnValue("!some-other-room");
// Jump to "last week"
mockClient.timestampToEvent.mockResolvedValue({
event_id: "$abc",
origin_server_ts: 0,
});
const jumpToLastWeekButton = await screen.findByTestId("jump-to-date-last-week");
fireEvent.click(jumpToLastWeekButton);
// Flush out the dispatcher which uses `window.setTimeout(...)` since we're
// using `jest.useFakeTimers()` in these tests.
await flushPromisesWithFakeTimers();
// We should not see any room switching going on (`Action.ViewRoom`)
expect(dispatcher.dispatch).not.toHaveBeenCalled();
});
it("should not show jump to date error if we already switched to another room", async () => {
// Render the component
getComponent();
// Open the jump to date context menu
fireEvent.click(screen.getByTestId("jump-to-date-separator-button"));
// Mimic the outcome of switching rooms while waiting for the jump to date
// request to finish. Imagine that we started jumping to "last week", the
// network request is taking a while, so we got bored, switched rooms; we
// shouldn't jump back to the previous room after the network request
// happens to finish later.
mockRoomViewStore.getRoomId.mockReturnValue("!some-other-room");
// Try to jump to "last week" but we want an error to occur and ensure that
// we don't show an error dialog for it since we already switched away to
// another room and don't care about the outcome here anymore.
mockClient.timestampToEvent.mockRejectedValue(new Error("Fake error in test"));
const jumpToLastWeekButton = await screen.findByTestId("jump-to-date-last-week");
fireEvent.click(jumpToLastWeekButton);
// Wait the necessary time in order to see if any modal will appear
await waitEnoughCyclesForModal({
useFakeTimers: true,
});
// We should not see any error modal dialog
//
// We have to use `queryBy` so that it can return `null` for something that does not exist.
expect(screen.queryByTestId("jump-to-date-error-content")).not.toBeInTheDocument();
});
it("should show error dialog with submit debug logs option when non-networking error occurs", async () => {
// Render the component
getComponent();
// Open the jump to date context menu
fireEvent.click(screen.getByTestId("jump-to-date-separator-button"));
// Try to jump to "last week" but we want a non-network error to occur so it
// shows the "Submit debug logs" UI
mockClient.timestampToEvent.mockRejectedValue(new Error("Fake error in test"));
const jumpToLastWeekButton = await screen.findByTestId("jump-to-date-last-week");
fireEvent.click(jumpToLastWeekButton);
// Expect error to be shown. We have to wait for the UI to transition.
await expect(screen.findByTestId("jump-to-date-error-content")).resolves.toBeInTheDocument();
// Expect an option to submit debug logs to be shown when a non-network error occurs
await expect(
screen.findByTestId("jump-to-date-error-submit-debug-logs-button"),
).resolves.toBeInTheDocument();
});
[
new ConnectionError("Fake connection error in test"),
new HTTPError("Fake http error in test", 418),
new MatrixError(
{ errcode: "M_FAKE_ERROR_CODE", error: "Some fake error occured" },
518,
"https://fake-url/",
),
].forEach((fakeError) => {
it(`should show error dialog without submit debug logs option when networking error (${fakeError.name}) occurs`, async () => {
// Try to jump to "last week" but we want a network error to occur
mockClient.timestampToEvent.mockRejectedValue(fakeError);
// Render the component
getComponent();
// Open the jump to date context menu
fireEvent.click(screen.getByTestId("jump-to-date-separator-button"));
const jumpToLastWeekButton = await screen.findByTestId("jump-to-date-last-week");
fireEvent.click(jumpToLastWeekButton);
// Expect error to be shown. We have to wait for the UI to transition.
await expect(screen.findByTestId("jump-to-date-error-content")).resolves.toBeInTheDocument();
// The submit debug logs option should *NOT* be shown for network errors.
//
// We have to use `queryBy` so that it can return `null` for something that does not exist.
await waitFor(() =>
expect(screen.queryByTestId("jump-to-date-error-submit-debug-logs-button")).not.toBeInTheDocument(),
);
});
});
});
});
@@ -1,33 +0,0 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2021 The Matrix.org Foundation C.I.C.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import React from "react";
import { render } from "jest-matrix-react";
import JumpToDatePicker from "../../../../../src/components/views/messages/JumpToDatePicker";
describe("JumpToDatePicker", () => {
const nowDate = new Date("2021-12-17T08:09:00.000Z");
beforeEach(() => {
// Set a stable fake time here so the test is always consistent
jest.useFakeTimers();
jest.setSystemTime(nowDate.getTime());
});
afterAll(() => {
jest.useRealTimers();
});
it("renders the date picker correctly", () => {
const { asFragment } = render(
<JumpToDatePicker ts={new Date("2020-07-04T05:55:00.000Z").getTime()} onDatePicked={() => {}} />,
);
expect(asFragment()).toMatchSnapshot();
});
});
@@ -1,103 +0,0 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`DateSeparator renders invalid date separator correctly 1`] = `
<DocumentFragment>
<div
aria-label="Invalid timestamp"
class="_flex_4dswl_9 mx_TimelineSeparator _timelineSeparator_yq5ye_8"
role="separator"
style="--mx-flex-display: flex; --mx-flex-direction: row; --mx-flex-align: center; --mx-flex-justify: start; --mx-flex-gap: 0; --mx-flex-wrap: nowrap;"
>
<hr
role="none"
/>
<div
class="mx_DateSeparator_dateContent"
>
<h2
aria-hidden="true"
class="mx_DateSeparator_dateHeading"
>
Invalid timestamp
</h2>
</div>
<hr
role="none"
/>
</div>
</DocumentFragment>
`;
exports[`DateSeparator renders the date separator correctly 1`] = `
<DocumentFragment>
<div
aria-label="today"
class="_flex_4dswl_9 mx_TimelineSeparator _timelineSeparator_yq5ye_8"
role="separator"
style="--mx-flex-display: flex; --mx-flex-direction: row; --mx-flex-align: center; --mx-flex-justify: start; --mx-flex-gap: 0; --mx-flex-wrap: nowrap;"
>
<hr
role="none"
/>
<div
class="mx_DateSeparator_dateContent"
>
<h2
aria-hidden="true"
class="mx_DateSeparator_dateHeading"
>
today
</h2>
</div>
<hr
role="none"
/>
</div>
</DocumentFragment>
`;
exports[`DateSeparator when feature_jump_to_date is enabled renders the date separator correctly 1`] = `
<DocumentFragment>
<div
aria-label="Fri, Dec 17, 2021"
class="_flex_4dswl_9 mx_TimelineSeparator _timelineSeparator_yq5ye_8"
role="separator"
style="--mx-flex-display: flex; --mx-flex-direction: row; --mx-flex-align: center; --mx-flex-justify: start; --mx-flex-gap: 0; --mx-flex-wrap: nowrap;"
>
<hr
role="none"
/>
<div
aria-expanded="false"
aria-haspopup="true"
aria-label="Jump to date"
class="mx_AccessibleButton mx_DateSeparator_jumpToDateMenu mx_DateSeparator_dateContent"
data-testid="jump-to-date-separator-button"
role="button"
tabindex="0"
>
<h2
aria-hidden="true"
class="mx_DateSeparator_dateHeading"
>
Fri, Dec 17, 2021
</h2>
<svg
class="mx_DateSeparator_chevron"
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M12 14.95q-.2 0-.375-.062a.9.9 0 0 1-.325-.213l-4.6-4.6a.95.95 0 0 1-.275-.7q0-.425.275-.7a.95.95 0 0 1 .7-.275q.425 0 .7.275l3.9 3.9 3.9-3.9a.95.95 0 0 1 .7-.275q.425 0 .7.275a.95.95 0 0 1 .275.7.95.95 0 0 1-.275.7l-4.6 4.6q-.15.15-.325.212a1.1 1.1 0 0 1-.375.063"
/>
</svg>
</div>
<hr
role="none"
/>
</div>
</DocumentFragment>
`;
@@ -1,41 +0,0 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`JumpToDatePicker renders the date picker correctly 1`] = `
<DocumentFragment>
<form
class="mx_JumpToDatePicker_form"
>
<span
class="mx_JumpToDatePicker_label"
>
Jump to date
</span>
<div
class="mx_Field mx_Field_input mx_JumpToDatePicker_datePicker"
>
<input
id="mx_Field_1"
label="Pick a date to jump to"
max="2021-12-17"
placeholder="Pick a date to jump to"
tabindex="-1"
type="date"
value="2020-07-04"
/>
<label
for="mx_Field_1"
>
Pick a date to jump to
</label>
</div>
<button
class="mx_AccessibleButton mx_JumpToDatePicker_submitButton mx_AccessibleButton_hasKind mx_AccessibleButton_kind_primary"
role="button"
tabindex="-1"
type="submit"
>
Go
</button>
</form>
</DocumentFragment>
`;
@@ -11,7 +11,6 @@ import {
formatRelativeTime,
formatDuration,
formatFullDateNoDayISO,
formatDateForInput,
formatTimeLeft,
formatPreciseDuration,
formatLocalDateShort,
@@ -351,15 +350,6 @@ describe("formatFullDateNoDayNoTime", () => {
});
});
describe("formatDateForInput", () => {
it.each([["1993-11-01"], ["1066-10-14"], ["0571-04-22"], ["0062-02-05"]])(
"should format %s",
(dateString: string) => {
expect(formatDateForInput(new Date(dateString))).toBe(dateString);
},
);
});
describe("formatTimeLeft", () => {
it.each([
[0, "0s left"],
File diff suppressed because one or more lines are too long