Take client creating functionality out of MatrixClientPeg (#34092)
* Take client creating functionality out of MatrixClientPeg Because all sorts of things import MatrixClientPeg and this means they pull in all manner of things related to creating a client, when all they need is to get the current one (and specifically it fixes the import cycle that means I can't add my test). * Remove fake indexeddb as it seems like the tests didn't actually see the fake indexeddb before (somehow) but now do, and are failing because they have that but no postmessage. It feels like the right solution is for these tests to not need indexeddb. * Don't mock a refresh token The tests don't mock out enough for the token refreshing setup to work, it wa somehow always ending up as null previously and now wasn't, at which point it broke, so just make it actually unset. * Move formatter instatiation to lazy rather than eagerly at parse time, as this apparently shifted one test to hit this import cycle instead. * Tests for room name generator
This commit is contained in:
@@ -16,32 +16,38 @@ import { jsxJoin } from "./ReactUtils";
|
||||
|
||||
export { formatBytes } from "@element-hq/web-shared-components";
|
||||
|
||||
const locale = getCurrentLanguage();
|
||||
let cachedFormatter: Intl.NumberFormat | undefined;
|
||||
let cachedCompactFormatter: Intl.NumberFormat | undefined;
|
||||
|
||||
// It's quite costly to instanciate `Intl.NumberFormat`, hence why we do not do
|
||||
// it in every function call
|
||||
const compactFormatter = new Intl.NumberFormat(locale, {
|
||||
notation: "compact",
|
||||
});
|
||||
const getCachedCompactFormatter = (): Intl.NumberFormat => {
|
||||
if (!cachedCompactFormatter)
|
||||
cachedCompactFormatter = new Intl.NumberFormat(getCurrentLanguage(), { notation: "compact" });
|
||||
return cachedCompactFormatter;
|
||||
};
|
||||
|
||||
/**
|
||||
* formats and rounds numbers to fit into ~3 characters, suitable for badge counts
|
||||
* e.g: 999, 10K, 99K, 1M, 10M, 99M, 1B, 10B, ...
|
||||
*/
|
||||
export function formatCount(count: number): string {
|
||||
return compactFormatter.format(count);
|
||||
return getCachedCompactFormatter().format(count);
|
||||
}
|
||||
|
||||
// It's quite costly to instanciate `Intl.NumberFormat`, hence why we do not do
|
||||
// it in every function call
|
||||
const formatter = new Intl.NumberFormat(locale);
|
||||
const getCachedFormatter = (): Intl.NumberFormat => {
|
||||
if (!cachedFormatter) cachedFormatter = new Intl.NumberFormat(getCurrentLanguage());
|
||||
return cachedFormatter;
|
||||
};
|
||||
|
||||
/**
|
||||
* Format a count showing the whole number but making it a bit more readable.
|
||||
* e.g: 1000 => 1,000
|
||||
*/
|
||||
export function formatCountLong(count: number): string {
|
||||
return formatter.format(count);
|
||||
return getCachedFormatter().format(count);
|
||||
}
|
||||
|
||||
export function getUserNameColorClass(userId: string): string {
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
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 { vi, describe, beforeEach, it, expect } from "vitest";
|
||||
import { type MatrixClient, RoomNameType } from "matrix-js-sdk/src/matrix";
|
||||
|
||||
import { createClientWithCreds } from "./createMatrixClient";
|
||||
|
||||
describe("createMatrixClient", () => {
|
||||
let client: MatrixClient;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("localStorage", {
|
||||
getItem: vi.fn().mockReturnValue(null),
|
||||
setItem: vi.fn(),
|
||||
removeItem: vi.fn(),
|
||||
});
|
||||
|
||||
client = createClientWithCreds({
|
||||
homeserverUrl: "https://test.dummy",
|
||||
userId: "@user:test.dummy",
|
||||
accessToken: "access_token",
|
||||
});
|
||||
});
|
||||
|
||||
describe("room name generator", () => {
|
||||
it("should return empty room for an empty room", () => {
|
||||
const roomName = client.roomNameGenerator?.("", {
|
||||
type: RoomNameType.EmptyRoom,
|
||||
});
|
||||
expect(roomName).toBe("Empty room");
|
||||
});
|
||||
|
||||
it("should include the old name for an empty room that used to have a name", () => {
|
||||
const roomName = client.roomNameGenerator?.("", {
|
||||
type: RoomNameType.EmptyRoom,
|
||||
oldName: "Old Room",
|
||||
});
|
||||
expect(roomName).toBe("Empty room (was Old Room)");
|
||||
});
|
||||
|
||||
it("should return null for an actual room name", () => {
|
||||
const roomName = client.roomNameGenerator?.("", {
|
||||
type: RoomNameType.Actual,
|
||||
name: "Some name",
|
||||
});
|
||||
expect(roomName).toBeNull();
|
||||
});
|
||||
|
||||
describe("generated room names", () => {
|
||||
it("should return empty room when there are no members", () => {
|
||||
const roomName = client.roomNameGenerator?.("", {
|
||||
type: RoomNameType.Generated,
|
||||
names: [],
|
||||
count: 0,
|
||||
});
|
||||
expect(roomName).toBe("Empty room");
|
||||
});
|
||||
|
||||
it("should return the single member name when there is only one other member", () => {
|
||||
const roomName = client.roomNameGenerator?.("", {
|
||||
type: RoomNameType.Generated,
|
||||
names: ["Alice"],
|
||||
count: 2,
|
||||
});
|
||||
expect(roomName).toBe("Alice");
|
||||
});
|
||||
|
||||
it("should join two member names with 'and'", () => {
|
||||
const roomName = client.roomNameGenerator?.("", {
|
||||
type: RoomNameType.Generated,
|
||||
names: ["Alice", "Bob"],
|
||||
count: 2,
|
||||
});
|
||||
expect(roomName).toBe("Alice and Bob");
|
||||
});
|
||||
|
||||
it("should name the first member and count the rest when there is one other member not named", () => {
|
||||
const roomName = client.roomNameGenerator?.("", {
|
||||
type: RoomNameType.Generated,
|
||||
names: ["Alice", "Bob"],
|
||||
count: 3,
|
||||
});
|
||||
expect(roomName).toBe("Alice and one other");
|
||||
});
|
||||
|
||||
it("should name the first member and count the rest when there are multiple members not named", () => {
|
||||
const roomName = client.roomNameGenerator?.("", {
|
||||
type: RoomNameType.Generated,
|
||||
names: ["Alice", "Bob", "Carol"],
|
||||
count: 3,
|
||||
});
|
||||
expect(roomName).toBe("Alice and 2 others");
|
||||
});
|
||||
|
||||
describe("when inviting", () => {
|
||||
it("should return empty room when there are no invitees", () => {
|
||||
const roomName = client.roomNameGenerator?.("", {
|
||||
type: RoomNameType.Generated,
|
||||
subtype: "Inviting",
|
||||
names: [],
|
||||
count: 0,
|
||||
});
|
||||
expect(roomName).toBe("Empty room");
|
||||
});
|
||||
|
||||
it("should return the single invitee name when there is only one invitee", () => {
|
||||
const roomName = client.roomNameGenerator?.("", {
|
||||
type: RoomNameType.Generated,
|
||||
subtype: "Inviting",
|
||||
names: ["Alice"],
|
||||
count: 1,
|
||||
});
|
||||
expect(roomName).toBe("Alice");
|
||||
});
|
||||
|
||||
it("should say who is being invited when there are two invitees", () => {
|
||||
const roomName = client.roomNameGenerator?.("", {
|
||||
type: RoomNameType.Generated,
|
||||
subtype: "Inviting",
|
||||
names: ["Alice", "Bob"],
|
||||
count: 2,
|
||||
});
|
||||
expect(roomName).toBe("Inviting Alice and Bob");
|
||||
});
|
||||
|
||||
it("should name the first invitee and count the rest when there are more than two invitees", () => {
|
||||
const roomName = client.roomNameGenerator?.("", {
|
||||
type: RoomNameType.Generated,
|
||||
subtype: "Inviting",
|
||||
names: ["Alice", "Bob", "Carol"],
|
||||
count: 3,
|
||||
});
|
||||
expect(roomName).toBe("Inviting Alice and 2 others");
|
||||
});
|
||||
|
||||
it("should count uninvited members separately from named invitees", () => {
|
||||
const roomName = client.roomNameGenerator?.("", {
|
||||
type: RoomNameType.Generated,
|
||||
subtype: "Inviting",
|
||||
names: ["Alice", "Bob"],
|
||||
count: 4,
|
||||
});
|
||||
expect(roomName).toBe("Inviting Alice and 3 others");
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2017-2021 The Matrix.org Foundation C.I.C.
|
||||
|
||||
@@ -14,9 +15,20 @@ import {
|
||||
IndexedDBCryptoStore,
|
||||
IndexedDBStore,
|
||||
LocalStorageCryptoStore,
|
||||
RoomNameType,
|
||||
type RoomNameState,
|
||||
type TokenRefreshFunction,
|
||||
EventTimelineSet,
|
||||
EventTimeline,
|
||||
} from "matrix-js-sdk/src/matrix";
|
||||
import { VerificationMethod } from "matrix-js-sdk/src/types";
|
||||
|
||||
import indexeddbWorkerFactory from "../workers/indexeddbWorkerFactory";
|
||||
import SettingsStore from "../settings/SettingsStore";
|
||||
import { crossSigningCallbacks } from "../SecurityManager";
|
||||
import IdentityAuthClient from "../IdentityAuthClient";
|
||||
import { _t } from "../languageHandler";
|
||||
import { formatList } from "./FormattingUtils";
|
||||
|
||||
const localStorage = window.localStorage;
|
||||
|
||||
@@ -27,6 +39,131 @@ try {
|
||||
indexedDB = window.indexedDB;
|
||||
} catch {}
|
||||
|
||||
/**
|
||||
* Credentials used to create a MatrixClient with `createClientWithCreds`.
|
||||
*/
|
||||
export interface IMatrixClientCreds {
|
||||
homeserverUrl: string;
|
||||
identityServerUrl?: string;
|
||||
userId: string;
|
||||
deviceId?: string;
|
||||
accessToken: string;
|
||||
refreshToken?: string;
|
||||
guest?: boolean;
|
||||
pickleKey?: string;
|
||||
freshLogin?: boolean;
|
||||
}
|
||||
|
||||
function namesToRoomName(names: string[], count: number): string | undefined {
|
||||
const countWithoutMe = count - 1;
|
||||
if (!names.length) {
|
||||
return _t("empty_room");
|
||||
}
|
||||
if (names.length === 1 && countWithoutMe <= 1) {
|
||||
return names[0];
|
||||
}
|
||||
}
|
||||
|
||||
function memberNamesToRoomName(names: string[], count: number): string {
|
||||
const name = namesToRoomName(names, count);
|
||||
if (name) return name;
|
||||
|
||||
if (names.length === 2 && count === 2) {
|
||||
return formatList(names);
|
||||
}
|
||||
return formatList(names, 1);
|
||||
}
|
||||
|
||||
function inviteeNamesToRoomName(names: string[], count: number): string {
|
||||
const name = namesToRoomName(names, count);
|
||||
if (name) return name;
|
||||
|
||||
if (names.length === 2 && count === 2) {
|
||||
return _t("inviting_user1_and_user2", {
|
||||
user1: names[0],
|
||||
user2: names[1],
|
||||
});
|
||||
}
|
||||
return _t("inviting_user_and_n_others", {
|
||||
user: names[0],
|
||||
count: count - 1,
|
||||
});
|
||||
}
|
||||
|
||||
function roomNameGenerator(_: string, state: RoomNameState): string | null {
|
||||
switch (state.type) {
|
||||
case RoomNameType.Generated:
|
||||
switch (state.subtype) {
|
||||
case "Inviting":
|
||||
return inviteeNamesToRoomName(state.names, state.count);
|
||||
default:
|
||||
return memberNamesToRoomName(state.names, state.count);
|
||||
}
|
||||
case RoomNameType.EmptyRoom:
|
||||
if (state.oldName) {
|
||||
return _t("empty_room_was_name", {
|
||||
oldName: state.oldName,
|
||||
});
|
||||
} else {
|
||||
return _t("empty_room");
|
||||
}
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new matrix client from credentials with all the options needed.
|
||||
*
|
||||
* @param creds The credentials to create the client with
|
||||
* @param tokenRefreshFunction Optional function to call when the access token is expired
|
||||
*
|
||||
* @returns {MatrixClient} the newly-created MatrixClient
|
||||
*/
|
||||
export function createClientWithCreds(
|
||||
creds: IMatrixClientCreds,
|
||||
tokenRefreshFunction?: TokenRefreshFunction,
|
||||
): MatrixClient {
|
||||
const opts: ICreateClientOpts = {
|
||||
baseUrl: creds.homeserverUrl,
|
||||
idBaseUrl: creds.identityServerUrl,
|
||||
accessToken: creds.accessToken,
|
||||
refreshToken: creds.refreshToken,
|
||||
tokenRefreshFunction,
|
||||
userId: creds.userId,
|
||||
deviceId: creds.deviceId,
|
||||
pickleKey: creds.pickleKey,
|
||||
timelineSupport: true,
|
||||
forceTURN: !SettingsStore.getValue("webRtcAllowPeerToPeer"),
|
||||
fallbackICEServerAllowed: !!SettingsStore.getValue("fallbackICEServerAllowed"),
|
||||
// Gather up to 20 ICE candidates when a call arrives: this should be more than we'd
|
||||
// ever normally need, so effectively this should make all the gathering happen when
|
||||
// the call arrives.
|
||||
iceCandidatePoolSize: 20,
|
||||
verificationMethods: [VerificationMethod.Sas, VerificationMethod.ShowQrCode, VerificationMethod.Reciprocate],
|
||||
identityServer: new IdentityAuthClient(),
|
||||
// These are always installed regardless of the labs flag so that cross-signing features
|
||||
// can toggle on without reloading and also be accessed immediately after login.
|
||||
cryptoCallbacks: { ...crossSigningCallbacks },
|
||||
enableEncryptedStateEvents: SettingsStore.getValue("feature_msc4362_encrypted_state_events"),
|
||||
unstableMSC1763Retention: SettingsStore.getValue("feature_retention"),
|
||||
roomNameGenerator,
|
||||
};
|
||||
|
||||
const newCli = createMatrixClient(opts);
|
||||
newCli.setGuest(Boolean(creds.guest));
|
||||
|
||||
const notifTimelineSet = new EventTimelineSet(undefined, {
|
||||
timelineSupport: true,
|
||||
pendingEvents: false,
|
||||
});
|
||||
// XXX: what is our initial pagination token?! it somehow needs to be synchronised with /sync.
|
||||
notifTimelineSet.getLiveTimeline().setPaginationToken("", EventTimeline.BACKWARDS);
|
||||
newCli.setNotifTimelineSet(notifTimelineSet);
|
||||
|
||||
return newCli;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new matrix client, with the persistent stores set up appropriately
|
||||
* (using localstorage/indexeddb, etc)
|
||||
@@ -36,7 +173,7 @@ try {
|
||||
*
|
||||
* @returns {MatrixClient} the newly-created MatrixClient
|
||||
*/
|
||||
export default function createMatrixClient(opts: ICreateClientOpts): MatrixClient {
|
||||
export function createMatrixClient(opts: ICreateClientOpts): MatrixClient {
|
||||
const storeOpts: Partial<ICreateClientOpts> = {
|
||||
useAuthorizationHeader: true,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user