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

Stop using the js-sdk's compare function #12782

Merged
merged 7 commits into from
Jul 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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: 2 additions & 2 deletions src/components/views/rooms/WhoIsTypingTile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ limitations under the License.

import React from "react";
import { Room, RoomEvent, RoomMember, RoomMemberEvent, MatrixEvent } from "matrix-js-sdk/src/matrix";
import { compare } from "matrix-js-sdk/src/utils";
Copy link
Member

Choose a reason for hiding this comment

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

matrix-js-sdk/src/utils is intended to be reusable though not necessarily stable. Given we use a load of utils from that export why are you picking on this one in particular?

image

Copy link
Member Author

Choose a reason for hiding this comment

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

Since it was instantiated at the module level, it was running before modernizr when I was trying to write the test. I figure rather than rearranging stuff to try to get the execution order right, the best way to fix this was to just not arbitrarily instantiate a static collator and instead make one when we need it, at which point the compare function is adding no value at all.

Copy link
Member

Choose a reason for hiding this comment

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

But element-web can't assume any of its dependencies don't do that. Sure we can fix that in the js-sdk but not in other dependencies. So instead we should write our code to defensively handle that situation.

Copy link
Member Author

Choose a reason for hiding this comment

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

I don't disagree, although I'd need to dig more into exactly what order things get run in to do so. This felt like a thing that was still worth doing anyway.

Copy link
Member

Choose a reason for hiding this comment

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

Copy link
Member Author

Choose a reason for hiding this comment

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

Although that said, if you strongly think that's a better thing to do than this then I'll stop killing myself trying to get the test coverage on this PR up to the bar.

Copy link
Member

Choose a reason for hiding this comment

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

I think this is a band-aid for a single cause, which is quite esoteric given that https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator#browser_compatibility has been supported for years, so instead making the "bootloader" resilient to any such calls for more recent APIs in dependencies we control and those we do not would be more sane IMO

Copy link
Member Author

Choose a reason for hiding this comment

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

Oh well, test didn't involve fixing other app bugs like the other one did, so this may as well live as tidy-up fix anyway. We might want to consider just loading a small stub from the HTML and loading the full app as an async import, which would give us more flexibility to do loading screens and such as well as have complete control over what executes in the stub.


import * as WhoIsTyping from "../../../WhoIsTyping";
import Timer from "../../../utils/Timer";
Expand Down Expand Up @@ -208,7 +207,8 @@ export default class WhoIsTypingTile extends React.Component<IProps, IState> {

// sort them so the typing members don't change order when
// moved to delayedStopTypingTimers
usersTyping.sort((a, b) => compare(a.name, b.name));
const collator = new Intl.Collator();
usersTyping.sort((a, b) => collator.compare(a.name, b.name));

const typingString = WhoIsTyping.whoIsTypingString(usersTyping, this.props.whoIsTypingLimit);
if (!typingString) {
Expand Down
16 changes: 12 additions & 4 deletions src/components/views/settings/PowerLevelSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

import React, { useState, JSX, PropsWithChildren } from "react";
import { Button } from "@vector-im/compound-web";
import { compare } from "matrix-js-sdk/src/utils";

import { useMatrixClientContext } from "../../../contexts/MatrixClientContext";
import PowerSelector from "../elements/PowerSelector";
Expand Down Expand Up @@ -78,9 +77,11 @@ export function PowerLevelSelector({
currentPowerLevel && currentPowerLevel.value !== userLevels[currentPowerLevel?.userId],
);

const collator = new Intl.Collator();

// We sort the users by power level, then we filter them
const users = Object.keys(userLevels)
.sort((userA, userB) => sortUser(userA, userB, userLevels))
.sort((userA, userB) => sortUser(collator, userA, userB, userLevels))
.filter(filter);

// No user to display, we return the children into fragment to convert it to JSX.Element type
Expand Down Expand Up @@ -136,7 +137,14 @@ export function PowerLevelSelector({
* @param userB
* @param userLevels
*/
function sortUser(userA: string, userB: string, userLevels: PowerLevelSelectorProps["userLevels"]): number {
function sortUser(
collator: Intl.Collator,
userA: string,
userB: string,
userLevels: PowerLevelSelectorProps["userLevels"],
): number {
const powerLevelDiff = userLevels[userA] - userLevels[userB];
return powerLevelDiff !== 0 ? powerLevelDiff : compare(userA.toLocaleLowerCase(), userB.toLocaleLowerCase());
return powerLevelDiff !== 0
? powerLevelDiff
: collator.compare(userA.toLocaleLowerCase(), userB.toLocaleLowerCase());
}
4 changes: 2 additions & 2 deletions src/integrations/IntegrationManagers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ limitations under the License.

import { logger } from "matrix-js-sdk/src/logger";
import { ClientEvent, IClientWellKnown, MatrixClient } from "matrix-js-sdk/src/matrix";
import { compare } from "matrix-js-sdk/src/utils";

import type { MatrixEvent } from "matrix-js-sdk/src/matrix";
import SdkConfig from "../SdkConfig";
Expand Down Expand Up @@ -145,14 +144,15 @@ export class IntegrationManagers {
}

public getOrderedManagers(): IntegrationManagerInstance[] {
const collator = new Intl.Collator();
const ordered: IntegrationManagerInstance[] = [];
for (const kind of KIND_PREFERENCE) {
const managers = this.managers.filter((m) => m.kind === kind);
if (!managers || !managers.length) continue;

if (kind === Kind.Account) {
// Order by state_keys (IDs)
managers.sort((a, b) => compare(a.id ?? "", b.id ?? ""));
managers.sort((a, b) => collator.compare(a.id ?? "", b.id ?? ""));
}

ordered.push(...managers);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ limitations under the License.
*/

import { Room } from "matrix-js-sdk/src/matrix";
import { compare } from "matrix-js-sdk/src/utils";

import { TagID } from "../../models";
import { IAlgorithm } from "./IAlgorithm";
Expand All @@ -25,8 +24,9 @@ import { IAlgorithm } from "./IAlgorithm";
*/
export class AlphabeticAlgorithm implements IAlgorithm {
public sortRooms(rooms: Room[], tagId: TagID): Room[] {
const collator = new Intl.Collator();
return rooms.sort((a, b) => {
return compare(a.name, b.name);
return collator.compare(a.name, b.name);
});
}
}
6 changes: 4 additions & 2 deletions src/stores/widgets/WidgetLayoutStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

import { Room, RoomStateEvent, MatrixEvent } from "matrix-js-sdk/src/matrix";
import { Optional } from "matrix-events-sdk";
import { compare, MapWithDefault, recursiveMapToObject } from "matrix-js-sdk/src/utils";
import { MapWithDefault, recursiveMapToObject } from "matrix-js-sdk/src/utils";
import { IWidget } from "matrix-widget-api";

import SettingsStore from "../../settings/SettingsStore";
Expand Down Expand Up @@ -200,6 +200,8 @@ export class WidgetLayoutStore extends ReadyWatchingStore {
const runoff = topWidgets.slice(MAX_PINNED);
rightWidgets.push(...runoff);

const collator = new Intl.Collator();

// Order the widgets in the top container, putting autopinned Jitsi widgets first
// unless they have a specific order in mind
topWidgets.sort((a, b) => {
Expand All @@ -219,7 +221,7 @@ export class WidgetLayoutStore extends ReadyWatchingStore {

if (orderA === orderB) {
// We just need a tiebreak
return compare(a.id, b.id);
return collator.compare(a.id, b.id);
}

return orderA - orderB;
Expand Down
6 changes: 4 additions & 2 deletions src/theme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import { compare } from "matrix-js-sdk/src/utils";
import { logger } from "matrix-js-sdk/src/logger";

import { _t } from "./languageHandler";
Expand Down Expand Up @@ -113,7 +112,10 @@ export function getOrderedThemes(): ITheme[] {
.map((p) => ({ id: p[0], name: p[1] })) // convert pairs to objects for code readability
.filter((p) => !isHighContrastTheme(p.id));
const builtInThemes = themes.filter((p) => !p.id.startsWith("custom-"));
const customThemes = themes.filter((p) => !builtInThemes.includes(p)).sort((a, b) => compare(a.name, b.name));
const collator = new Intl.Collator();
const customThemes = themes
.filter((p) => !builtInThemes.includes(p))
.sort((a, b) => collator.compare(a.name, b.name));
return [...builtInThemes, ...customThemes];
}

Expand Down
4 changes: 2 additions & 2 deletions test/components/views/rooms/MemberList-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import React from "react";
import { act, fireEvent, render, RenderResult, screen } from "@testing-library/react";
import { Room, MatrixClient, RoomState, RoomMember, User, MatrixEvent } from "matrix-js-sdk/src/matrix";
import { KnownMembership } from "matrix-js-sdk/src/types";
import { compare } from "matrix-js-sdk/src/utils";
import { mocked, MockedObject } from "jest-mock";

import { MatrixClientPeg } from "../../../../src/MatrixClientPeg";
Expand Down Expand Up @@ -145,7 +144,8 @@ describe("MemberList", () => {
if (!groupChange) {
const nameA = memberA.name[0] === "@" ? memberA.name.slice(1) : memberA.name;
const nameB = memberB.name[0] === "@" ? memberB.name.slice(1) : memberB.name;
const nameCompare = compare(nameB, nameA);
const collator = new Intl.Collator();
const nameCompare = collator.compare(nameB, nameA);
console.log("Comparing name");
expect(nameCompare).toBeGreaterThanOrEqual(0);
} else {
Expand Down
70 changes: 70 additions & 0 deletions test/integrations/IntegrationManagers-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
Copyright 2024 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 { MatrixClient, MatrixEvent } from "matrix-js-sdk/src/matrix";
import { mocked } from "jest-mock";

import { IntegrationManagers } from "../../src/integrations/IntegrationManagers";
import { stubClient } from "../test-utils";

describe("IntegrationManagers", () => {
let client: MatrixClient;
let intMgrs: IntegrationManagers;

beforeEach(() => {
client = stubClient();
mocked(client).getAccountData.mockReturnValue({
getContent: jest.fn().mockReturnValue({
foo: {
id: "foo",
content: {
type: "m.integration_manager",
url: "http://foo/ui",
data: {
api_url: "http://foo/api",
},
},
},
bar: {
id: "bar",
content: {
type: "m.integration_manager",
url: "http://bar/ui",
data: {
api_url: "http://bar/api",
},
},
},
}),
} as unknown as MatrixEvent);

intMgrs = new IntegrationManagers();
intMgrs.startWatching();
});

afterEach(() => {
intMgrs.stopWatching();
});

describe("getOrderedManagers", () => {
it("should return integration managers in alphabetical order", () => {
const orderedManagers = intMgrs.getOrderedManagers();

expect(orderedManagers[0].id).toBe("bar");
expect(orderedManagers[1].id).toBe("foo");
});
});
});
42 changes: 31 additions & 11 deletions test/stores/WidgetLayoutStore-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,25 +25,29 @@ import SettingsStore from "../../src/settings/SettingsStore";

// setup test env values
const roomId = "!room:server";
const mockRoom = <Room>{
roomId: roomId,
currentState: {
getStateEvents: (_l, _x) => {
return {
getId: () => "$layoutEventId",
getContent: () => null,
};
},
},
};

describe("WidgetLayoutStore", () => {
let client: MatrixClient;
let store: WidgetLayoutStore;
let roomUpdateListener: (event: string) => void;
let mockApps: IApp[];
let mockRoom: Room;
let layoutEventContent: Record<string, any> | null;

beforeEach(() => {
layoutEventContent = null;
mockRoom = <Room>{
roomId: roomId,
currentState: {
getStateEvents: (_l, _x) => {
return {
getId: () => "$layoutEventId",
getContent: () => layoutEventContent,
};
},
},
};

mockApps = [
<IApp>{ roomId: roomId, id: "1" },
<IApp>{ roomId: roomId, id: "2" },
Expand Down Expand Up @@ -87,6 +91,22 @@ describe("WidgetLayoutStore", () => {
expect(store.getContainerHeight(mockRoom, Container.Top)).toBeNull();
});

it("ordering of top container widgets should be consistent even if no index specified", async () => {
layoutEventContent = {
widgets: {
"1": {
container: "top",
},
"2": {
container: "top",
},
},
};

store.recalculateRoom(mockRoom);
expect(store.getContainerWidgets(mockRoom, Container.Top)).toStrictEqual([mockApps[0], mockApps[1]]);
});

it("add three widgets to top container", async () => {
store.recalculateRoom(mockRoom);
store.moveToContainer(mockRoom, mockApps[0], Container.Top);
Expand Down
19 changes: 17 additions & 2 deletions test/theme-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,13 @@ limitations under the License.
*/

import SettingsStore from "../src/settings/SettingsStore";
import { enumerateThemes, setTheme } from "../src/theme";
import { enumerateThemes, getOrderedThemes, setTheme } from "../src/theme";

describe("theme", () => {
afterEach(() => {
jest.restoreAllMocks();
});

describe("setTheme", () => {
let lightTheme: HTMLStyleElement;
let darkTheme: HTMLStyleElement;
Expand Down Expand Up @@ -48,7 +52,6 @@ describe("theme", () => {
});

afterEach(() => {
jest.restoreAllMocks();
jest.useRealTimers();
});

Expand Down Expand Up @@ -162,4 +165,16 @@ describe("theme", () => {
});
});
});

describe("getOrderedThemes", () => {
it("should return a list of themes in the correct order", () => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue([{ name: "Zebra Striped" }, { name: "Apple Green" }]);
expect(getOrderedThemes()).toEqual([
{ id: "light", name: "Light" },
{ id: "dark", name: "Dark" },
{ id: "custom-Apple Green", name: "Apple Green" },
{ id: "custom-Zebra Striped", name: "Zebra Striped" },
]);
});
});
});
Loading