Skip to content
This repository was archived by the owner on Sep 11, 2024. It is now read-only.

Commit 06c4ba3

Browse files
authored
Store refactor: make it easier to test stores (#9290)
* refactor: convert RoomViewStore from flux Store to standard EventEmitter Parts of a series of experimental changes to improve the design of stores. * Use a gen5 store for RoomViewStore for now due to lock handling * Revert "Use a gen5 store for RoomViewStore for now due to lock handling" This reverts commit 1076af0. * Add untilEmission and tweak untilDispatch; use it in RoomViewStore * Add more RVS tests; remove custom room ID listener code and use EventEmitter * Better comments * Null guard `dis` as tests mock out `defaultDispatcher` * Additional tests
1 parent 1f1a18f commit 06c4ba3

File tree

11 files changed

+289
-129
lines changed

11 files changed

+289
-129
lines changed

src/components/structures/RoomView.tsx

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ import React, { createRef, ReactElement, ReactNode, RefObject, useContext } from
2424
import classNames from 'classnames';
2525
import { IRecommendedVersion, NotificationCountType, Room, RoomEvent } from "matrix-js-sdk/src/models/room";
2626
import { IThreadBundledRelationship, MatrixEvent, MatrixEventEvent } from "matrix-js-sdk/src/models/event";
27-
import { EventSubscription } from "fbemitter";
2827
import { ISearchResults } from 'matrix-js-sdk/src/@types/search';
2928
import { logger } from "matrix-js-sdk/src/logger";
3029
import { EventTimeline } from 'matrix-js-sdk/src/models/event-timeline';
@@ -366,7 +365,6 @@ function LocalRoomCreateLoader(props: ILocalRoomCreateLoaderProps): ReactElement
366365

367366
export class RoomView extends React.Component<IRoomProps, IRoomState> {
368367
private readonly dispatcherRef: string;
369-
private readonly roomStoreToken: EventSubscription;
370368
private settingWatchers: string[];
371369

372370
private unmounted = false;
@@ -439,7 +437,7 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
439437
context.on(CryptoEvent.KeysChanged, this.onCrossSigningKeysChanged);
440438
context.on(MatrixEventEvent.Decrypted, this.onEventDecrypted);
441439
// Start listening for RoomViewStore updates
442-
this.roomStoreToken = RoomViewStore.instance.addListener(this.onRoomViewStoreUpdate);
440+
RoomViewStore.instance.on(UPDATE_EVENT, this.onRoomViewStoreUpdate);
443441

444442
RightPanelStore.instance.on(UPDATE_EVENT, this.onRightPanelStoreUpdate);
445443

@@ -883,10 +881,7 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
883881

884882
window.removeEventListener('beforeunload', this.onPageUnload);
885883

886-
// Remove RoomStore listener
887-
if (this.roomStoreToken) {
888-
this.roomStoreToken.remove();
889-
}
884+
RoomViewStore.instance.off(UPDATE_EVENT, this.onRoomViewStoreUpdate);
890885

891886
RightPanelStore.instance.off(UPDATE_EVENT, this.onRightPanelStoreUpdate);
892887
WidgetEchoStore.removeListener(UPDATE_EVENT, this.onWidgetEchoStoreUpdate);

src/components/views/right_panel/TimelineCard.tsx

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ limitations under the License.
1515
*/
1616

1717
import React from 'react';
18-
import { EventSubscription } from "fbemitter";
1918
import { IEventRelation, MatrixEvent } from 'matrix-js-sdk/src/models/event';
2019
import { EventTimelineSet } from 'matrix-js-sdk/src/models/event-timeline-set';
2120
import { NotificationCountType, Room } from 'matrix-js-sdk/src/models/room';
@@ -42,6 +41,7 @@ import JumpToBottomButton from '../rooms/JumpToBottomButton';
4241
import { ViewRoomPayload } from "../../../dispatcher/payloads/ViewRoomPayload";
4342
import Measured from '../elements/Measured';
4443
import Heading from '../typography/Heading';
44+
import { UPDATE_EVENT } from '../../../stores/AsyncStore';
4545

4646
interface IProps {
4747
room: Room;
@@ -77,7 +77,6 @@ export default class TimelineCard extends React.Component<IProps, IState> {
7777
private layoutWatcherRef: string;
7878
private timelinePanel = React.createRef<TimelinePanel>();
7979
private card = React.createRef<HTMLDivElement>();
80-
private roomStoreToken: EventSubscription;
8180
private readReceiptsSettingWatcher: string;
8281

8382
constructor(props: IProps) {
@@ -92,7 +91,7 @@ export default class TimelineCard extends React.Component<IProps, IState> {
9291
}
9392

9493
public componentDidMount(): void {
95-
this.roomStoreToken = RoomViewStore.instance.addListener(this.onRoomViewStoreUpdate);
94+
RoomViewStore.instance.addListener(UPDATE_EVENT, this.onRoomViewStoreUpdate);
9695
this.dispatcherRef = dis.register(this.onAction);
9796
this.readReceiptsSettingWatcher = SettingsStore.watchSetting("showReadReceipts", null, (...[,,, value]) =>
9897
this.setState({ showReadReceipts: value as boolean }),
@@ -103,9 +102,7 @@ export default class TimelineCard extends React.Component<IProps, IState> {
103102
}
104103

105104
public componentWillUnmount(): void {
106-
// Remove RoomStore listener
107-
108-
this.roomStoreToken?.remove();
105+
RoomViewStore.instance.removeListener(UPDATE_EVENT, this.onRoomViewStoreUpdate);
109106

110107
if (this.readReceiptsSettingWatcher) {
111108
SettingsStore.unwatchSetting(this.readReceiptsSettingWatcher);

src/components/views/rooms/RoomList.tsx

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ See the License for the specific language governing permissions and
1414
limitations under the License.
1515
*/
1616

17-
import * as fbEmitter from "fbemitter";
1817
import { EventType, RoomType } from "matrix-js-sdk/src/@types/event";
1918
import { Room } from "matrix-js-sdk/src/models/room";
2019
import React, { ComponentType, createRef, ReactComponentElement, RefObject } from "react";
@@ -37,6 +36,7 @@ import { UIComponent } from "../../../settings/UIFeature";
3736
import { RoomNotificationStateStore } from "../../../stores/notifications/RoomNotificationStateStore";
3837
import { ITagMap } from "../../../stores/room-list/algorithms/models";
3938
import { DefaultTagID, TagID } from "../../../stores/room-list/models";
39+
import { UPDATE_EVENT } from "../../../stores/AsyncStore";
4040
import RoomListStore, { LISTS_UPDATE_EVENT } from "../../../stores/room-list/RoomListStore";
4141
import { RoomViewStore } from "../../../stores/RoomViewStore";
4242
import {
@@ -403,7 +403,6 @@ const TAG_AESTHETICS: ITagAestheticsMap = {
403403

404404
export default class RoomList extends React.PureComponent<IProps, IState> {
405405
private dispatcherRef;
406-
private roomStoreToken: fbEmitter.EventSubscription;
407406
private treeRef = createRef<HTMLDivElement>();
408407
private favouriteMessageWatcher: string;
409408

@@ -422,7 +421,7 @@ export default class RoomList extends React.PureComponent<IProps, IState> {
422421

423422
public componentDidMount(): void {
424423
this.dispatcherRef = defaultDispatcher.register(this.onAction);
425-
this.roomStoreToken = RoomViewStore.instance.addListener(this.onRoomViewStoreUpdate);
424+
RoomViewStore.instance.on(UPDATE_EVENT, this.onRoomViewStoreUpdate);
426425
SpaceStore.instance.on(UPDATE_SUGGESTED_ROOMS, this.updateSuggestedRooms);
427426
RoomListStore.instance.on(LISTS_UPDATE_EVENT, this.updateLists);
428427
this.favouriteMessageWatcher =
@@ -437,7 +436,7 @@ export default class RoomList extends React.PureComponent<IProps, IState> {
437436
RoomListStore.instance.off(LISTS_UPDATE_EVENT, this.updateLists);
438437
SettingsStore.unwatchSetting(this.favouriteMessageWatcher);
439438
defaultDispatcher.unregister(this.dispatcherRef);
440-
if (this.roomStoreToken) this.roomStoreToken.remove();
439+
RoomViewStore.instance.off(UPDATE_EVENT, this.onRoomViewStoreUpdate);
441440
}
442441

443442
private onRoomViewStoreUpdate = () => {

src/components/views/voip/PipView.tsx

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ limitations under the License.
1616

1717
import React, { createRef } from 'react';
1818
import { CallEvent, CallState, MatrixCall } from 'matrix-js-sdk/src/webrtc/call';
19-
import { EventSubscription } from 'fbemitter';
2019
import { logger } from "matrix-js-sdk/src/logger";
2120
import classNames from 'classnames';
2221
import { Room } from "matrix-js-sdk/src/models/room";
@@ -35,6 +34,7 @@ import LegacyCallViewHeader from './LegacyCallView/LegacyCallViewHeader';
3534
import ActiveWidgetStore, { ActiveWidgetStoreEvent } from '../../../stores/ActiveWidgetStore';
3635
import WidgetStore, { IApp } from "../../../stores/WidgetStore";
3736
import { ViewRoomPayload } from "../../../dispatcher/payloads/ViewRoomPayload";
37+
import { UPDATE_EVENT } from '../../../stores/AsyncStore';
3838

3939
const SHOW_CALL_IN_STATES = [
4040
CallState.Connected,
@@ -116,7 +116,6 @@ function getPrimarySecondaryCallsForPip(roomId: string): [MatrixCall, MatrixCall
116116
*/
117117

118118
export default class PipView extends React.Component<IProps, IState> {
119-
private roomStoreToken: EventSubscription;
120119
private settingsWatcherRef: string;
121120
private movePersistedElement = createRef<() => void>();
122121

@@ -141,7 +140,7 @@ export default class PipView extends React.Component<IProps, IState> {
141140
public componentDidMount() {
142141
LegacyCallHandler.instance.addListener(LegacyCallHandlerEvent.CallChangeRoom, this.updateCalls);
143142
LegacyCallHandler.instance.addListener(LegacyCallHandlerEvent.CallState, this.updateCalls);
144-
this.roomStoreToken = RoomViewStore.instance.addListener(this.onRoomViewStoreUpdate);
143+
RoomViewStore.instance.addListener(UPDATE_EVENT, this.onRoomViewStoreUpdate);
145144
MatrixClientPeg.get().on(CallEvent.RemoteHoldUnhold, this.onCallRemoteHold);
146145
const room = MatrixClientPeg.get()?.getRoom(this.state.viewedRoomId);
147146
if (room) {
@@ -157,7 +156,7 @@ export default class PipView extends React.Component<IProps, IState> {
157156
LegacyCallHandler.instance.removeListener(LegacyCallHandlerEvent.CallChangeRoom, this.updateCalls);
158157
LegacyCallHandler.instance.removeListener(LegacyCallHandlerEvent.CallState, this.updateCalls);
159158
MatrixClientPeg.get().removeListener(CallEvent.RemoteHoldUnhold, this.onCallRemoteHold);
160-
this.roomStoreToken?.remove();
159+
RoomViewStore.instance.removeListener(UPDATE_EVENT, this.onRoomViewStoreUpdate);
161160
SettingsStore.unwatchSetting(this.settingsWatcherRef);
162161
const room = MatrixClientPeg.get().getRoom(this.state.viewedRoomId);
163162
if (room) {

src/stores/RoomViewStore.tsx

Lines changed: 45 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ limitations under the License.
1717
*/
1818

1919
import React, { ReactNode } from "react";
20-
import { Store } from 'flux/utils';
2120
import { MatrixError } from "matrix-js-sdk/src/http-api";
2221
import { logger } from "matrix-js-sdk/src/logger";
2322
import { ViewRoom as ViewRoomEvent } from "@matrix-org/analytics-events/types/typescript/ViewRoom";
@@ -26,13 +25,13 @@ import { JoinRule } from "matrix-js-sdk/src/@types/partials";
2625
import { Room } from "matrix-js-sdk/src/models/room";
2726
import { MatrixEvent } from "matrix-js-sdk/src/models/event";
2827
import { Optional } from "matrix-events-sdk";
28+
import EventEmitter from "events";
2929

30-
import dis from '../dispatcher/dispatcher';
30+
import { defaultDispatcher, MatrixDispatcher } from '../dispatcher/dispatcher';
3131
import { MatrixClientPeg } from '../MatrixClientPeg';
3232
import Modal from '../Modal';
3333
import { _t } from '../languageHandler';
3434
import { getCachedRoomIDForAlias, storeRoomAliasInCache } from '../RoomAliasCache';
35-
import { ActionPayload } from "../dispatcher/payloads";
3635
import { Action } from "../dispatcher/actions";
3736
import { retry } from "../utils/promise";
3837
import { TimelineRenderingType } from "../contexts/RoomContext";
@@ -50,6 +49,7 @@ import { ActiveRoomChangedPayload } from "../dispatcher/payloads/ActiveRoomChang
5049
import SettingsStore from "../settings/SettingsStore";
5150
import { SlidingSyncManager } from "../SlidingSyncManager";
5251
import { awaitRoomDownSync } from "../utils/RoomUpgrade";
52+
import { UPDATE_EVENT } from "./AsyncStore";
5353

5454
const NUM_JOIN_RETRY = 5;
5555

@@ -90,47 +90,34 @@ const INITIAL_STATE = {
9090
type Listener = (isActive: boolean) => void;
9191

9292
/**
93-
* A class for storing application state for RoomView. This is the RoomView's interface
94-
* with a subset of the js-sdk.
95-
* ```
93+
* A class for storing application state for RoomView.
9694
*/
97-
export class RoomViewStore extends Store<ActionPayload> {
95+
export class RoomViewStore extends EventEmitter {
9896
// Important: This cannot be a dynamic getter (lazily-constructed instance) because
9997
// otherwise we'll miss view_room dispatches during startup, breaking relaunches of
10098
// the app. We need to eagerly create the instance.
101-
public static readonly instance = new RoomViewStore();
99+
public static readonly instance = new RoomViewStore(defaultDispatcher);
102100

103101
private state = INITIAL_STATE; // initialize state
104102

105-
// Keep these out of state to avoid causing excessive/recursive updates
106-
private roomIdActivityListeners: Record<string, Listener[]> = {};
103+
private dis: MatrixDispatcher;
104+
private dispatchToken: string;
107105

108-
public constructor() {
109-
super(dis);
106+
public constructor(dis: MatrixDispatcher) {
107+
super();
108+
this.resetDispatcher(dis);
110109
}
111110

112111
public addRoomListener(roomId: string, fn: Listener): void {
113-
if (!this.roomIdActivityListeners[roomId]) this.roomIdActivityListeners[roomId] = [];
114-
this.roomIdActivityListeners[roomId].push(fn);
112+
this.on(roomId, fn);
115113
}
116114

117115
public removeRoomListener(roomId: string, fn: Listener): void {
118-
if (this.roomIdActivityListeners[roomId]) {
119-
const i = this.roomIdActivityListeners[roomId].indexOf(fn);
120-
if (i > -1) {
121-
this.roomIdActivityListeners[roomId].splice(i, 1);
122-
}
123-
} else {
124-
logger.warn("Unregistering unrecognised listener (roomId=" + roomId + ")");
125-
}
116+
this.off(roomId, fn);
126117
}
127118

128119
private emitForRoom(roomId: string, isActive: boolean): void {
129-
if (!this.roomIdActivityListeners[roomId]) return;
130-
131-
for (const fn of this.roomIdActivityListeners[roomId]) {
132-
fn.call(null, isActive);
133-
}
120+
this.emit(roomId, isActive);
134121
}
135122

136123
private setState(newState: Partial<typeof INITIAL_STATE>): void {
@@ -156,17 +143,17 @@ export class RoomViewStore extends Store<ActionPayload> {
156143

157144
// Fired so we can reduce dependency on event emitters to this store, which is relatively
158145
// central to the application and can easily cause import cycles.
159-
dis.dispatch<ActiveRoomChangedPayload>({
146+
this.dis.dispatch<ActiveRoomChangedPayload>({
160147
action: Action.ActiveRoomChanged,
161148
oldRoomId: lastRoomId,
162149
newRoomId: this.state.roomId,
163150
});
164151
}
165152

166-
this.__emitChange();
153+
this.emit(UPDATE_EVENT);
167154
}
168155

169-
protected __onDispatch(payload): void { // eslint-disable-line @typescript-eslint/naming-convention
156+
private onDispatch(payload): void { // eslint-disable-line @typescript-eslint/naming-convention
170157
switch (payload.action) {
171158
// view_room:
172159
// - room_alias: '#somealias:matrix.org'
@@ -243,7 +230,7 @@ export class RoomViewStore extends Store<ActionPayload> {
243230
// both room and search timeline rendering types, search will get auto-closed by RoomView at this time.
244231
if ([TimelineRenderingType.Room, TimelineRenderingType.Search].includes(payload.context)) {
245232
if (payload.event && payload.event.getRoomId() !== this.state.roomId) {
246-
dis.dispatch<ViewRoomPayload>({
233+
this.dis.dispatch<ViewRoomPayload>({
247234
action: Action.ViewRoom,
248235
room_id: payload.event.getRoomId(),
249236
replyingToEvent: payload.event,
@@ -283,9 +270,9 @@ export class RoomViewStore extends Store<ActionPayload> {
283270
});
284271
}
285272
if (SettingsStore.getValue("feature_sliding_sync") && this.state.roomId !== payload.room_id) {
286-
if (this.state.roomId) {
273+
if (this.state.subscribingRoomId && this.state.subscribingRoomId !== payload.room_id) {
287274
// unsubscribe from this room, but don't await it as we don't care when this gets done.
288-
SlidingSyncManager.instance.setRoomVisible(this.state.roomId, false);
275+
SlidingSyncManager.instance.setRoomVisible(this.state.subscribingRoomId, false);
289276
}
290277
this.setState({
291278
subscribingRoomId: payload.room_id,
@@ -306,11 +293,11 @@ export class RoomViewStore extends Store<ActionPayload> {
306293
// Whilst we were subscribing another room was viewed, so stop what we're doing and
307294
// unsubscribe
308295
if (this.state.subscribingRoomId !== payload.room_id) {
309-
SlidingSyncManager.instance.setRoomVisible(this.state.roomId, false);
296+
SlidingSyncManager.instance.setRoomVisible(payload.room_id, false);
310297
return;
311298
}
312299
// Re-fire the payload: we won't re-process it because the prev room ID == payload room ID now
313-
dis.dispatch({
300+
this.dis.dispatch({
314301
...payload,
315302
});
316303
return;
@@ -346,7 +333,7 @@ export class RoomViewStore extends Store<ActionPayload> {
346333
this.setState(newState);
347334

348335
if (payload.auto_join) {
349-
dis.dispatch<JoinRoomPayload>({
336+
this.dis.dispatch<JoinRoomPayload>({
350337
...payload,
351338
action: Action.JoinRoom,
352339
roomId: payload.room_id,
@@ -378,7 +365,7 @@ export class RoomViewStore extends Store<ActionPayload> {
378365
roomId = result.room_id;
379366
} catch (err) {
380367
logger.error("RVS failed to get room id for alias: ", err);
381-
dis.dispatch<ViewRoomErrorPayload>({
368+
this.dis.dispatch<ViewRoomErrorPayload>({
382369
action: Action.ViewRoomError,
383370
room_id: null,
384371
room_alias: payload.room_alias,
@@ -389,7 +376,7 @@ export class RoomViewStore extends Store<ActionPayload> {
389376
}
390377

391378
// Re-fire the payload with the newly found room_id
392-
dis.dispatch({
379+
this.dis.dispatch({
393380
...payload,
394381
room_id: roomId,
395382
});
@@ -427,13 +414,13 @@ export class RoomViewStore extends Store<ActionPayload> {
427414
// We do *not* clear the 'joining' flag because the Room object and/or our 'joined' member event may not
428415
// have come down the sync stream yet, and that's the point at which we'd consider the user joined to the
429416
// room.
430-
dis.dispatch<JoinRoomReadyPayload>({
417+
this.dis.dispatch<JoinRoomReadyPayload>({
431418
action: Action.JoinRoomReady,
432419
roomId,
433420
metricsTrigger: payload.metricsTrigger,
434421
});
435422
} catch (err) {
436-
dis.dispatch({
423+
this.dis.dispatch({
437424
action: Action.JoinRoomError,
438425
roomId,
439426
err,
@@ -493,6 +480,24 @@ export class RoomViewStore extends Store<ActionPayload> {
493480
this.state = Object.assign({}, INITIAL_STATE);
494481
}
495482

483+
/**
484+
* Reset which dispatcher should be used to listen for actions. The old dispatcher will be
485+
* unregistered.
486+
* @param dis The new dispatcher to use.
487+
*/
488+
public resetDispatcher(dis: MatrixDispatcher) {
489+
if (this.dispatchToken) {
490+
this.dis.unregister(this.dispatchToken);
491+
}
492+
this.dis = dis;
493+
if (dis) {
494+
// Some tests mock the dispatcher file resulting in an empty defaultDispatcher
495+
// so rather than dying here, just ignore it. When we no longer mock files like this,
496+
// we should remove the null check.
497+
this.dispatchToken = this.dis.register(this.onDispatch.bind(this));
498+
}
499+
}
500+
496501
// The room ID of the room currently being viewed
497502
public getRoomId(): Optional<string> {
498503
return this.state.roomId;

src/stores/room-list/RoomListStore.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ import { SpaceWatcher } from "./SpaceWatcher";
3939
import { IRoomTimelineActionPayload } from "../../actions/MatrixActionCreators";
4040
import { RoomListStore as Interface, RoomListStoreEvent } from "./Interface";
4141
import { SlidingRoomListStoreClass } from "./SlidingRoomListStore";
42+
import { UPDATE_EVENT } from "../AsyncStore";
4243

4344
interface IState {
4445
// state is tracked in underlying classes
@@ -104,7 +105,7 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> implements
104105
this.readyStore.useUnitTestClient(forcedClient);
105106
}
106107

107-
RoomViewStore.instance.addListener(() => this.handleRVSUpdate({}));
108+
RoomViewStore.instance.addListener(UPDATE_EVENT, () => this.handleRVSUpdate({}));
108109
this.algorithm.on(LIST_UPDATED_EVENT, this.onAlgorithmListUpdated);
109110
this.algorithm.on(FILTER_CHANGED, this.onAlgorithmFilterUpdated);
110111
this.setupWatchers();

0 commit comments

Comments
 (0)