From 805f64aec5e13ecfa67a832ee2ffed56ca3f70df Mon Sep 17 00:00:00 2001 From: "Timo K." Date: Mon, 23 Nov 2026 15:59:44 +0100 Subject: [PATCH] refactor disconnectedBanner to use a custom context + app view model logic. --- src/App.tsx | 71 ++++++++++++----------- src/DisconnectedBanner.test.tsx | 38 +++++-------- src/DisconnectedBanner.tsx | 41 ++------------ src/DisconnectedContext.ts | 20 +++++++ src/state/AppViewModel.test.ts | 84 ++++++++++++++++++++++++++++ src/state/AppViewModel.ts | 25 +++++++++ src/state/StandaloneClientSession.ts | 4 +- 7 files changed, 187 insertions(+), 96 deletions(-) create mode 100644 src/DisconnectedContext.ts create mode 100644 src/state/AppViewModel.test.ts diff --git a/src/App.tsx b/src/App.tsx index 1e26cc7bd..4ac124dad 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -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 = ({ vm, widget }) => { }); const content = loaded ? ( - - - - } - > - - } - /> - {/* A host's session is signed in to by the host, never here */} - {vm.clientManager !== null && ( - <> - } - /> - } - /> - - )} - } - /> - - - - - + + + + + } + > + + } + /> + {/* A host's session is signed in to by the host, never here */} + {vm.clientManager !== null && ( + <> + } + /> + + } + /> + + )} + } + /> + + + + + + ) : ( ); diff --git a/src/DisconnectedBanner.test.tsx b/src/DisconnectedBanner.test.tsx index 309a4f710..3c04a3793 100644 --- a/src/DisconnectedBanner.test.tsx +++ b/src/DisconnectedBanner.test.tsx @@ -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 as MatrixClient; +test("shows while the client is disconnected", () => { + const disconnected$ = new BehaviorSubject(false); const { container } = render( - + - , + , ); 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(); expect(container.textContent).toBe(""); }); diff --git a/src/DisconnectedBanner.tsx b/src/DisconnectedBanner.tsx index f2484fd64..d723432f8 100644 --- a/src/DisconnectedBanner.tsx +++ b/src/DisconnectedBanner.tsx @@ -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 { children?: ReactNode; @@ -34,36 +26,11 @@ export const DisconnectedBanner: FC = ({ ...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 && (
{children} {t("disconnected_banner")} diff --git a/src/DisconnectedContext.ts b/src/DisconnectedContext.ts new file mode 100644 index 000000000..6d281ad85 --- /dev/null +++ b/src/DisconnectedContext.ts @@ -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>(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)); diff --git a/src/state/AppViewModel.test.ts b/src/state/AppViewModel.test.ts new file mode 100644 index 000000000..2ca15f0f2 --- /dev/null +++ b/src/state/AppViewModel.test.ts @@ -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): 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); +}); diff --git a/src/state/AppViewModel.ts b/src/state/AppViewModel.ts index d505f77c1..c0b6a8d69 100644 --- a/src/state/AppViewModel.ts +++ b/src/state/AppViewModel.ts @@ -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 = 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. diff --git a/src/state/StandaloneClientSession.ts b/src/state/StandaloneClientSession.ts index 0dbb47c65..ea5fd4121 100644 --- a/src/state/StandaloneClientSession.ts +++ b/src/state/StandaloneClientSession.ts @@ -82,7 +82,7 @@ export function createStandaloneClientSession$( const restoring$ = new BehaviorSubject(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 { + async function restore(): Promise { // The homeserver to restore against is in the config, which is loaded // concurrently with this await Config.init();