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

Commit 3a63c88

Browse files
author
Germain
authored
Order new search dialog results by recency (#8444)
* Order new search dialog results by recency * Add getLastTs tests * Add sort rooms tests
1 parent b5ac949 commit 3a63c88

File tree

3 files changed

+194
-45
lines changed

3 files changed

+194
-45
lines changed

src/components/views/dialogs/SpotlightDialog.tsx

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ import { KeyBindingAction } from "../../../accessibility/KeyboardShortcuts";
7474
import { PosthogAnalytics } from "../../../PosthogAnalytics";
7575
import { getCachedRoomIDForAlias } from "../../../RoomAliasCache";
7676
import { roomContextDetailsText, spaceContextDetailsText } from "../../../utils/i18n-helpers";
77+
import { RecentAlgorithm } from "../../../stores/room-list/algorithms/tag-sorting/RecentAlgorithm";
7778

7879
const MAX_RECENT_SEARCHES = 10;
7980
const SECTION_LIMIT = 50; // only show 50 results per section for performance reasons
@@ -210,6 +211,8 @@ type Result = IRoomResult | IResult;
210211

211212
const isRoomResult = (result: any): result is IRoomResult => !!result?.room;
212213

214+
const recentAlgorithm = new RecentAlgorithm();
215+
213216
export const useWebSearchMetrics = (numResults: number, queryLength: number, viaSpotlight: boolean): void => {
214217
useEffect(() => {
215218
if (!queryLength) return;
@@ -280,6 +283,7 @@ const SpotlightDialog: React.FC<IProps> = ({ initialText = "", onFinished }) =>
280283

281284
const results: [Result[], Result[], Result[]] = [[], [], []];
282285

286+
// Group results in their respective sections
283287
possibleResults.forEach(entry => {
284288
if (isRoomResult(entry)) {
285289
if (!entry.room.normalizedName.includes(normalizedQuery) &&
@@ -295,8 +299,25 @@ const SpotlightDialog: React.FC<IProps> = ({ initialText = "", onFinished }) =>
295299
results[entry.section].push(entry);
296300
});
297301

302+
// Sort results by most recent activity
303+
304+
const myUserId = cli.getUserId();
305+
for (const resultArray of results) {
306+
resultArray.sort((a: Result, b: Result) => {
307+
// This is not a room result, it should appear at the bottom of
308+
// the list
309+
if (!(a as IRoomResult).room) return 1;
310+
if (!(b as IRoomResult).room) return -1;
311+
312+
const roomA = (a as IRoomResult).room;
313+
const roomB = (b as IRoomResult).room;
314+
315+
return recentAlgorithm.getLastTs(roomB, myUserId) - recentAlgorithm.getLastTs(roomA, myUserId);
316+
});
317+
}
318+
298319
return results;
299-
}, [possibleResults, trimmedQuery]);
320+
}, [possibleResults, trimmedQuery, cli]);
300321

301322
const numResults = trimmedQuery ? people.length + rooms.length + spaces.length : 0;
302323
useWebSearchMetrics(numResults, query.length, true);

src/stores/room-list/algorithms/tag-sorting/RecentAlgorithm.ts

Lines changed: 45 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -63,58 +63,55 @@ export const sortRooms = (rooms: Room[]): Room[] => {
6363
}
6464

6565
const tsCache: { [roomId: string]: number } = {};
66-
const getLastTs = (r: Room) => {
67-
if (tsCache[r.roomId]) {
68-
return tsCache[r.roomId];
69-
}
7066

71-
const ts = (() => {
72-
// Apparently we can have rooms without timelines, at least under testing
73-
// environments. Just return MAX_INT when this happens.
74-
if (!r || !r.timeline) {
75-
return Number.MAX_SAFE_INTEGER;
76-
}
67+
return rooms.sort((a, b) => {
68+
const roomALastTs = tsCache[a.roomId] ?? getLastTs(a, myUserId);
69+
const roomBLastTs = tsCache[b.roomId] ?? getLastTs(b, myUserId);
7770

78-
// If the room hasn't been joined yet, it probably won't have a timeline to
79-
// parse. We'll still fall back to the timeline if this fails, but chances
80-
// are we'll at least have our own membership event to go off of.
81-
const effectiveMembership = getEffectiveMembership(r.getMyMembership());
82-
if (effectiveMembership !== EffectiveMembership.Join) {
83-
const membershipEvent = r.currentState.getStateEvents("m.room.member", myUserId);
84-
if (membershipEvent && !Array.isArray(membershipEvent)) {
85-
return membershipEvent.getTs();
86-
}
87-
}
71+
tsCache[a.roomId] = roomALastTs;
72+
tsCache[b.roomId] = roomBLastTs;
8873

89-
for (let i = r.timeline.length - 1; i >= 0; --i) {
90-
const ev = r.timeline[i];
91-
if (!ev.getTs()) continue; // skip events that don't have timestamps (tests only?)
74+
return roomBLastTs - roomALastTs;
75+
});
76+
};
9277

93-
if (
94-
(ev.getSender() === myUserId && shouldCauseReorder(ev)) ||
95-
Unread.eventTriggersUnreadCount(ev)
96-
) {
97-
return ev.getTs();
98-
}
99-
}
78+
const getLastTs = (r: Room, userId: string) => {
79+
const ts = (() => {
80+
// Apparently we can have rooms without timelines, at least under testing
81+
// environments. Just return MAX_INT when this happens.
82+
if (!r?.timeline) {
83+
return Number.MAX_SAFE_INTEGER;
84+
}
10085

101-
// we might only have events that don't trigger the unread indicator,
102-
// in which case use the oldest event even if normally it wouldn't count.
103-
// This is better than just assuming the last event was forever ago.
104-
if (r.timeline.length && r.timeline[0].getTs()) {
105-
return r.timeline[0].getTs();
106-
} else {
107-
return Number.MAX_SAFE_INTEGER;
86+
// If the room hasn't been joined yet, it probably won't have a timeline to
87+
// parse. We'll still fall back to the timeline if this fails, but chances
88+
// are we'll at least have our own membership event to go off of.
89+
const effectiveMembership = getEffectiveMembership(r.getMyMembership());
90+
if (effectiveMembership !== EffectiveMembership.Join) {
91+
const membershipEvent = r.currentState.getStateEvents(EventType.RoomMember, userId);
92+
if (membershipEvent && !Array.isArray(membershipEvent)) {
93+
return membershipEvent.getTs();
10894
}
109-
})();
95+
}
11096

111-
tsCache[r.roomId] = ts;
112-
return ts;
113-
};
97+
for (let i = r.timeline.length - 1; i >= 0; --i) {
98+
const ev = r.timeline[i];
99+
if (!ev.getTs()) continue; // skip events that don't have timestamps (tests only?)
114100

115-
return rooms.sort((a, b) => {
116-
return getLastTs(b) - getLastTs(a);
117-
});
101+
if (
102+
(ev.getSender() === userId && shouldCauseReorder(ev)) ||
103+
Unread.eventTriggersUnreadCount(ev)
104+
) {
105+
return ev.getTs();
106+
}
107+
}
108+
109+
// we might only have events that don't trigger the unread indicator,
110+
// in which case use the oldest event even if normally it wouldn't count.
111+
// This is better than just assuming the last event was forever ago.
112+
return r.timeline[0]?.getTs() ?? Number.MAX_SAFE_INTEGER;
113+
})();
114+
return ts;
118115
};
119116

120117
/**
@@ -125,4 +122,8 @@ export class RecentAlgorithm implements IAlgorithm {
125122
public sortRooms(rooms: Room[], tagId: TagID): Room[] {
126123
return sortRooms(rooms);
127124
}
125+
126+
public getLastTs(room: Room, userId: string): number {
127+
return getLastTs(room, userId);
128+
}
128129
}
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
/*
2+
Copyright 2022 The Matrix.org Foundation C.I.C.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
import { Room } from "matrix-js-sdk/src/models/room";
18+
19+
import { stubClient, mkRoom, mkMessage } from "../../../test-utils";
20+
import { MatrixClientPeg } from "../../../../src/MatrixClientPeg";
21+
import "../../../../src/stores/room-list/RoomListStore";
22+
import { RecentAlgorithm } from "../../../../src/stores/room-list/algorithms/tag-sorting/RecentAlgorithm";
23+
import { EffectiveMembership } from "../../../../src/utils/membership";
24+
25+
describe("RecentAlgorithm", () => {
26+
let algorithm;
27+
let cli;
28+
beforeEach(() => {
29+
stubClient();
30+
cli = MatrixClientPeg.get();
31+
algorithm = new RecentAlgorithm();
32+
});
33+
34+
describe("getLastTs", () => {
35+
it("returns the last ts", () => {
36+
const room = new Room("room123", cli, "@john:matrix.org");
37+
38+
const event1 = mkMessage({
39+
room: room.roomId,
40+
msg: "Hello world!",
41+
user: "@alice:matrix.org",
42+
ts: 5,
43+
event: true,
44+
});
45+
const event2 = mkMessage({
46+
room: room.roomId,
47+
msg: "Howdy!",
48+
user: "@bob:matrix.org",
49+
ts: 10,
50+
event: true,
51+
});
52+
53+
room.getMyMembership = () => "join";
54+
55+
room.addLiveEvents([event1]);
56+
expect(algorithm.getLastTs(room, "@jane:matrix.org")).toBe(5);
57+
expect(algorithm.getLastTs(room, "@john:matrix.org")).toBe(5);
58+
59+
room.addLiveEvents([event2]);
60+
61+
expect(algorithm.getLastTs(room, "@jane:matrix.org")).toBe(10);
62+
expect(algorithm.getLastTs(room, "@john:matrix.org")).toBe(10);
63+
});
64+
65+
it("returns a fake ts for rooms without a timeline", () => {
66+
const room = mkRoom(cli, "!new:example.org");
67+
room.timeline = undefined;
68+
expect(algorithm.getLastTs(room, "@john:matrix.org")).toBe(Number.MAX_SAFE_INTEGER);
69+
});
70+
71+
it("works when not a member", () => {
72+
const room = mkRoom(cli, "!new:example.org");
73+
room.getMyMembership.mockReturnValue(EffectiveMembership.Invite);
74+
expect(algorithm.getLastTs(room, "@john:matrix.org")).toBe(Number.MAX_SAFE_INTEGER);
75+
});
76+
});
77+
78+
describe("sortRooms", () => {
79+
it("orders rooms per last message ts", () => {
80+
const room1 = new Room("room1", cli, "@bob:matrix.org");
81+
const room2 = new Room("room2", cli, "@bob:matrix.org");
82+
83+
room1.getMyMembership = () => "join";
84+
room2.getMyMembership = () => "join";
85+
86+
const evt = mkMessage({
87+
room: room1.roomId,
88+
msg: "Hello world!",
89+
user: "@alice:matrix.org",
90+
ts: 5,
91+
event: true,
92+
});
93+
const evt2 = mkMessage({
94+
room: room2.roomId,
95+
msg: "Hello world!",
96+
user: "@alice:matrix.org",
97+
ts: 2,
98+
event: true,
99+
});
100+
101+
room1.addLiveEvents([evt]);
102+
room2.addLiveEvents([evt2]);
103+
104+
expect(algorithm.sortRooms([room2, room1])).toEqual([room1, room2]);
105+
});
106+
107+
it("orders rooms without messages first", () => {
108+
const room1 = new Room("room1", cli, "@bob:matrix.org");
109+
const room2 = new Room("room2", cli, "@bob:matrix.org");
110+
111+
room1.getMyMembership = () => "join";
112+
room2.getMyMembership = () => "join";
113+
114+
const evt = mkMessage({
115+
room: room1.roomId,
116+
msg: "Hello world!",
117+
user: "@alice:matrix.org",
118+
ts: 5,
119+
event: true,
120+
});
121+
122+
room1.addLiveEvents([evt]);
123+
124+
expect(algorithm.sortRooms([room2, room1])).toEqual([room2, room1]);
125+
});
126+
});
127+
});

0 commit comments

Comments
 (0)