refactor disconnectedBanner to use a custom context + app view model

logic.
This commit is contained in:
Timo K. committed 2026-11-23 15:59:44 +01:00
1 parent 74ff32e818
commit 805f64aec5
7 files changed
+187 -96

No files matched your search

+38 -33
View File
@@ -53,6 +53,7 @@ import {
} from "./HostBridge";
import { useInitial } from "./useInitial";
import { LeaveToHomeProvider } from "./LeaveToHomeContext";
import { DisconnectedProvider } from "./DisconnectedContext";
const SentryRoute = Sentry.withSentryReactRouterV7Routing(Route);
@@ -131,39 +132,43 @@ export const App: FC<Props> = ({ vm, widget }) => {
});
const content = loaded ? (
<ClientProvider session={vm.clientSession}>
<MediaDevicesContext value={vm.mediaDevices}>
<BackgroundEffectsProvider effects={vm.backgroundEffects}>
<Sentry.ErrorBoundary
fallback={(error) => <ErrorPage error={error} />}
>
<Routes>
<SentryRoute
path="/"
element={<HomePage clientManager={vm.clientManager} />}
/>
{/* A host's session is signed in to by the host, never here */}
{vm.clientManager !== null && (
<>
<SentryRoute
path="/login"
element={<LoginPage clientManager={vm.clientManager} />}
/>
<SentryRoute
path="/register"
element={<RegisterPage clientManager={vm.clientManager} />}
/>
</>
)}
<SentryRoute
path="*"
element={<RoomPage clientManager={vm.clientManager} />}
/>
</Routes>
</Sentry.ErrorBoundary>
</BackgroundEffectsProvider>
</MediaDevicesContext>
</ClientProvider>
<DisconnectedProvider value={vm.disconnected$}>
<ClientProvider session={vm.clientSession}>
<MediaDevicesContext value={vm.mediaDevices}>
<BackgroundEffectsProvider effects={vm.backgroundEffects}>
<Sentry.ErrorBoundary
fallback={(error) => <ErrorPage error={error} />}
>
<Routes>
<SentryRoute
path="/"
element={<HomePage clientManager={vm.clientManager} />}
/>
{/* A host's session is signed in to by the host, never here */}
{vm.clientManager !== null && (
<>
<SentryRoute
path="/login"
element={<LoginPage clientManager={vm.clientManager} />}
/>
<SentryRoute
path="/register"
element={
<RegisterPage clientManager={vm.clientManager} />
}
/>
</>
)}
<SentryRoute
path="*"
element={<RoomPage clientManager={vm.clientManager} />}
/>
</Routes>
</Sentry.ErrorBoundary>
</BackgroundEffectsProvider>
</MediaDevicesContext>
</ClientProvider>
</DisconnectedProvider>
) : (
<LoadingPage />
);
+14 -24
View File
@@ -5,39 +5,29 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { expect, test, vi } from "vitest";
import { expect, test } from "vitest";
import { act, render } from "@testing-library/react";
import { type MatrixClient } from "matrix-js-sdk";
import { BehaviorSubject } from "rxjs";
import { ClientProvider } from "./ClientContext";
import { DisconnectedBanner } from "./DisconnectedBanner";
import { hostClientSession } from "./state/ClientSession";
import { DisconnectedProvider } from "./DisconnectedContext";
test("shows while the client's sync fails to connect", () => {
const client = {
on: vi.fn(),
removeListener: vi.fn(),
getUserId: () => "@alice:example.org",
} as Partial<MatrixClient> as MatrixClient;
test("shows while the client is disconnected", () => {
const disconnected$ = new BehaviorSubject(false);
const { container } = render(
<ClientProvider session={hostClientSession(client)}>
<DisconnectedProvider value={disconnected$}>
<DisconnectedBanner />
</ClientProvider>,
</DisconnectedProvider>,
);
expect(container.textContent).toBe("");
const [, onSync] = vi.mocked(client.on).mock.calls[0] as [
unknown,
(state: string, old: null, data?: { error?: Error }) => void,
];
const connectionError = Object.assign(new Error("offline"), {
name: "ConnectionError",
});
act(() => onSync("ERROR", null, { error: connectionError }));
act(() => disconnected$.next(true));
expect(container.textContent).not.toBe("");
// Any other failure is not a connection problem
act(() => onSync("ERROR", null, { error: new Error("rate limited") }));
expect(container.textContent).toBe("");
act(() => onSync("SYNCING", null));
act(() => disconnected$.next(false));
expect(container.textContent).toBe("");
});
test("stays hidden without a provider", () => {
const { container } = render(<DisconnectedBanner />);
expect(container.textContent).toBe("");
});
+4 -37
View File
@@ -6,19 +6,11 @@ Please see LICENSE in the repository root for full details.
*/
import classNames from "classnames";
import {
type FC,
type HTMLAttributes,
type ReactNode,
useEffect,
useState,
} from "react";
import { type FC, type HTMLAttributes, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { ClientEvent, type MatrixClient } from "matrix-js-sdk";
import { type ISyncStateData, type SyncState } from "matrix-js-sdk/lib/sync";
import styles from "./DisconnectedBanner.module.css";
import { useClient } from "./ClientContext";
import { useDisconnected } from "./DisconnectedContext";
interface Props extends HTMLAttributes<HTMLElement> {
children?: ReactNode;
@@ -34,36 +26,11 @@ export const DisconnectedBanner: FC<Props> = ({
...rest
}) => {
const { t } = useTranslation();
const client = useClient();
// Tagged with the client it describes, so that a swapped client does not
// inherit the old one's verdict before its first sync
const [disconnected, setDisconnected] = useState<
[MatrixClient, boolean] | null
>(null);
useEffect(() => {
if (client === undefined) return;
const onSync = (
syncState: SyncState,
_old: SyncState | null,
data?: ISyncStateData,
): void => {
const clientIsDisconnected =
syncState === "ERROR" && data?.error?.name === "ConnectionError";
setDisconnected([client, clientIsDisconnected]);
};
client.on(ClientEvent.Sync, onSync);
return (): void => {
client.removeListener(ClientEvent.Sync, onSync);
};
}, [client]);
const shouldShowBanner =
disconnected !== null && disconnected[0] === client && disconnected[1];
const disconnected = useDisconnected();
return (
<>
{shouldShowBanner && (
{disconnected && (
<div className={classNames(styles.banner, className)} {...rest}>
{children}
{t("disconnected_banner")}
+20
View File
@@ -0,0 +1,20 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { createContext, use } from "react";
import { type Behavior, constant } from "./state/Behavior";
import { useBehavior } from "./useBehavior";
// Without a provider there is no client whose connection could fail
const DisconnectedContext = createContext<Behavior<boolean>>(constant(false));
export const DisconnectedProvider = DisconnectedContext.Provider;
/** Whether the signed-in client is failing to reach its homeserver. */
export const useDisconnected = (): boolean =>
useBehavior(use(DisconnectedContext));
+84
View File
@@ -0,0 +1,84 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { EventEmitter } from "events";
import { expect, test, vi } from "vitest";
import { BehaviorSubject } from "rxjs";
import { ClientEvent, type MatrixClient } from "matrix-js-sdk";
import { SyncState } from "matrix-js-sdk/lib/sync";
import { AppViewModel } from "./AppViewModel";
import { type ClientSessionState } from "./ClientSession";
import { testScope } from "../utils/test";
// The devices are beside the point here, and jsdom has none to enumerate
vi.mock("./MediaDevices", () => ({ MediaDevices: class {} }));
const connectionError = Object.assign(new Error("offline"), {
name: "ConnectionError",
});
const mockClient = (): MatrixClient =>
new EventEmitter() as unknown as MatrixClient;
const failSync = (client: MatrixClient, error = connectionError): boolean =>
client.emit(ClientEvent.Sync, SyncState.Error, null, { error });
const sync = (client: MatrixClient): boolean =>
client.emit(ClientEvent.Sync, SyncState.Syncing, null);
const signedIn = (client: MatrixClient): ClientSessionState => ({
state: "signedIn",
client,
passwordlessUser: false,
});
function build(state$: BehaviorSubject<ClientSessionState>): AppViewModel {
return new AppViewModel(
testScope(),
{ controlledAudioDevices: false },
{ state$ },
null,
);
}
test("is disconnected while the client's sync fails to connect", () => {
const client = mockClient();
const vm = build(new BehaviorSubject(signedIn(client)));
const seen: boolean[] = [];
vm.disconnected$.subscribe((d) => seen.push(d));
failSync(client);
// Any other failure is not a connection problem
failSync(client, new Error("rate limited"));
failSync(client);
sync(client);
expect(seen).toEqual([false, true, false, true, false]);
});
test("starts connected again when the client changes", () => {
const first = mockClient();
const state$ = new BehaviorSubject(signedIn(first));
const vm = build(state$);
failSync(first);
expect(vm.disconnected$.value).toBe(true);
state$.next(signedIn(mockClient()));
expect(vm.disconnected$.value).toBe(false);
// The old client is no longer listened to
failSync(first);
expect(vm.disconnected$.value).toBe(false);
});
test("is not disconnected when no one is signed in", () => {
const client = mockClient();
const state$ = new BehaviorSubject(signedIn(client));
const vm = build(state$);
failSync(client);
state$.next({ state: "signedOut" });
expect(vm.disconnected$.value).toBe(false);
});
+25
View File
@@ -5,6 +5,11 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { ClientEvent } from "matrix-js-sdk";
import { type ISyncStateData, type SyncState } from "matrix-js-sdk/lib/sync";
import { fromEvent, of, startWith, switchMap } from "rxjs";
import { type Behavior } from "./Behavior";
import { type ClientManager, type ClientSession } from "./ClientSession";
import { type AudioOutputOptions, MediaDevices } from "./MediaDevices";
import { type ObservableScope } from "./ObservableScope";
@@ -20,6 +25,26 @@ export class AppViewModel {
);
public readonly backgroundEffects = createAppBackgroundEffects$(this.scope);
/**
* Whether the signed-in client's sync is failing to reach the homeserver.
* False until its first sync, and whenever no one is signed in.
*/
public readonly disconnected$: Behavior<boolean> = this.scope.behavior(
this.clientSession.state$.pipe(
switchMap((state) =>
state.state === "signedIn"
? fromEvent(
state.client,
ClientEvent.Sync,
(syncState: SyncState, _old: unknown, data?: ISyncStateData) =>
syncState === "ERROR" &&
data?.error?.name === "ConnectionError",
).pipe(startWith(false))
: of(false),
),
),
);
// TODO: Move more application logic here. The CallViewModel, at the very
// least, ought to be accessible from this object.
+2 -2
View File
@@ -82,7 +82,7 @@ export function createStandaloneClientSession$(
const restoring$ = new BehaviorSubject<boolean>(true);
restore()
.then((clientData)=> clientData$.next(clientData))
.then((clientData) => clientData$.next(clientData))
.catch((e) => {
logger.error("Failed to restore the session", e);
error$.next(e);
@@ -164,7 +164,7 @@ export function createStandaloneClientSession$(
},
};
async function restore(): Promise<ClientData|undefined> {
async function restore(): Promise<ClientData | undefined> {
// The homeserver to restore against is in the config, which is loaded
// concurrently with this
await Config.init();