This repository was archived by the owner on Oct 22, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathRightPanelStore.ts
411 lines (367 loc) · 16.9 KB
/
RightPanelStore.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
/*
Copyright 2024 New Vector Ltd.
Copyright 2019-2023 The Matrix.org Foundation C.I.C.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
Please see LICENSE files in the repository root for full details.
*/
import { logger } from "matrix-js-sdk/src/logger";
import { CryptoEvent } from "matrix-js-sdk/src/crypto";
import { Optional } from "matrix-events-sdk";
import defaultDispatcher from "../../dispatcher/dispatcher";
import { pendingVerificationRequestForUser } from "../../verification";
import SettingsStore from "../../settings/SettingsStore";
import { RightPanelPhases } from "./RightPanelStorePhases";
import { SettingLevel } from "../../settings/SettingLevel";
import { UPDATE_EVENT } from "../AsyncStore";
import { ReadyWatchingStore } from "../ReadyWatchingStore";
import {
convertToStatePanel,
convertToStorePanel,
IRightPanelCard,
IRightPanelCardState,
IRightPanelForRoom,
} from "./RightPanelStoreIPanelState";
import { ActionPayload } from "../../dispatcher/payloads";
import { Action } from "../../dispatcher/actions";
import { ActiveRoomChangedPayload } from "../../dispatcher/payloads/ActiveRoomChangedPayload";
import { SdkContextClass } from "../../contexts/SDKContext";
import { MatrixClientPeg } from "../../MatrixClientPeg";
/**
* A class for tracking the state of the right panel between layouts and
* sessions. This state includes a history for each room. Each history element
* contains the phase (e.g. RightPanelPhase.RoomMemberInfo) and the state (e.g.
* the member) associated with it.
*/
export default class RightPanelStore extends ReadyWatchingStore {
private static internalInstance: RightPanelStore;
private global?: IRightPanelForRoom;
private byRoom: { [roomId: string]: IRightPanelForRoom } = {};
private viewedRoomId: Optional<string>;
private constructor() {
super(defaultDispatcher);
this.reset();
}
/**
* Resets the store. Intended for test usage only.
*/
public reset(): void {
this.global = undefined;
this.byRoom = {};
this.viewedRoomId = null;
}
protected async onReady(): Promise<any> {
this.viewedRoomId = SdkContextClass.instance.roomViewStore.getRoomId();
this.matrixClient?.on(CryptoEvent.VerificationRequestReceived, this.onVerificationRequestUpdate);
this.loadCacheFromSettings();
this.emitAndUpdateSettings();
}
protected async onNotReady(): Promise<any> {
this.matrixClient?.off(CryptoEvent.VerificationRequestReceived, this.onVerificationRequestUpdate);
}
protected onDispatcherAction(payload: ActionPayload): void {
switch (payload.action) {
case Action.ActiveRoomChanged: {
const changePayload = <ActiveRoomChangedPayload>payload;
this.handleViewedRoomChange(changePayload.oldRoomId, changePayload.newRoomId);
break;
}
case Action.FocusMessageSearch: {
if (this.currentCard.phase !== RightPanelPhases.RoomSummary) {
this.setCard({ phase: RightPanelPhases.RoomSummary, state: { focusRoomSearch: true } });
}
}
}
}
// Getters
/**
* If you are calling this from a component that already knows about a
* specific room from props / state, then it's best to prefer
* `isOpenForRoom` below to ensure all your data is for a single room
* during room changes.
*/
public get isOpen(): boolean {
return this.byRoom[this.viewedRoomId ?? ""]?.isOpen ?? false;
}
public isOpenForRoom(roomId: string): boolean {
return this.byRoom[roomId]?.isOpen ?? false;
}
public get roomPhaseHistory(): Array<IRightPanelCard> {
return this.byRoom[this.viewedRoomId ?? ""]?.history ?? [];
}
/**
* If you are calling this from a component that already knows about a
* specific room from props / state, then it's best to prefer
* `currentCardForRoom` below to ensure all your data is for a single room
* during room changes.
*/
public get currentCard(): IRightPanelCard {
const hist = this.roomPhaseHistory;
if (hist.length >= 1) {
return hist[hist.length - 1];
}
return { state: {}, phase: null };
}
public currentCardForRoom(roomId: string): IRightPanelCard {
const hist = this.byRoom[roomId]?.history ?? [];
if (hist.length > 0) {
return hist[hist.length - 1];
}
return { state: {}, phase: null };
}
public get previousCard(): IRightPanelCard {
const hist = this.roomPhaseHistory;
if (hist?.length >= 2) {
return hist[hist.length - 2];
}
return { state: {}, phase: null };
}
// Setters
public setCard(card: IRightPanelCard, allowClose = true, roomId?: string): void {
const rId = roomId ?? this.viewedRoomId ?? "";
// This function behaves as following:
// Update state: if the same phase is send but with a state
// Set right panel and erase history: if a "different to the current" phase is send (with or without a state)
// If the right panel is set, this function also shows the right panel.
const redirect = this.getVerificationRedirect(card);
const targetPhase = redirect?.phase ?? card.phase;
const cardState = redirect?.state ?? (Object.keys(card.state ?? {}).length === 0 ? null : card.state);
// Checks for wrong SetRightPanelPhase requests
if (!this.isPhaseValid(targetPhase, Boolean(rId))) return;
if (targetPhase === this.currentCardForRoom(rId)?.phase && !!cardState) {
// Update state: set right panel with a new state but keep the phase (don't know it this is ever needed...)
const hist = this.byRoom[rId]?.history ?? [];
hist[hist.length - 1].state = cardState;
this.emitAndUpdateSettings();
} else if (targetPhase !== this.currentCardForRoom(rId)?.phase || !this.byRoom[rId]) {
// Set right panel and initialize/erase history
const history = [{ phase: targetPhase, state: cardState ?? {} }];
this.byRoom[rId] = { history, isOpen: true };
this.emitAndUpdateSettings();
} else {
this.show(rId);
this.emitAndUpdateSettings();
}
}
public setCards(cards: IRightPanelCard[], allowClose = true, roomId: string | null = null): void {
// This function sets the history of the right panel and shows the right panel if not already visible.
const rId = roomId ?? this.viewedRoomId ?? "";
const history = cards.map((c) => ({ phase: c.phase, state: c.state ?? {} }));
this.byRoom[rId] = { history, isOpen: true };
this.show(rId);
this.emitAndUpdateSettings();
}
// Appends a card to the history and shows the right panel if not already visible
public pushCard(card: IRightPanelCard, allowClose = true, roomId: string | null = null): void {
const rId = roomId ?? this.viewedRoomId ?? "";
const redirect = this.getVerificationRedirect(card);
const targetPhase = redirect?.phase ?? card.phase;
const pState = redirect?.state ?? card.state ?? {};
// Checks for wrong SetRightPanelPhase requests
if (!this.isPhaseValid(targetPhase, Boolean(rId))) return;
const roomCache = this.byRoom[rId];
if (!!roomCache) {
// append new phase
roomCache.history.push({ state: pState, phase: targetPhase });
roomCache.isOpen = allowClose ? roomCache.isOpen : true;
} else {
// setup room panel cache with the new card
this.byRoom[rId] = {
history: [{ phase: targetPhase, state: pState }],
// if there was no right panel store object the the panel was closed -> keep it closed, except if allowClose==false
isOpen: !allowClose,
};
}
this.show(rId);
this.emitAndUpdateSettings();
}
public popCard(roomId: string | null = null): IRightPanelCard | undefined {
const rId = roomId ?? this.viewedRoomId ?? "";
if (!this.byRoom[rId]) return;
const removedCard = this.byRoom[rId].history.pop();
this.emitAndUpdateSettings();
return removedCard;
}
public togglePanel(roomId: string | null): void {
const rId = roomId ?? this.viewedRoomId ?? "";
if (!this.byRoom[rId]) return;
this.byRoom[rId].isOpen = !this.byRoom[rId].isOpen;
this.emitAndUpdateSettings();
}
public show(roomId: string | null): void {
if (!this.isOpenForRoom(roomId ?? this.viewedRoomId ?? "")) {
this.togglePanel(roomId);
}
}
public hide(roomId: string | null): void {
if (this.isOpenForRoom(roomId ?? this.viewedRoomId ?? "")) {
this.togglePanel(roomId);
}
}
/**
* Helper to show a right panel phase.
* If the UI is already showing that phase, the right panel will be hidden.
*
* Calling the same phase twice with a different state will update the current
* phase and push the old state in the right panel history.
* @param phase The right panel phase.
* @param cardState The state within the phase.
*/
public showOrHidePhase(phase: RightPanelPhases, cardState?: Partial<IRightPanelCardState>): void {
if (this.currentCard.phase == phase && !cardState && this.isOpen) {
this.togglePanel(null);
} else {
this.setCard({ phase, state: cardState });
if (!this.isOpen) this.togglePanel(null);
}
}
private loadCacheFromSettings(): void {
if (this.viewedRoomId) {
const room = this.mxClient?.getRoom(this.viewedRoomId);
if (!!room) {
this.global =
this.global ?? convertToStatePanel(SettingsStore.getValue("RightPanel.phasesGlobal"), room);
this.byRoom[this.viewedRoomId] =
this.byRoom[this.viewedRoomId] ??
convertToStatePanel(SettingsStore.getValue("RightPanel.phases", this.viewedRoomId), room);
} else {
logger.warn(
"Could not restore the right panel after load because there was no associated room object.",
);
}
}
}
private emitAndUpdateSettings(): void {
this.filterValidCards(this.global);
const storePanelGlobal = convertToStorePanel(this.global);
SettingsStore.setValue("RightPanel.phasesGlobal", null, SettingLevel.DEVICE, storePanelGlobal);
if (!!this.viewedRoomId) {
const panelThisRoom = this.byRoom[this.viewedRoomId];
this.filterValidCards(panelThisRoom);
const storePanelThisRoom = convertToStorePanel(panelThisRoom);
SettingsStore.setValue(
"RightPanel.phases",
this.viewedRoomId,
SettingLevel.ROOM_DEVICE,
storePanelThisRoom,
);
}
this.emit(UPDATE_EVENT, null);
}
private filterValidCards(rightPanelForRoom?: IRightPanelForRoom): void {
if (!rightPanelForRoom?.history) return;
rightPanelForRoom.history = rightPanelForRoom.history.filter((card) => this.isCardStateValid(card));
if (!rightPanelForRoom.history.length) {
rightPanelForRoom.isOpen = false;
}
}
private isCardStateValid(card: IRightPanelCard): boolean {
// this function does a sanity check on the card. this is required because
// some phases require specific state properties that might not be available.
// This can be caused on if element is reloaded and the tries to reload right panel data from id's stored in the local storage.
// we store id's of users and matrix events. If are not yet fetched on reload the right panel cannot display them.
// or potentially other errors.
// (A nicer fix could be to indicate, that the right panel is loading if there is missing state data and re-emit if the data is available)
switch (card.phase) {
case RightPanelPhases.ThreadView:
if (!card.state?.threadHeadEvent) {
logger.warn("removed card from right panel because of missing threadHeadEvent in card state");
}
return !!card.state?.threadHeadEvent;
case RightPanelPhases.RoomMemberInfo:
case RightPanelPhases.SpaceMemberInfo:
case RightPanelPhases.EncryptionPanel:
if (!card.state?.member) {
logger.warn("removed card from right panel because of missing member in card state");
}
return !!card.state?.member;
case RightPanelPhases.Room3pidMemberInfo:
case RightPanelPhases.Space3pidMemberInfo:
if (!card.state?.memberInfoEvent) {
logger.warn("removed card from right panel because of missing memberInfoEvent in card state");
}
return !!card.state?.memberInfoEvent;
case RightPanelPhases.Widget:
if (!card.state?.widgetId) {
logger.warn("removed card from right panel because of missing widgetId in card state");
}
return !!card.state?.widgetId;
}
return true;
}
private getVerificationRedirect(card: IRightPanelCard): IRightPanelCard | null {
if (card.phase === RightPanelPhases.RoomMemberInfo && card.state) {
// RightPanelPhases.RoomMemberInfo -> needs to be changed to RightPanelPhases.EncryptionPanel if there is a pending verification request
const { member } = card.state;
const pendingRequest = member
? pendingVerificationRequestForUser(MatrixClientPeg.safeGet(), member)
: undefined;
if (pendingRequest) {
return {
phase: RightPanelPhases.EncryptionPanel,
state: {
verificationRequest: pendingRequest,
member,
},
};
}
}
return null;
}
private isPhaseValid(targetPhase: RightPanelPhases | null, isViewingRoom: boolean): boolean {
if (!targetPhase || !RightPanelPhases[targetPhase]) {
logger.warn(`Tried to switch right panel to unknown phase: ${targetPhase}`);
return false;
}
if (!isViewingRoom) {
logger.warn(
`Tried to switch right panel to a room phase: ${targetPhase}, ` +
`but we are currently not viewing a room`,
);
return false;
}
return true;
}
private onVerificationRequestUpdate = (): void => {
if (!this.currentCard?.state) return;
const { member } = this.currentCard.state;
if (!member) return;
const pendingRequest = pendingVerificationRequestForUser(MatrixClientPeg.safeGet(), member);
if (pendingRequest) {
this.currentCard.state.verificationRequest = pendingRequest;
this.emitAndUpdateSettings();
}
};
private handleViewedRoomChange(oldRoomId: Optional<string>, newRoomId: Optional<string>): void {
if (!this.mxClient) return; // not ready, onReady will handle the first room
this.viewedRoomId = newRoomId;
// load values from byRoomCache with the viewedRoomId.
this.loadCacheFromSettings();
// when we're switching to a room, clear out any stale MemberInfo cards
// in order to fix https://github.com/vector-im/element-web/issues/21487
if (this.currentCard?.phase !== RightPanelPhases.EncryptionPanel) {
const panel = this.byRoom[this.viewedRoomId ?? ""];
if (panel?.history) {
panel.history = panel.history.filter(
(card: IRightPanelCard) =>
card.phase != RightPanelPhases.RoomMemberInfo &&
card.phase != RightPanelPhases.Room3pidMemberInfo,
);
}
}
// when we're switching to a room, clear out thread permalinks to not get you stuck in the middle of the thread
// in order to fix https://github.com/matrix-org/matrix-react-sdk/pull/11011
if (this.currentCard?.phase === RightPanelPhases.ThreadView && this.currentCard.state) {
this.currentCard.state.initialEvent = undefined;
this.currentCard.state.isInitialEventHighlighted = undefined;
this.currentCard.state.initialEventScrollIntoView = undefined;
}
this.emitAndUpdateSettings();
}
public static get instance(): RightPanelStore {
if (!this.internalInstance) {
this.internalInstance = new RightPanelStore();
}
return this.internalInstance;
}
}
window.mxRightPanelStore = RightPanelStore.instance;