Files
element-call/src/room/useActiveFocus.ts

63 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-08-18 09:03:21 +01:00
/*
Copyright 2023, 2024 New Vector Ltd.
2023-08-18 09:03:21 +01:00
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
2023-08-18 09:03:21 +01:00
*/
import {
type MatrixRTCSession,
2023-08-18 09:03:21 +01:00
MatrixRTCSessionEvent,
} from "matrix-js-sdk/src/matrixrtc/MatrixRTCSession";
import { useCallback, useEffect, useState } from "react";
import { deepCompare } from "matrix-js-sdk/src/utils";
import { logger } from "matrix-js-sdk/src/logger";
import {
type LivekitFocus,
isLivekitFocus,
} from "matrix-js-sdk/src/matrixrtc/LivekitFocus";
2023-08-18 09:03:21 +01:00
/**
* Gets the currently active (livekit) focus for a MatrixRTC session
* This logic is specific to livekit foci where the whole call must use one
* and the same focus.
*/
export function useActiveLivekitFocus(
2023-10-11 10:42:04 -04:00
rtcSession: MatrixRTCSession,
2023-08-18 09:03:21 +01:00
): LivekitFocus | undefined {
const [activeFocus, setActiveFocus] = useState(() => {
const f = rtcSession.getActiveFocus();
// Only handle foci with type="livekit" for now.
return !!f && isLivekitFocus(f) ? f : undefined;
});
2023-08-18 09:03:21 +01:00
const onMembershipsChanged = useCallback(() => {
const newActiveFocus = rtcSession.getActiveFocus();
if (!!newActiveFocus && !isLivekitFocus(newActiveFocus)) return;
2023-08-18 09:03:21 +01:00
if (!deepCompare(activeFocus, newActiveFocus)) {
const oldestMembership = rtcSession.getOldestMembership();
logger.warn(
`Got new active focus from membership: ${oldestMembership?.sender}/${oldestMembership?.deviceId}.
2024-12-10 13:05:09 -05:00
Updating focus (focus switch) from ${JSON.stringify(activeFocus)} to ${JSON.stringify(newActiveFocus)}`,
);
2023-08-18 09:03:21 +01:00
setActiveFocus(newActiveFocus);
}
}, [activeFocus, rtcSession]);
useEffect(() => {
rtcSession.on(
MatrixRTCSessionEvent.MembershipsChanged,
2023-10-11 10:42:04 -04:00
onMembershipsChanged,
2023-08-18 09:03:21 +01:00
);
2024-06-04 11:20:25 -04:00
return (): void => {
2023-08-18 09:03:21 +01:00
rtcSession.off(
MatrixRTCSessionEvent.MembershipsChanged,
2023-10-11 10:42:04 -04:00
onMembershipsChanged,
2023-08-18 09:03:21 +01:00
);
};
});
return activeFocus;
}