1
0
mirror of https://github.com/matrix-org/matrix-react-sdk.git synced 2025-07-31 13:44:28 +03:00

Use Intl to localise dates and times (#11422)

* Use Intl to generate better internationalised date formats

* Get `Yesterday` and `Today` from Intl also

* Correct capitalisation blunder

* Fix formatTime include weekday

* Iterate

* Fix tests

* use jest setSystemTime

* Discard changes to cypress/e2e/settings/general-user-settings-tab.spec.ts

* Discard changes to res/css/_components.pcss

* Discard changes to res/css/views/elements/_LanguageDropdown.pcss

* Discard changes to src/components/views/elements/LanguageDropdown.tsx

* Add docs & tests for getDaysArray & getMonthsArray

* Discard changes to test/components/structures/__snapshots__/MatrixChat-test.tsx.snap

* Consolidate consts

* Improve testing & documentation

* Update snapshot

* Apply suggestions from code review

Co-authored-by: Richard van der Hoff <1389908+richvdh@users.noreply.github.com>

* Iterate

* Clarify comments

* Update src/DateUtils.ts

Co-authored-by: Richard van der Hoff <1389908+richvdh@users.noreply.github.com>

* Specify hourCycle

* Discard changes to test/components/views/settings/devices/DeviceDetails-test.tsx

* Update comments

---------

Co-authored-by: Richard van der Hoff <1389908+richvdh@users.noreply.github.com>
This commit is contained in:
Michael Telatynski
2023-08-21 20:38:59 +01:00
committed by GitHub
parent d4571aef68
commit 3c52ba0c92
21 changed files with 446 additions and 193 deletions

View File

@ -96,6 +96,7 @@ const mockEvents = (room: Room, count = 2): MatrixEvent[] => {
type: EventType.RoomMessage,
sender: "userId",
content: createMessageEventContent("`Event${index}`"),
origin_server_ts: index,
}),
);
}
@ -447,7 +448,7 @@ describe("TimelinePanel", () => {
render(<TimelinePanel {...props} />);
const event = new MatrixEvent({ type: RoomEvent.Timeline });
const event = new MatrixEvent({ type: RoomEvent.Timeline, origin_server_ts: 0 });
const data = { timeline: otherTimeline, liveEvent: true };
client.emit(RoomEvent.Timeline, event, room, false, false, data);
@ -463,7 +464,7 @@ describe("TimelinePanel", () => {
render(<TimelinePanel {...props} />);
const event = new MatrixEvent({ type: RoomEvent.Timeline });
const event = new MatrixEvent({ type: RoomEvent.Timeline, origin_server_ts: 0 });
const data = { timeline: props.timelineSet.getLiveTimeline(), liveEvent: false };
client.emit(RoomEvent.Timeline, event, room, false, false, data);
@ -479,7 +480,7 @@ describe("TimelinePanel", () => {
render(<TimelinePanel {...props} />);
const event = new MatrixEvent({ type: RoomEvent.Timeline });
const event = new MatrixEvent({ type: RoomEvent.Timeline, origin_server_ts: 0 });
const data = { timeline: props.timelineSet.getLiveTimeline(), liveEvent: false };
const toStartOfTimeline = true;
client.emit(RoomEvent.Timeline, event, room, toStartOfTimeline, false, data);
@ -496,7 +497,7 @@ describe("TimelinePanel", () => {
render(<TimelinePanel {...props} />);
const event = new MatrixEvent({ type: RoomEvent.Timeline });
const event = new MatrixEvent({ type: RoomEvent.Timeline, origin_server_ts: 0 });
const data = { timeline: props.timelineSet.getLiveTimeline(), liveEvent: true };
client.emit(RoomEvent.Timeline, event, room, false, false, data);
@ -521,7 +522,7 @@ describe("TimelinePanel", () => {
await flushPromises();
const event = new MatrixEvent({ type: RoomEvent.Timeline });
const event = new MatrixEvent({ type: RoomEvent.Timeline, origin_server_ts: 0 });
const data = { timeline: props.timelineSet.getLiveTimeline(), liveEvent: true };
client.emit(RoomEvent.Timeline, event, room, false, false, data);
@ -539,11 +540,13 @@ describe("TimelinePanel", () => {
type: "m.call.invite",
room_id: virtualRoom.roomId,
event_id: `virtualCallEvent1`,
origin_server_ts: 0,
});
const virtualCallMetaEvent = new MatrixEvent({
type: "org.matrix.call.sdp_stream_metadata_changed",
room_id: virtualRoom.roomId,
event_id: `virtualCallEvent2`,
origin_server_ts: 0,
});
const virtualEvents = [virtualCallInvite, ...mockEvents(virtualRoom), virtualCallMetaEvent];
const { timelineSet: overlayTimelineSet } = getProps(virtualRoom, virtualEvents);
@ -819,6 +822,7 @@ describe("TimelinePanel", () => {
type: EventType.RoomMessage,
sender: "userId",
content: createMessageEventContent("ReplyEvent1"),
origin_server_ts: 0,
});
reply2 = new MatrixEvent({
@ -827,6 +831,7 @@ describe("TimelinePanel", () => {
type: EventType.RoomMessage,
sender: "userId",
content: createMessageEventContent("ReplyEvent2"),
origin_server_ts: 0,
});
root = new MatrixEvent({
@ -835,6 +840,7 @@ describe("TimelinePanel", () => {
type: EventType.RoomMessage,
sender: "userId",
content: createMessageEventContent("RootEvent"),
origin_server_ts: 0,
});
const eventMap: { [key: string]: MatrixEvent } = {

View File

@ -39,7 +39,7 @@ exports[`MessagePanel should handle lots of membership events quickly 1`] = `
data-testid="__testid__"
>
<div
aria-label="Thu, Jan 1 1970"
aria-label="Thu, Jan 1, 1970"
class="mx_DateSeparator"
role="separator"
>
@ -53,7 +53,7 @@ exports[`MessagePanel should handle lots of membership events quickly 1`] = `
aria-hidden="true"
class="mx_DateSeparator_dateHeading"
>
Thu, Jan 1 1970
Thu, Jan 1, 1970
</h2>
</div>
<hr

View File

@ -51,7 +51,7 @@ describe("<MessageEditHistory />", () => {
new MatrixEvent({
type: EventType.RoomMessage,
room_id: roomId,
origin_server_ts: e.ts,
origin_server_ts: e.ts ?? 0,
content: {
body: e.msg,
},

View File

@ -45,7 +45,7 @@ exports[`<MessageEditHistory /> should match the snapshot 1`] = `
>
<li>
<div
aria-label="Thu, Jan 1 1970"
aria-label="Thu, Jan 1, 1970"
class="mx_DateSeparator"
role="separator"
>
@ -59,7 +59,7 @@ exports[`<MessageEditHistory /> should match the snapshot 1`] = `
aria-hidden="true"
class="mx_DateSeparator_dateHeading"
>
Thu, Jan 1 1970
Thu, Jan 1, 1970
</h2>
</div>
<hr
@ -161,7 +161,7 @@ exports[`<MessageEditHistory /> should support events with 1`] = `
>
<li>
<div
aria-label=", NaN NaN"
aria-label="Thu, Jan 1, 1970"
class="mx_DateSeparator"
role="separator"
>
@ -175,7 +175,7 @@ exports[`<MessageEditHistory /> should support events with 1`] = `
aria-hidden="true"
class="mx_DateSeparator_dateHeading"
>
, NaN NaN
Thu, Jan 1, 1970
</h2>
</div>
<hr
@ -193,7 +193,7 @@ exports[`<MessageEditHistory /> should support events with 1`] = `
<span
class="mx_MessageTimestamp"
>
NaN:NaN
00:00
</span>
<div
class="mx_EventTile_content"
@ -236,7 +236,7 @@ exports[`<MessageEditHistory /> should support events with 1`] = `
<span
class="mx_MessageTimestamp"
>
NaN:NaN
00:00
</span>
<div
class="mx_EventTile_content"
@ -290,7 +290,7 @@ exports[`<MessageEditHistory /> should support events with 1`] = `
<span
class="mx_MessageTimestamp"
>
NaN:NaN
00:00
</span>
<div
class="mx_EventTile_content"

View File

@ -60,11 +60,11 @@ describe("DateSeparator", () => {
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"],
["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"],
["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(),

View File

@ -3,7 +3,7 @@
exports[`DateSeparator renders the date separator correctly 1`] = `
<DocumentFragment>
<div
aria-label="Today"
aria-label="today"
class="mx_DateSeparator"
role="separator"
>
@ -17,7 +17,7 @@ exports[`DateSeparator renders the date separator correctly 1`] = `
aria-hidden="true"
class="mx_DateSeparator_dateHeading"
>
Today
today
</h2>
</div>
<hr
@ -30,7 +30,7 @@ exports[`DateSeparator renders the date separator correctly 1`] = `
exports[`DateSeparator when feature_jump_to_date is enabled renders the date separator correctly 1`] = `
<DocumentFragment>
<div
aria-label="Fri, Dec 17 2021"
aria-label="Fri, Dec 17, 2021"
class="mx_DateSeparator"
role="separator"
>
@ -50,7 +50,7 @@ exports[`DateSeparator when feature_jump_to_date is enabled renders the date sep
aria-hidden="true"
class="mx_DateSeparator_dateHeading"
>
Fri, Dec 17 2021
Fri, Dec 17, 2021
</h2>
<div
class="mx_DateSeparator_chevron"

View File

@ -93,7 +93,7 @@ describe("SearchResultTile", () => {
room_id: ROOM_ID,
content: { body: `Message #${i}` },
event_id: `$${i}:server`,
origin_server_ts: undefined,
origin_server_ts: i,
}),
),
});

View File

@ -51,7 +51,7 @@ exports[`<PinnedEventTile /> should render pinned event 1`] = `
<span
class="mx_MessageTimestamp mx_PinnedEventTile_timestamp"
>
Thu, Jan 1 1970 00:00:00
Thu, Jan 1, 1970, 00:00
</span>
<div
class="mx_AccessibleButton mx_AccessibleButton_hasKind mx_AccessibleButton_kind_link"

View File

@ -103,6 +103,7 @@ export const makeBeaconEvent = (
room_id: roomId,
sender,
content: ContentHelpers.makeBeaconContent(geoUri, timestamp, beaconInfoId, description),
origin_server_ts: 0,
});
};

View File

@ -27,6 +27,7 @@ export const makeLegacyLocationEvent = (geoUri: string): MatrixEvent => {
msgtype: "m.location",
geo_uri: geoUri,
},
origin_server_ts: 0,
});
};
@ -41,6 +42,7 @@ export const makeLocationEvent = (geoUri: string, assetType?: LocationAssetType)
"Human-readable label",
assetType,
),
origin_server_ts: 0,
});
};

View File

@ -538,6 +538,7 @@ export function mkMessage({
}
const message = msg ?? "Random->" + Math.random();
const event: MakeEventProps = {
ts: 0,
...opts,
type: "m.room.message",
content: {

View File

@ -23,8 +23,224 @@ import {
formatTimeLeft,
formatPreciseDuration,
formatLocalDateShort,
getDaysArray,
getMonthsArray,
formatFullDateNoDayNoTime,
formatTime,
formatFullTime,
formatFullDate,
formatFullDateNoTime,
formatDate,
HOUR_MS,
MINUTE_MS,
DAY_MS,
} from "../../src/DateUtils";
import { REPEATABLE_DATE, mockIntlDateTimeFormat, unmockIntlDateTimeFormat } from "../test-utils";
import * as languageHandler from "../../src/languageHandler";
describe("getDaysArray", () => {
it("should return Sunday-Saturday in long mode", () => {
expect(getDaysArray("long")).toMatchInlineSnapshot(`
[
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
]
`);
});
it("should return Sun-Sat in short mode", () => {
expect(getDaysArray("short")).toMatchInlineSnapshot(`
[
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat",
]
`);
});
it("should return S-S in narrow mode", () => {
expect(getDaysArray("narrow")).toMatchInlineSnapshot(`
[
"S",
"M",
"T",
"W",
"T",
"F",
"S",
]
`);
});
});
describe("getMonthsArray", () => {
it("should return January-December in long mode", () => {
expect(getMonthsArray("long")).toMatchInlineSnapshot(`
[
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
]
`);
});
it("should return Jan-Dec in short mode", () => {
expect(getMonthsArray("short")).toMatchInlineSnapshot(`
[
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
]
`);
});
it("should return J-D in narrow mode", () => {
expect(getMonthsArray("narrow")).toMatchInlineSnapshot(`
[
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D",
]
`);
});
it("should return 1-12 in numeric mode", () => {
expect(getMonthsArray("numeric")).toMatchInlineSnapshot(`
[
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
]
`);
});
it("should return 01-12 in 2-digit mode", () => {
expect(getMonthsArray("2-digit")).toMatchInlineSnapshot(`
[
"01",
"02",
"03",
"04",
"05",
"06",
"07",
"08",
"09",
"10",
"11",
"12",
]
`);
});
});
describe("formatDate", () => {
beforeAll(() => {
jest.useFakeTimers();
jest.setSystemTime(REPEATABLE_DATE);
});
afterAll(() => {
jest.setSystemTime(jest.getRealSystemTime());
jest.useRealTimers();
});
it("should return time string if date is within same day", () => {
const date = new Date(REPEATABLE_DATE.getTime() + 2 * HOUR_MS + 12 * MINUTE_MS);
expect(formatDate(date, false, "en-GB")).toMatchInlineSnapshot(`"19:10"`);
});
it("should return time string with weekday if date is within last 6 days", () => {
const date = new Date(REPEATABLE_DATE.getTime() - 6 * DAY_MS + 2 * HOUR_MS + 12 * MINUTE_MS);
expect(formatDate(date, false, "en-GB")).toMatchInlineSnapshot(`"Fri 19:10"`);
});
it("should return time & date string without year if it is within the same year", () => {
const date = new Date(REPEATABLE_DATE.getTime() - 66 * DAY_MS + 2 * HOUR_MS + 12 * MINUTE_MS);
expect(formatDate(date, false, "en-GB")).toMatchInlineSnapshot(`"Mon, 12 Sept, 19:10"`);
});
it("should return full time & date string otherwise", () => {
const date = new Date(REPEATABLE_DATE.getTime() - 666 * DAY_MS + 2 * HOUR_MS + 12 * MINUTE_MS);
expect(formatDate(date, false, "en-GB")).toMatchInlineSnapshot(`"Wed, 20 Jan 2021, 19:10"`);
});
});
describe("formatFullDateNoTime", () => {
it("should match given locale en-GB", () => {
expect(formatFullDateNoTime(REPEATABLE_DATE, "en-GB")).toMatchInlineSnapshot(`"Thu, 17 Nov 2022"`);
});
});
describe("formatFullDate", () => {
it("correctly formats with seconds", () => {
expect(formatFullDate(REPEATABLE_DATE, true, true, "en-GB")).toMatchInlineSnapshot(
`"Thu, 17 Nov 2022, 4:58:32 pm"`,
);
});
it("correctly formats without seconds", () => {
expect(formatFullDate(REPEATABLE_DATE, false, false, "en-GB")).toMatchInlineSnapshot(
`"Thu, 17 Nov 2022, 16:58"`,
);
});
});
describe("formatFullTime", () => {
it("correctly formats 12 hour mode", () => {
expect(formatFullTime(REPEATABLE_DATE, true, "en-GB")).toMatchInlineSnapshot(`"4:58:32 pm"`);
});
it("correctly formats 24 hour mode", () => {
expect(formatFullTime(REPEATABLE_DATE, false, "en-GB")).toMatchInlineSnapshot(`"16:58:32"`);
});
});
describe("formatTime", () => {
it("correctly formats 12 hour mode", () => {
expect(formatTime(REPEATABLE_DATE, true, "en-GB")).toMatchInlineSnapshot(`"4:58 pm"`);
});
it("correctly formats 24 hour mode", () => {
expect(formatTime(REPEATABLE_DATE, false, "en-GB")).toMatchInlineSnapshot(`"16:58"`);
});
});
describe("formatSeconds", () => {
it("correctly formats time with hours", () => {
@ -43,16 +259,15 @@ describe("formatSeconds", () => {
});
describe("formatRelativeTime", () => {
let dateSpy: jest.SpyInstance<number, []>;
beforeAll(() => {
dateSpy = jest
.spyOn(global.Date, "now")
// Tuesday, 2 November 2021 11:18:03 UTC
.mockImplementation(() => 1635851883000);
jest.useFakeTimers();
// Tuesday, 2 November 2021 11:18:03 UTC
jest.setSystemTime(1635851883000);
});
afterAll(() => {
dateSpy.mockRestore();
jest.setSystemTime(jest.getRealSystemTime());
jest.useRealTimers();
});
it("returns hour format for events created in the same day", () => {
@ -71,7 +286,7 @@ describe("formatRelativeTime", () => {
const date = new Date(2021, 10, 2, 11, 1, 23, 0);
expect(formatRelativeTime(date)).toBe("11:01");
expect(formatRelativeTime(date, false)).toBe("11:01");
expect(formatRelativeTime(date, true)).toBe("11:01AM");
expect(formatRelativeTime(date, true)).toBe("11:01 AM");
});
it("returns month and day for events created in the current year", () => {
@ -134,6 +349,12 @@ describe("formatFullDateNoDayISO", () => {
});
});
describe("formatFullDateNoDayNoTime", () => {
it("should return a date formatted for en-GB locale", () => {
expect(formatFullDateNoDayNoTime(REPEATABLE_DATE, "en-GB")).toMatchInlineSnapshot(`"17/11/2022"`);
});
});
describe("formatDateForInput", () => {
it.each([["1993-11-01"], ["1066-10-14"], ["0571-04-22"], ["0062-02-05"]])(
"should format %s",
@ -162,15 +383,18 @@ describe("formatLocalDateShort()", () => {
});
const timestamp = new Date("Fri Dec 17 2021 09:09:00 GMT+0100 (Central European Standard Time)").getTime();
it("formats date correctly by locale", () => {
const locale = jest.spyOn(languageHandler, "getUserLanguage");
mockIntlDateTimeFormat();
// format is DD/MM/YY
mockIntlDateTimeFormat("en-UK");
locale.mockReturnValue("en-GB");
expect(formatLocalDateShort(timestamp)).toEqual("17/12/21");
// US date format is MM/DD/YY
mockIntlDateTimeFormat("en-US");
locale.mockReturnValue("en-US");
expect(formatLocalDateShort(timestamp)).toEqual("12/17/21");
mockIntlDateTimeFormat("de-DE");
locale.mockReturnValue("de-DE");
expect(formatLocalDateShort(timestamp)).toEqual("17.12.21");
});
});

View File

@ -49,8 +49,8 @@ describe("PlainTextExport", () => {
});
it.each([
[24, false, "Fri, Apr 16 2021 17:20:00 - @alice:example.com: Hello, world!\n"],
[12, true, "Fri, Apr 16 2021 5:20:00PM - @alice:example.com: Hello, world!\n"],
[24, false, "Fri, Apr 16, 2021, 17:20:00 - @alice:example.com: Hello, world!\n"],
[12, true, "Fri, Apr 16, 2021, 5:20:00 PM - @alice:example.com: Hello, world!\n"],
])("should return text with %i hr time format", async (hour: number, setting: boolean, expectedMessage: string) => {
jest.spyOn(SettingsStore, "getValue").mockImplementation((settingName: string) =>
settingName === "showTwelveHourTimestamps" ? setting : undefined,

File diff suppressed because one or more lines are too long