Skip to content

Commit

Permalink
Use useRoomState & useAsyncMemo
Browse files Browse the repository at this point in the history
  • Loading branch information
florianduros committed Nov 13, 2024
1 parent c76f086 commit 0ee713a
Showing 1 changed file with 16 additions and 24 deletions.
40 changes: 16 additions & 24 deletions src/hooks/useIsEncrypted.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,33 +6,25 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
Please see LICENSE files in the repository root for full details.
*/

import { useCallback, useEffect, useState } from "react";
import { MatrixClient, MatrixEvent, Room, RoomStateEvent, EventType } from "matrix-js-sdk/src/matrix";
import { MatrixClient, MatrixEvent, Room, EventType } from "matrix-js-sdk/src/matrix";

import { useTypedEventEmitter } from "./useEventEmitter";
import { useRoomState } from "./useRoomState.ts";
import { useAsyncMemo } from "./useAsyncMemo.ts";

// Hook to simplify watching whether a Matrix room is encrypted, returns undefined if room is undefined, return null when isRoomEncrypted is computed
export function useIsEncrypted(cli: MatrixClient, room?: Room): boolean | undefined | null {
const [isEncrypted, setIsEncrypted] = useState<boolean | null | undefined>(null);
// Hook to simplify watching whether a Matrix room is encrypted, returns null if room is undefined or the state is loading
export function useIsEncrypted(cli: MatrixClient, room?: Room): boolean | null {
const encryptionStateEvent: MatrixEvent | undefined = useRoomState(
room,
(roomState) => roomState.getStateEvents(EventType.RoomEncryption)?.[0],
);
return useAsyncMemo(
async () => {
const crypto = cli.getCrypto();
if (!room || !crypto) return null;

useEffect(() => {
const func = async (): Promise<void> =>
room && setIsEncrypted(await cli.getCrypto()?.isEncryptionEnabledInRoom(room.roomId));
func();
}, [cli, room]);
const update = useCallback(
async (event: MatrixEvent) => {
if (room && event.getType() === EventType.RoomEncryption) {
try {
setIsEncrypted(await cli.getCrypto()?.isEncryptionEnabledInRoom(room.roomId));
} catch {
setIsEncrypted(false);
}
}
return crypto.isEncryptionEnabledInRoom(room.roomId);
},
[cli, room],
[room, encryptionStateEvent],
null,
);
useTypedEventEmitter(room?.currentState, RoomStateEvent.Events, update);

return isEncrypted;
}

0 comments on commit 0ee713a

Please sign in to comment.