forked from element-hq/element-web
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseSpaceResults.ts
More file actions
60 lines (48 loc) · 2.21 KB
/
Copy pathuseSpaceResults.ts
File metadata and controls
60 lines (48 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
Copyright 2024 New Vector Ltd.
Copyright 2022 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 { useCallback, useEffect, useMemo, useState } from "react";
import { type Room, RoomType, type HierarchyRoom } from "matrix-js-sdk/src/matrix";
import { KnownMembership } from "matrix-js-sdk/src/types";
import { RoomHierarchy } from "matrix-js-sdk/src/room-hierarchy";
import { normalize } from "matrix-js-sdk/src/utils";
import { MatrixClientPeg } from "../MatrixClientPeg";
export const useSpaceResults = (space: Room | undefined, query: string): [HierarchyRoom[], boolean] => {
const [rooms, setRooms] = useState<HierarchyRoom[]>([]);
const [hierarchy, setHierarchy] = useState<RoomHierarchy>();
const resetHierarchy = useCallback(() => {
setHierarchy(space ? new RoomHierarchy(space, 50) : undefined);
}, [space]);
useEffect(resetHierarchy, [resetHierarchy]);
useEffect(() => {
if (!space || !hierarchy) return; // nothing to load
let unmounted = false;
(async (): Promise<void> => {
while (hierarchy?.canLoadMore && !unmounted && space === hierarchy.root) {
await hierarchy.load();
if (hierarchy.canLoadMore) hierarchy.load(); // start next load so that the loading attribute is right
setRooms(hierarchy.rooms!);
}
})();
return () => {
unmounted = true;
};
}, [space, hierarchy]);
const results = useMemo(() => {
const trimmedQuery = query.trim();
const lcQuery = trimmedQuery.toLowerCase();
const normalizedQuery = normalize(trimmedQuery);
const cli = MatrixClientPeg.safeGet();
return rooms?.filter((r) => {
return (
r.room_type !== RoomType.Space &&
cli.getRoom(r.room_id)?.getMyMembership() !== KnownMembership.Join &&
(normalize(r.name || "").includes(normalizedQuery) || (r.canonical_alias || "").includes(lcQuery))
);
});
}, [rooms, query]);
return [results, hierarchy?.loading ?? false];
};