Experimental Module API Additions (#30863)
* Module API experiments * Move ResizerNotifier into SDKContext so we don't have to pass it into RoomView * Add the MultiRoomViewStore * Make RoomViewStore able to take a roomId prop * Different interface to add space panel items A bit less flexible but probably simpler and will help keep things actually consistent rather than just allowing modules to stick any JSX into the space panel (which means they also have to worry about styling if they *do* want it to be consistent). * Allow space panel items to be updated and manage which one is selected, allowing module "spaces" to be considered spaces * Remove fetchRoomFn from SpaceNotificationStore which didn't really seem to have any point as it was only called from one place * Switch to using module api via .instance * Fairly awful workaround to actually break the dependency nightmare * Add test for multiroomviewstore * add test * Make room names deterministic So the tests don't fail if you add other tests or run them individually * Add test for builtinsapi * Update module api * RVS is not needed as prop anymore Since it's passed through context * Add roomId to prop * Remove RoomViewStore from state This is now accessed through class field * Fix test * No need to pass RVS from LoggedInView * Add RoomContextType * Implement new builtins api * Add tests * Fix import * Fix circular dependency issue * Fix import * Add more tests * Improve comment * room-id is optional * Update license * Add implementation for AccountDataApi * Add implementation for Room * Add implementation for ClientApi * Create ClientApi in Api.ts * Write tests * Use nullish coalescing assignment * Implement openRoom in NavigationApi * Write tests * Add implementation for StoresApi * Write tests * Fix circular dependency * Add comments in lieu of type and fix else block * Change to class field --------- Co-authored-by: R Midhun Suresh <hi@midhun.dev>
This commit is contained in:
@@ -31,7 +31,7 @@ const notLoggedInMap: Record<Exclude<Views, Views.LOGGED_IN>, ScreenName> = {
|
||||
[Views.LOCK_STOLEN]: "SessionLockStolen",
|
||||
};
|
||||
|
||||
const loggedInPageTypeMap: Record<PageType, ScreenName> = {
|
||||
const loggedInPageTypeMap: Record<PageType | string, ScreenName> = {
|
||||
[PageType.HomePage]: "Home",
|
||||
[PageType.RoomView]: "Room",
|
||||
[PageType.UserView]: "User",
|
||||
@@ -48,10 +48,10 @@ export default class PosthogTrackers {
|
||||
}
|
||||
|
||||
private view: Views = Views.LOADING;
|
||||
private pageType?: PageType;
|
||||
private pageType?: PageType | string;
|
||||
private override?: ScreenName;
|
||||
|
||||
public trackPageChange(view: Views, pageType: PageType | undefined, durationMs: number): void {
|
||||
public trackPageChange(view: Views, pageType: PageType | string | undefined, durationMs: number): void {
|
||||
this.view = view;
|
||||
this.pageType = pageType;
|
||||
if (this.override) return;
|
||||
|
||||
@@ -68,7 +68,8 @@ import { monitorSyncedPushRules } from "../../utils/pushRules/monitorSyncedPushR
|
||||
import { type ConfigOptions } from "../../SdkConfig";
|
||||
import { MatrixClientContextProvider } from "./MatrixClientContextProvider";
|
||||
import { Landmark, LandmarkNavigation } from "../../accessibility/LandmarkNavigation";
|
||||
import { SDKContext, SdkContextClass } from "../../contexts/SDKContext.ts";
|
||||
import { ModuleApi } from "../../modules/Api.ts";
|
||||
import { SDKContext } from "../../contexts/SDKContext.ts";
|
||||
|
||||
// We need to fetch each pinned message individually (if we don't already have it)
|
||||
// so each pinned message may trigger a request. Limit the number per room for sanity.
|
||||
@@ -679,6 +680,10 @@ class LoggedInView extends React.Component<IProps, IState> {
|
||||
public render(): React.ReactNode {
|
||||
let pageElement;
|
||||
|
||||
const moduleRenderer = this.props.page_type
|
||||
? ModuleApi.instance.navigation.locationRenderers.get(this.props.page_type)
|
||||
: undefined;
|
||||
|
||||
switch (this.props.page_type) {
|
||||
case PageTypes.RoomView:
|
||||
pageElement = (
|
||||
@@ -690,7 +695,6 @@ class LoggedInView extends React.Component<IProps, IState> {
|
||||
key={this.props.currentRoomId || "roomview"}
|
||||
justCreatedOpts={this.props.roomJustCreatedOpts}
|
||||
forceTimeline={this.props.forceTimeline}
|
||||
roomViewStore={SdkContextClass.instance.roomViewStore}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
@@ -706,6 +710,13 @@ class LoggedInView extends React.Component<IProps, IState> {
|
||||
);
|
||||
}
|
||||
break;
|
||||
default: {
|
||||
if (moduleRenderer) {
|
||||
pageElement = moduleRenderer();
|
||||
} else {
|
||||
console.warn(`Couldn't render page type "${this.props.page_type}"`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const wrapperClasses = classNames({
|
||||
@@ -747,20 +758,22 @@ class LoggedInView extends React.Component<IProps, IState> {
|
||||
)}
|
||||
<SpacePanel />
|
||||
{!useNewRoomList && <BackdropPanel backgroundImage={this.state.backgroundImage} />}
|
||||
<div
|
||||
className="mx_LeftPanel_wrapper--user"
|
||||
ref={this._resizeContainer}
|
||||
data-collapsed={shouldUseMinimizedUI ? true : undefined}
|
||||
>
|
||||
<LeftPanel
|
||||
pageType={this.props.page_type as PageTypes}
|
||||
isMinimized={shouldUseMinimizedUI || false}
|
||||
resizeNotifier={this.context.resizeNotifier}
|
||||
/>
|
||||
</div>
|
||||
{!moduleRenderer && (
|
||||
<div
|
||||
className="mx_LeftPanel_wrapper--user"
|
||||
ref={this._resizeContainer}
|
||||
data-collapsed={shouldUseMinimizedUI ? true : undefined}
|
||||
>
|
||||
<LeftPanel
|
||||
pageType={this.props.page_type as PageTypes}
|
||||
isMinimized={shouldUseMinimizedUI || false}
|
||||
resizeNotifier={this.context.resizeNotifier}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<ResizeHandle passRef={this.resizeHandler} id="lp-resizer" />
|
||||
{!moduleRenderer && <ResizeHandle passRef={this.resizeHandler} id="lp-resizer" />}
|
||||
<div className="mx_RoomView_wrapper">{pageElement}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -140,6 +140,7 @@ import { ShareFormat, type SharePayload } from "../../dispatcher/payloads/ShareP
|
||||
import Markdown from "../../Markdown";
|
||||
import { sanitizeHtmlParams } from "../../Linkify";
|
||||
import { isOnlyAdmin } from "../../utils/membership";
|
||||
import { ModuleApi } from "../../modules/Api.ts";
|
||||
|
||||
// legacy export
|
||||
export { default as Views } from "../../Views";
|
||||
@@ -175,9 +176,11 @@ interface IProps {
|
||||
interface IState {
|
||||
// the master view we are showing.
|
||||
view: Views;
|
||||
// What the LoggedInView would be showing if visible
|
||||
// What the LoggedInView would be showing if visible.
|
||||
// A member of the enum for standard pages or a string for those provided by
|
||||
// a module.
|
||||
// eslint-disable-next-line camelcase
|
||||
page_type?: PageType;
|
||||
page_type?: PageType | string;
|
||||
// The ID of the room we're viewing. This is either populated directly
|
||||
// in the case where we view a room by ID or by RoomView when it resolves
|
||||
// what ID an alias points at.
|
||||
@@ -1921,8 +1924,8 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
|
||||
userId: userId,
|
||||
subAction: params?.action,
|
||||
});
|
||||
} else {
|
||||
logger.info(`Ignoring showScreen for '${screen}'`);
|
||||
} else if (ModuleApi.instance.navigation.locationRenderers.get(screen)) {
|
||||
this.setState({ page_type: screen });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -44,6 +44,7 @@ import { type CallState, type MatrixCall } from "matrix-js-sdk/src/webrtc/call";
|
||||
import { debounce, throttle } from "lodash";
|
||||
import { CryptoEvent } from "matrix-js-sdk/src/crypto-api";
|
||||
import { type ViewRoomOpts } from "@matrix-org/react-sdk-module-api/lib/lifecycles/RoomViewLifecycle";
|
||||
import { type RoomViewProps } from "@element-hq/element-web-module-api";
|
||||
|
||||
import shouldHideEvent from "../../shouldHideEvent";
|
||||
import { _t } from "../../languageHandler";
|
||||
@@ -148,7 +149,7 @@ if (DEBUG) {
|
||||
debuglog = logger.log.bind(console);
|
||||
}
|
||||
|
||||
interface IRoomProps {
|
||||
interface IRoomProps extends RoomViewProps {
|
||||
threepidInvite?: IThreepidInvite;
|
||||
oobData?: IOOBData;
|
||||
|
||||
@@ -158,19 +159,17 @@ interface IRoomProps {
|
||||
|
||||
// Called with the credentials of a registered user (if they were a ROU that transitioned to PWLU)
|
||||
onRegistered?(credentials: IMatrixClientCreds): void;
|
||||
|
||||
/**
|
||||
* The RoomViewStore instance for the room to be displayed.
|
||||
* Only necessary if RoomView should get it's RoomViewStore through the MultiRoomViewStore.
|
||||
* Omitting this will mean that RoomView renders for the room held in SDKContext.RoomViewStore.
|
||||
*/
|
||||
roomViewStore: RoomViewStore;
|
||||
roomId?: string;
|
||||
}
|
||||
|
||||
export { MainSplitContentType };
|
||||
|
||||
export interface IRoomState {
|
||||
/**
|
||||
* The RoomViewStore instance for the room we are displaying
|
||||
*/
|
||||
roomViewStore: RoomViewStore;
|
||||
room?: Room;
|
||||
roomId?: string;
|
||||
roomAlias?: string;
|
||||
@@ -389,6 +388,8 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
|
||||
private messagePanel: TimelinePanel | null = null;
|
||||
private roomViewBody = createRef<HTMLDivElement>();
|
||||
|
||||
private roomViewStore: RoomViewStore;
|
||||
|
||||
public static contextType = SDKContext;
|
||||
declare public context: React.ContextType<typeof SDKContext>;
|
||||
|
||||
@@ -401,9 +402,14 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
|
||||
throw new Error("Unable to create RoomView without MatrixClient");
|
||||
}
|
||||
|
||||
if (props.roomId) {
|
||||
this.roomViewStore = this.context.multiRoomViewStore.getRoomViewStoreForRoom(props.roomId);
|
||||
} else {
|
||||
this.roomViewStore = context.roomViewStore;
|
||||
}
|
||||
|
||||
const llMembers = context.client.hasLazyLoadMembersEnabled();
|
||||
this.state = {
|
||||
roomViewStore: props.roomViewStore,
|
||||
roomId: undefined,
|
||||
roomLoading: true,
|
||||
peekLoading: false,
|
||||
@@ -535,7 +541,7 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
|
||||
};
|
||||
|
||||
private getMainSplitContentType = (room: Room): MainSplitContentType => {
|
||||
if (this.state.roomViewStore.isViewingCall() || isVideoRoom(room)) {
|
||||
if (this.roomViewStore.isViewingCall() || isVideoRoom(room)) {
|
||||
return MainSplitContentType.Call;
|
||||
}
|
||||
if (this.context.widgetLayoutStore.hasMaximisedWidget(room)) {
|
||||
@@ -549,8 +555,8 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
|
||||
return;
|
||||
}
|
||||
|
||||
const roomLoadError = this.state.roomViewStore.getRoomLoadError() ?? undefined;
|
||||
if (!initial && !roomLoadError && this.state.roomId !== this.state.roomViewStore.getRoomId()) {
|
||||
const roomLoadError = this.roomViewStore.getRoomLoadError() ?? undefined;
|
||||
if (!initial && !roomLoadError && this.state.roomId !== this.roomViewStore.getRoomId()) {
|
||||
// RoomView explicitly does not support changing what room
|
||||
// is being viewed: instead it should just be re-mounted when
|
||||
// switching rooms. Therefore, if the room ID changes, we
|
||||
@@ -564,7 +570,7 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
|
||||
// it was, it means we're about to be unmounted.
|
||||
return;
|
||||
}
|
||||
const roomViewStore = this.state.roomViewStore;
|
||||
const roomViewStore = this.roomViewStore;
|
||||
const roomId = roomViewStore.getRoomId() ?? null;
|
||||
const roomAlias = roomViewStore.getRoomAlias() ?? undefined;
|
||||
const roomLoading = roomViewStore.isRoomLoading();
|
||||
@@ -611,7 +617,7 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
|
||||
newState.showRightPanel = false;
|
||||
}
|
||||
|
||||
const initialEventId = this.state.roomViewStore.getInitialEventId() ?? this.state.initialEventId;
|
||||
const initialEventId = this.roomViewStore.getInitialEventId() ?? this.state.initialEventId;
|
||||
if (initialEventId) {
|
||||
let initialEvent = room?.findEventById(initialEventId);
|
||||
// The event does not exist in the current sync data
|
||||
@@ -637,13 +643,13 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
|
||||
action: Action.ShowThread,
|
||||
rootEvent: thread.rootEvent,
|
||||
initialEvent,
|
||||
highlighted: this.state.roomViewStore.isInitialEventHighlighted(),
|
||||
scroll_into_view: this.state.roomViewStore.initialEventScrollIntoView(),
|
||||
highlighted: this.roomViewStore.isInitialEventHighlighted(),
|
||||
scroll_into_view: this.roomViewStore.initialEventScrollIntoView(),
|
||||
});
|
||||
} else {
|
||||
newState.initialEventId = initialEventId;
|
||||
newState.isInitialEventHighlighted = this.state.roomViewStore.isInitialEventHighlighted();
|
||||
newState.initialEventScrollIntoView = this.state.roomViewStore.initialEventScrollIntoView();
|
||||
newState.isInitialEventHighlighted = this.roomViewStore.isInitialEventHighlighted();
|
||||
newState.initialEventScrollIntoView = this.roomViewStore.initialEventScrollIntoView();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -903,7 +909,7 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
|
||||
this.context.client.on(MatrixEventEvent.Decrypted, this.onEventDecrypted);
|
||||
}
|
||||
// Start listening for RoomViewStore updates
|
||||
this.state.roomViewStore.on(UPDATE_EVENT, this.onRoomViewStoreUpdate);
|
||||
this.roomViewStore.on(UPDATE_EVENT, this.onRoomViewStoreUpdate);
|
||||
|
||||
this.context.rightPanelStore.on(UPDATE_EVENT, this.onRightPanelStoreUpdate);
|
||||
|
||||
@@ -1020,7 +1026,7 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
|
||||
|
||||
window.removeEventListener("beforeunload", this.onPageUnload);
|
||||
|
||||
this.state.roomViewStore.off(UPDATE_EVENT, this.onRoomViewStoreUpdate);
|
||||
this.roomViewStore.off(UPDATE_EVENT, this.onRoomViewStoreUpdate);
|
||||
|
||||
this.context.rightPanelStore.off(UPDATE_EVENT, this.onRightPanelStoreUpdate);
|
||||
WidgetEchoStore.removeListener(UPDATE_EVENT, this.onWidgetEchoStoreUpdate);
|
||||
@@ -1048,6 +1054,8 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
|
||||
// clean up if this was a local room
|
||||
this.context.client?.store.removeRoom(this.state.room.roomId);
|
||||
}
|
||||
|
||||
if (this.props.roomId) this.context.multiRoomViewStore.removeRoomViewStore(this.props.roomId);
|
||||
}
|
||||
|
||||
private onRightPanelStoreUpdate = (): void => {
|
||||
@@ -2070,7 +2078,7 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
|
||||
if (!this.state.room || !this.context?.client) return null;
|
||||
const names = this.state.room.getDefaultRoomName(this.context.client.getSafeUserId());
|
||||
return (
|
||||
<ScopedRoomContextProvider {...this.state}>
|
||||
<ScopedRoomContextProvider {...this.state} roomViewStore={this.roomViewStore}>
|
||||
<LocalRoomCreateLoader
|
||||
localRoom={localRoom}
|
||||
names={names}
|
||||
@@ -2082,7 +2090,7 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
|
||||
|
||||
private renderLocalRoomView(localRoom: LocalRoom): ReactNode {
|
||||
return (
|
||||
<ScopedRoomContextProvider {...this.state}>
|
||||
<ScopedRoomContextProvider {...this.state} roomViewStore={this.roomViewStore}>
|
||||
<LocalRoomView
|
||||
e2eStatus={this.state.e2eStatus}
|
||||
localRoom={localRoom}
|
||||
@@ -2098,7 +2106,7 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
|
||||
|
||||
private renderWaitingForThirdPartyRoomView(inviteEvent: MatrixEvent): ReactNode {
|
||||
return (
|
||||
<ScopedRoomContextProvider {...this.state}>
|
||||
<ScopedRoomContextProvider {...this.state} roomViewStore={this.roomViewStore}>
|
||||
<WaitingForThirdPartyRoomView
|
||||
resizeNotifier={this.context.resizeNotifier}
|
||||
roomView={this.roomView}
|
||||
@@ -2640,7 +2648,7 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
|
||||
}
|
||||
|
||||
return (
|
||||
<ScopedRoomContextProvider {...this.state}>
|
||||
<ScopedRoomContextProvider {...this.state} roomViewStore={this.roomViewStore}>
|
||||
<div className={mainClasses} ref={this.roomView} onKeyDown={this.onReactKeyDown}>
|
||||
{showChatEffects && this.roomView.current && (
|
||||
<EffectsOverlay roomWidth={this.roomView.current.offsetWidth} />
|
||||
|
||||
@@ -68,6 +68,8 @@ import { ThreadsActivityCentre } from "./threads-activity-centre/";
|
||||
import AccessibleButton from "../elements/AccessibleButton";
|
||||
import { Landmark, LandmarkNavigation } from "../../../accessibility/LandmarkNavigation";
|
||||
import { KeyboardShortcut } from "../settings/KeyboardShortcut";
|
||||
import { ModuleApi } from "../../../modules/Api.ts";
|
||||
import { useModuleSpacePanelItems } from "../../../modules/ExtrasApi.ts";
|
||||
import { ReleaseAnnouncement } from "../../structures/ReleaseAnnouncement";
|
||||
|
||||
const useSpaces = (): [Room[], MetaSpace[], Room[], SpaceKey] => {
|
||||
@@ -290,6 +292,8 @@ const InnerSpacePanel = React.memo<IInnerSpacePanelProps>(
|
||||
const [invites, metaSpaces, actualSpaces, activeSpace] = useSpaces();
|
||||
const activeSpaces = activeSpace ? [activeSpace] : [];
|
||||
|
||||
const moduleSpaceItems = useModuleSpacePanelItems(ModuleApi.instance.extras);
|
||||
|
||||
const metaSpacesSection = metaSpaces
|
||||
.filter((key) => !(key === MetaSpace.VideoRooms && !SettingsStore.getValue("feature_video_rooms")))
|
||||
.map((key) => {
|
||||
@@ -341,6 +345,27 @@ const InnerSpacePanel = React.memo<IInnerSpacePanelProps>(
|
||||
</Draggable>
|
||||
))}
|
||||
{children}
|
||||
{moduleSpaceItems.map((item) => (
|
||||
<li
|
||||
key={item.spaceKey}
|
||||
className={classNames("mx_SpaceItem", {
|
||||
collapsed: isPanelCollapsed,
|
||||
})}
|
||||
role="treeitem"
|
||||
aria-selected={false} // TODO
|
||||
>
|
||||
<SpaceButton
|
||||
{...item}
|
||||
isNarrow={isPanelCollapsed}
|
||||
size="32px"
|
||||
selected={activeSpace === item.spaceKey}
|
||||
onClick={() => {
|
||||
SpaceStore.instance.setActiveSpace(item.spaceKey);
|
||||
item.onSelected?.();
|
||||
}}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
{shouldShowComponent(UIComponent.CreateSpaces) && (
|
||||
<CreateSpaceButton isPanelCollapsed={isPanelCollapsed} setPanelCollapsed={setPanelCollapsed} />
|
||||
)}
|
||||
|
||||
@@ -52,6 +52,7 @@ type ButtonProps<T extends keyof HTMLElementTagNameMap> = Omit<
|
||||
className?: string;
|
||||
selected?: boolean;
|
||||
label: string;
|
||||
icon?: JSX.Element;
|
||||
contextMenuTooltip?: string;
|
||||
notificationState?: NotificationState;
|
||||
isNarrow?: boolean;
|
||||
@@ -65,6 +66,7 @@ export const SpaceButton = <T extends keyof HTMLElementTagNameMap>({
|
||||
space,
|
||||
spaceKey: _spaceKey,
|
||||
className,
|
||||
icon,
|
||||
selected,
|
||||
label,
|
||||
contextMenuTooltip,
|
||||
@@ -84,7 +86,7 @@ export const SpaceButton = <T extends keyof HTMLElementTagNameMap>({
|
||||
|
||||
let avatar = (
|
||||
<div className="mx_SpaceButton_avatarPlaceholder">
|
||||
<div className="mx_SpaceButton_icon" />
|
||||
<div className="mx_SpaceButton_icon">{icon}</div>
|
||||
</div>
|
||||
);
|
||||
if (space) {
|
||||
@@ -143,6 +145,7 @@ export const SpaceButton = <T extends keyof HTMLElementTagNameMap>({
|
||||
mx_SpaceButton_active: selected,
|
||||
mx_SpaceButton_hasMenuOpen: menuDisplayed,
|
||||
mx_SpaceButton_narrow: isNarrow,
|
||||
mx_SpaceButton_withIcon: Boolean(icon),
|
||||
})}
|
||||
aria-label={label}
|
||||
title={!isNarrow || menuDisplayed ? undefined : label}
|
||||
|
||||
@@ -10,6 +10,7 @@ import { createContext } from "react";
|
||||
|
||||
import { type IRoomState } from "../components/structures/RoomView";
|
||||
import { Layout } from "../settings/enums/Layout";
|
||||
import { type RoomViewStore } from "../stores/RoomViewStore";
|
||||
|
||||
export enum TimelineRenderingType {
|
||||
Room = "Room",
|
||||
@@ -29,11 +30,12 @@ export enum MainSplitContentType {
|
||||
Call,
|
||||
}
|
||||
|
||||
const RoomContext = createContext<
|
||||
IRoomState & {
|
||||
threadId?: string;
|
||||
}
|
||||
>({
|
||||
export interface RoomContextType extends IRoomState {
|
||||
threadId?: string;
|
||||
roomViewStore: RoomViewStore;
|
||||
}
|
||||
|
||||
const RoomContext = createContext<RoomContextType>({
|
||||
roomLoading: true,
|
||||
peekLoading: false,
|
||||
shouldPeek: true,
|
||||
|
||||
@@ -25,6 +25,7 @@ import { WidgetPermissionStore } from "../stores/widgets/WidgetPermissionStore";
|
||||
import { OidcClientStore } from "../stores/oidc/OidcClientStore";
|
||||
import WidgetStore from "../stores/WidgetStore";
|
||||
import ResizeNotifier from "../utils/ResizeNotifier";
|
||||
import { MultiRoomViewStore } from "../stores/MultiRoomViewStore";
|
||||
|
||||
// This context is available to components under MatrixChat,
|
||||
// the context must not be used by components outside a SdkContextClass tree.
|
||||
@@ -66,6 +67,7 @@ export class SdkContextClass {
|
||||
protected _UserProfilesStore?: UserProfilesStore;
|
||||
protected _OidcClientStore?: OidcClientStore;
|
||||
protected _ResizeNotifier?: ResizeNotifier;
|
||||
protected _MultiRoomViewStore?: MultiRoomViewStore;
|
||||
|
||||
/**
|
||||
* Automatically construct stores which need to be created eagerly so they can register with
|
||||
@@ -183,6 +185,13 @@ export class SdkContextClass {
|
||||
return this._ResizeNotifier;
|
||||
}
|
||||
|
||||
public get multiRoomViewStore(): MultiRoomViewStore {
|
||||
if (!this._MultiRoomViewStore) {
|
||||
this._MultiRoomViewStore = new MultiRoomViewStore(defaultDispatcher, this);
|
||||
}
|
||||
return this._MultiRoomViewStore;
|
||||
}
|
||||
|
||||
public onLoggedOut(): void {
|
||||
this._UserProfilesStore = undefined;
|
||||
}
|
||||
|
||||
54
src/modules/AccountDataApi.ts
Normal file
54
src/modules/AccountDataApi.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
Copyright 2025 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { Watchable, type AccountDataApi as IAccountDataApi } from "@element-hq/element-web-module-api";
|
||||
import { ClientEvent, type MatrixEvent, type MatrixClient } from "matrix-js-sdk/src/matrix";
|
||||
|
||||
import { MatrixClientPeg } from "../MatrixClientPeg";
|
||||
|
||||
export class AccountDataApi implements IAccountDataApi {
|
||||
public get(eventType: string): Watchable<unknown> {
|
||||
const cli = MatrixClientPeg.safeGet();
|
||||
return new AccountDataWatchable(cli, eventType);
|
||||
}
|
||||
|
||||
public async set(eventType: string, content: any): Promise<void> {
|
||||
const cli = MatrixClientPeg.safeGet();
|
||||
//@ts-expect-error: JS-SDK accepts known event-types, intentionally allow arbitrary types.
|
||||
await cli.setAccountData(eventType, content);
|
||||
}
|
||||
|
||||
public async delete(eventType: string): Promise<void> {
|
||||
const cli = MatrixClientPeg.safeGet();
|
||||
//@ts-expect-error: JS-SDK accepts known event-types, intentionally allow arbitrary types.
|
||||
await cli.deleteAccountData(eventType);
|
||||
}
|
||||
}
|
||||
|
||||
class AccountDataWatchable extends Watchable<unknown> {
|
||||
public constructor(
|
||||
private cli: MatrixClient,
|
||||
private eventType: string,
|
||||
) {
|
||||
//@ts-expect-error: JS-SDK accepts known event-types, intentionally allow arbitrary types.
|
||||
super(cli.getAccountData(eventType)?.getContent());
|
||||
}
|
||||
|
||||
private onAccountData = (event: MatrixEvent): void => {
|
||||
if (event.getType() === this.eventType) {
|
||||
this.value = event.getContent();
|
||||
}
|
||||
};
|
||||
|
||||
protected onFirstWatch(): void {
|
||||
this.cli.on(ClientEvent.AccountData, this.onAccountData);
|
||||
}
|
||||
|
||||
protected onLastWatch(): void {
|
||||
this.cli.off(ClientEvent.AccountData, this.onAccountData);
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,10 @@ import { WatchableProfile } from "./Profile.ts";
|
||||
import { NavigationApi } from "./Navigation.ts";
|
||||
import { openDialog } from "./Dialog.tsx";
|
||||
import { overwriteAccountAuth } from "./Auth.ts";
|
||||
import { ElementWebExtrasApi } from "./ExtrasApi.ts";
|
||||
import { ElementWebBuiltinsApi } from "./BuiltinsApi.tsx";
|
||||
import { ClientApi } from "./ClientApi.ts";
|
||||
import { StoresApi } from "./StoresApi.ts";
|
||||
|
||||
const legacyCustomisationsFactory = <T extends object>(baseCustomisations: T) => {
|
||||
let used = false;
|
||||
@@ -79,7 +83,11 @@ export class ModuleApi implements Api {
|
||||
public readonly config = new ConfigApi();
|
||||
public readonly i18n = new I18nApi();
|
||||
public readonly customComponents = new CustomComponentsApi();
|
||||
public readonly extras = new ElementWebExtrasApi();
|
||||
public readonly builtins = new ElementWebBuiltinsApi();
|
||||
public readonly rootNode = document.getElementById("matrixchat")!;
|
||||
public readonly client = new ClientApi();
|
||||
public readonly stores = new StoresApi();
|
||||
|
||||
public createRoot(element: Element): Root {
|
||||
return createRoot(element);
|
||||
|
||||
75
src/modules/BuiltinsApi.tsx
Normal file
75
src/modules/BuiltinsApi.tsx
Normal file
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
Copyright 2025 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import React from "react";
|
||||
import { type RoomViewProps, type BuiltinsApi } from "@element-hq/element-web-module-api";
|
||||
|
||||
import { MatrixClientPeg } from "../MatrixClientPeg";
|
||||
import type { Room } from "matrix-js-sdk/src/matrix";
|
||||
|
||||
interface RoomViewPropsWithRoomId extends RoomViewProps {
|
||||
roomId?: string;
|
||||
}
|
||||
|
||||
interface RoomAvatarProps {
|
||||
room: Room;
|
||||
size?: string;
|
||||
}
|
||||
|
||||
interface Components {
|
||||
roomView: React.ComponentType<RoomViewPropsWithRoomId>;
|
||||
roomAvatar: React.ComponentType<RoomAvatarProps>;
|
||||
}
|
||||
|
||||
export class ElementWebBuiltinsApi implements BuiltinsApi {
|
||||
private _roomView?: React.ComponentType<RoomViewPropsWithRoomId>;
|
||||
private _roomAvatar?: React.ComponentType<RoomAvatarProps>;
|
||||
|
||||
/**
|
||||
* Sets the components used by the API.
|
||||
*
|
||||
* This only really exists here because referencing these components directly causes a nightmare of
|
||||
* circular dependencies that break the whole app, so instead we avoid referencing it here
|
||||
* and pass it in from somewhere it's already referenced (see related comment in app.tsx).
|
||||
*
|
||||
* @param component The components used by the api, see {@link Components}
|
||||
*/
|
||||
public setComponents(components: Components): void {
|
||||
this._roomView = components.roomView;
|
||||
this._roomAvatar = components.roomAvatar;
|
||||
}
|
||||
|
||||
public getRoomViewComponent(): React.ComponentType<RoomViewPropsWithRoomId> {
|
||||
if (!this._roomView) {
|
||||
throw new Error("No RoomView component has been set");
|
||||
}
|
||||
|
||||
return this._roomView;
|
||||
}
|
||||
|
||||
public getRoomAvatarComponent(): React.ComponentType<RoomAvatarProps> {
|
||||
if (!this._roomAvatar) {
|
||||
throw new Error("No RoomAvatar component has been set");
|
||||
}
|
||||
|
||||
return this._roomAvatar;
|
||||
}
|
||||
|
||||
public renderRoomView(roomId: string): React.ReactNode {
|
||||
const Component = this.getRoomViewComponent();
|
||||
return <Component roomId={roomId} />;
|
||||
}
|
||||
|
||||
public renderRoomAvatar(roomId: string, size?: string): React.ReactNode {
|
||||
const room = MatrixClientPeg.safeGet().getRoom(roomId);
|
||||
if (!room) {
|
||||
throw new Error(`No room such room: ${roomId}`);
|
||||
}
|
||||
const Component = this.getRoomAvatarComponent();
|
||||
return <Component room={room} size={size} />;
|
||||
}
|
||||
}
|
||||
20
src/modules/ClientApi.ts
Normal file
20
src/modules/ClientApi.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
Copyright 2025 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
import type { ClientApi as IClientApi, Room } from "@element-hq/element-web-module-api";
|
||||
import { Room as ModuleRoom } from "./models/Room";
|
||||
import { AccountDataApi } from "./AccountDataApi";
|
||||
import { MatrixClientPeg } from "../MatrixClientPeg";
|
||||
|
||||
export class ClientApi implements IClientApi {
|
||||
public readonly accountData = new AccountDataApi();
|
||||
|
||||
public getRoom(roomId: string): Room | null {
|
||||
const sdkRoom = MatrixClientPeg.safeGet().getRoom(roomId);
|
||||
if (sdkRoom) return new ModuleRoom(sdkRoom);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
50
src/modules/ExtrasApi.ts
Normal file
50
src/modules/ExtrasApi.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
Copyright 2025 New Vector Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { useState } from "react";
|
||||
import { type SpacePanelItemProps, type ExtrasApi } from "@element-hq/element-web-module-api";
|
||||
import { TypedEventEmitter } from "matrix-js-sdk/src/matrix";
|
||||
|
||||
import { useTypedEventEmitter } from "../hooks/useEventEmitter";
|
||||
|
||||
export interface ModuleSpacePanelItem extends SpacePanelItemProps {
|
||||
spaceKey: string;
|
||||
}
|
||||
|
||||
enum ExtrasApiEvent {
|
||||
SpacePanelItemsChanged = "SpacePanelItemsChanged",
|
||||
}
|
||||
|
||||
interface EmittedEvents {
|
||||
[ExtrasApiEvent.SpacePanelItemsChanged]: () => void;
|
||||
}
|
||||
|
||||
export class ElementWebExtrasApi extends TypedEventEmitter<keyof EmittedEvents, EmittedEvents> implements ExtrasApi {
|
||||
public spacePanelItems = new Map<string, SpacePanelItemProps>();
|
||||
|
||||
public setSpacePanelItem(spacekey: string, item: SpacePanelItemProps): void {
|
||||
this.spacePanelItems.set(spacekey, item);
|
||||
this.emit(ExtrasApiEvent.SpacePanelItemsChanged);
|
||||
}
|
||||
}
|
||||
|
||||
export function useModuleSpacePanelItems(api: ElementWebExtrasApi): ModuleSpacePanelItem[] {
|
||||
const getItems = (): ModuleSpacePanelItem[] => {
|
||||
return Array.from(api.spacePanelItems.entries()).map(([spaceKey, item]) => ({
|
||||
spaceKey,
|
||||
...item,
|
||||
}));
|
||||
};
|
||||
|
||||
const [items, setItems] = useState<ModuleSpacePanelItem[]>(getItems);
|
||||
|
||||
useTypedEventEmitter(api, ExtrasApiEvent.SpacePanelItemsChanged, () => {
|
||||
setItems(getItems());
|
||||
});
|
||||
|
||||
return items;
|
||||
}
|
||||
@@ -5,8 +5,11 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { type NavigationApi as INavigationApi } from "@element-hq/element-web-module-api";
|
||||
|
||||
import type {
|
||||
LocationRenderFunction,
|
||||
NavigationApi as INavigationApi,
|
||||
OpenRoomOptions,
|
||||
} from "@element-hq/element-web-module-api";
|
||||
import { navigateToPermalink } from "../utils/permalinks/navigator.ts";
|
||||
import { parsePermalink } from "../utils/permalinks/Permalinks.ts";
|
||||
import dispatcher from "../dispatcher/dispatcher.ts";
|
||||
@@ -14,28 +17,32 @@ import { Action } from "../dispatcher/actions.ts";
|
||||
import type { ViewRoomPayload } from "../dispatcher/payloads/ViewRoomPayload.ts";
|
||||
|
||||
export class NavigationApi implements INavigationApi {
|
||||
public locationRenderers = new Map<string, LocationRenderFunction>();
|
||||
|
||||
public async toMatrixToLink(link: string, join = false): Promise<void> {
|
||||
navigateToPermalink(link);
|
||||
|
||||
const parts = parsePermalink(link);
|
||||
if (parts?.roomIdOrAlias) {
|
||||
if (parts.roomIdOrAlias.startsWith("#")) {
|
||||
dispatcher.dispatch<ViewRoomPayload>({
|
||||
action: Action.ViewRoom,
|
||||
room_alias: parts.roomIdOrAlias,
|
||||
via_servers: parts.viaServers ?? undefined,
|
||||
auto_join: join,
|
||||
metricsTrigger: undefined,
|
||||
});
|
||||
} else {
|
||||
dispatcher.dispatch<ViewRoomPayload>({
|
||||
action: Action.ViewRoom,
|
||||
room_id: parts.roomIdOrAlias,
|
||||
via_servers: parts.viaServers ?? undefined,
|
||||
auto_join: join,
|
||||
metricsTrigger: undefined,
|
||||
});
|
||||
}
|
||||
this.openRoom(parts.roomIdOrAlias, {
|
||||
viaServers: parts.viaServers ?? undefined,
|
||||
autoJoin: join,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public registerLocationRenderer(path: string, renderer: LocationRenderFunction): void {
|
||||
this.locationRenderers.set(path, renderer);
|
||||
}
|
||||
|
||||
public openRoom(roomIdOrAlias: string, opts: OpenRoomOptions = {}): void {
|
||||
const key = roomIdOrAlias.startsWith("#") ? "room_alias" : "room_id";
|
||||
dispatcher.dispatch<ViewRoomPayload>({
|
||||
action: Action.ViewRoom,
|
||||
[key]: roomIdOrAlias,
|
||||
via_servers: opts.viaServers,
|
||||
auto_join: opts.autoJoin,
|
||||
metricsTrigger: undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
106
src/modules/StoresApi.ts
Normal file
106
src/modules/StoresApi.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
Copyright 2025 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
import {
|
||||
type StoresApi as IStoresApi,
|
||||
type RoomListStoreApi as IRoomListStore,
|
||||
type Room,
|
||||
Watchable,
|
||||
} from "@element-hq/element-web-module-api";
|
||||
|
||||
import type { RoomListStoreV3Class, RoomListStoreV3Event } from "../stores/room-list-v3/RoomListStoreV3";
|
||||
import { Room as ModuleRoom } from "./models/Room";
|
||||
|
||||
interface RlsEvents {
|
||||
LISTS_LOADED_EVENT: RoomListStoreV3Event.ListsLoaded;
|
||||
LISTS_UPDATE_EVENT: RoomListStoreV3Event.ListsUpdate;
|
||||
}
|
||||
|
||||
export class RoomListStoreApi implements IRoomListStore {
|
||||
private rls?: RoomListStoreV3Class;
|
||||
private LISTS_LOADED_EVENT?: RoomListStoreV3Event.ListsLoaded;
|
||||
private LISTS_UPDATE_EVENT?: RoomListStoreV3Event.ListsUpdate;
|
||||
public readonly moduleLoadPromise: Promise<void>;
|
||||
|
||||
public constructor() {
|
||||
this.moduleLoadPromise = this.init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the RLS through a dynamic import. This is necessary to prevent
|
||||
* circular dependency issues.
|
||||
*/
|
||||
private async init(): Promise<void> {
|
||||
const module = await import("../stores/room-list-v3/RoomListStoreV3");
|
||||
this.rls = module.default.instance;
|
||||
this.LISTS_LOADED_EVENT = module.LISTS_LOADED_EVENT;
|
||||
this.LISTS_UPDATE_EVENT = module.LISTS_UPDATE_EVENT;
|
||||
}
|
||||
|
||||
public getRooms(): RoomsWatchable {
|
||||
return new RoomsWatchable(this.roomListStore, this.events);
|
||||
}
|
||||
|
||||
private get events(): RlsEvents {
|
||||
if (!this.LISTS_LOADED_EVENT || !this.LISTS_UPDATE_EVENT) {
|
||||
throw new Error("Event type was not loaded correctly, did you forget to await waitForReady()?");
|
||||
}
|
||||
return { LISTS_LOADED_EVENT: this.LISTS_LOADED_EVENT, LISTS_UPDATE_EVENT: this.LISTS_UPDATE_EVENT };
|
||||
}
|
||||
|
||||
private get roomListStore(): RoomListStoreV3Class {
|
||||
if (!this.rls) {
|
||||
throw new Error("rls is undefined, did you forget to await waitForReady()?");
|
||||
}
|
||||
return this.rls;
|
||||
}
|
||||
|
||||
public async waitForReady(): Promise<void> {
|
||||
// Wait for the module to load first
|
||||
await this.moduleLoadPromise;
|
||||
|
||||
// Check if RLS is already loaded
|
||||
if (!this.roomListStore.isLoadingRooms) return;
|
||||
|
||||
// Await a promise that resolves when RLS has loaded
|
||||
const { promise, resolve } = Promise.withResolvers<void>();
|
||||
const { LISTS_LOADED_EVENT } = this.events;
|
||||
this.roomListStore.once(LISTS_LOADED_EVENT, resolve);
|
||||
await promise;
|
||||
}
|
||||
}
|
||||
|
||||
class RoomsWatchable extends Watchable<Room[]> {
|
||||
public constructor(
|
||||
private readonly rls: RoomListStoreV3Class,
|
||||
private readonly events: RlsEvents,
|
||||
) {
|
||||
super(rls.getSortedRooms().map((sdkRoom) => new ModuleRoom(sdkRoom)));
|
||||
}
|
||||
|
||||
private onRlsUpdate = (): void => {
|
||||
this.value = this.rls.getSortedRooms().map((sdkRoom) => new ModuleRoom(sdkRoom));
|
||||
};
|
||||
|
||||
protected onFirstWatch(): void {
|
||||
this.rls.on(this.events.LISTS_UPDATE_EVENT, this.onRlsUpdate);
|
||||
}
|
||||
|
||||
protected onLastWatch(): void {
|
||||
this.rls.off(this.events.LISTS_UPDATE_EVENT, this.onRlsUpdate);
|
||||
}
|
||||
}
|
||||
|
||||
export class StoresApi implements IStoresApi {
|
||||
private roomListStoreApi?: IRoomListStore;
|
||||
|
||||
public get roomListStore(): IRoomListStore {
|
||||
if (!this.roomListStoreApi) {
|
||||
this.roomListStoreApi = new RoomListStoreApi();
|
||||
}
|
||||
return this.roomListStoreApi;
|
||||
}
|
||||
}
|
||||
45
src/modules/models/Room.ts
Normal file
45
src/modules/models/Room.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
Copyright 2025 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { type Room as IRoom, Watchable } from "@element-hq/element-web-module-api";
|
||||
import { RoomEvent, type Room as SdkRoom } from "matrix-js-sdk/src/matrix";
|
||||
|
||||
export class Room implements IRoom {
|
||||
public name: Watchable<string>;
|
||||
|
||||
public constructor(private sdkRoom: SdkRoom) {
|
||||
this.name = new WatchableName(sdkRoom);
|
||||
}
|
||||
|
||||
public getLastActiveTimestamp(): number {
|
||||
return this.sdkRoom.getLastActiveTimestamp();
|
||||
}
|
||||
|
||||
public get id(): string {
|
||||
return this.sdkRoom.roomId;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A custom watchable for room name.
|
||||
*/
|
||||
class WatchableName extends Watchable<string> {
|
||||
public constructor(private sdkRoom: SdkRoom) {
|
||||
super(sdkRoom.name);
|
||||
}
|
||||
|
||||
private onNameUpdate = (): void => {
|
||||
super.value = this.sdkRoom.name;
|
||||
};
|
||||
protected onFirstWatch(): void {
|
||||
this.sdkRoom.on(RoomEvent.Name, this.onNameUpdate);
|
||||
}
|
||||
|
||||
protected onLastWatch(): void {
|
||||
this.sdkRoom.off(RoomEvent.Name, this.onNameUpdate);
|
||||
}
|
||||
}
|
||||
67
src/stores/MultiRoomViewStore.ts
Normal file
67
src/stores/MultiRoomViewStore.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
Copyright 2025 New Vector Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { logger } from "matrix-js-sdk/src/logger";
|
||||
|
||||
import { RoomViewStore } from "./RoomViewStore";
|
||||
import { type MatrixDispatcher } from "../dispatcher/dispatcher";
|
||||
import { type SdkContextClass } from "../contexts/SDKContext";
|
||||
import { Action } from "../dispatcher/actions";
|
||||
|
||||
/**
|
||||
* Acts as a cache of many RoomViewStore instances, creating them as necessary
|
||||
* given a room ID.
|
||||
*/
|
||||
export class MultiRoomViewStore {
|
||||
/**
|
||||
* Map from room-id to RVS instance.
|
||||
*/
|
||||
private stores: Map<string, RoomViewStore> = new Map();
|
||||
|
||||
public constructor(
|
||||
private dispatcher: MatrixDispatcher,
|
||||
private sdkContextClass: SdkContextClass,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Get a RVS instance for the room identified by the given roomId.
|
||||
*/
|
||||
public getRoomViewStoreForRoom(roomId: string): RoomViewStore {
|
||||
// Get existing store / create new store
|
||||
const store = this.stores.has(roomId)
|
||||
? this.stores.get(roomId)!
|
||||
: new RoomViewStore(this.dispatcher, this.sdkContextClass, roomId);
|
||||
|
||||
// RoomView component does not render the room unless you call viewRoom
|
||||
store.viewRoom({
|
||||
action: Action.ViewRoom,
|
||||
room_id: roomId,
|
||||
metricsTrigger: undefined,
|
||||
});
|
||||
|
||||
// Cache the store, okay to do even if the store is already in the map
|
||||
this.stores.set(roomId, store);
|
||||
|
||||
return store;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a RVS instance that was created by {@link getRoomViewStoreForRoom}.
|
||||
*/
|
||||
public removeRoomViewStore(roomId: string): void {
|
||||
const didRemove = this.stores.delete(roomId);
|
||||
if (!didRemove) {
|
||||
logger.warn(`removeRoomViewStore called with ${roomId} but no store exists for this room.`);
|
||||
}
|
||||
}
|
||||
|
||||
public dispose(): void {
|
||||
for (const id of this.stores.keys()) {
|
||||
this.removeRoomViewStore(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -153,6 +153,7 @@ export class RoomViewStore extends EventEmitter {
|
||||
public constructor(
|
||||
dis: MatrixDispatcher,
|
||||
private readonly stores: SdkContextClass,
|
||||
private readonly lockedToRoomId?: string,
|
||||
) {
|
||||
super();
|
||||
this.resetDispatcher(dis);
|
||||
@@ -187,7 +188,7 @@ export class RoomViewStore extends EventEmitter {
|
||||
|
||||
const lastRoomId = this.state.roomId;
|
||||
this.state = Object.assign(this.state, newState);
|
||||
if (lastRoomId !== this.state.roomId) {
|
||||
if (!this.lockedToRoomId && lastRoomId !== this.state.roomId) {
|
||||
if (lastRoomId) this.emitForRoom(lastRoomId, false);
|
||||
if (this.state.roomId) this.emitForRoom(this.state.roomId, true);
|
||||
|
||||
@@ -204,6 +205,9 @@ export class RoomViewStore extends EventEmitter {
|
||||
}
|
||||
|
||||
private onDispatch(payload: ActionPayload): void {
|
||||
if (this.lockedToRoomId && payload.room_id && this.lockedToRoomId !== payload.room_id) {
|
||||
return;
|
||||
}
|
||||
// eslint-disable-line @typescript-eslint/naming-convention
|
||||
switch (payload.action) {
|
||||
// view_room:
|
||||
@@ -324,7 +328,7 @@ export class RoomViewStore extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
private async viewRoom(payload: ViewRoomPayload): Promise<void> {
|
||||
public async viewRoom(payload: ViewRoomPayload): Promise<void> {
|
||||
if (payload.room_id) {
|
||||
const room = MatrixClientPeg.safeGet().getRoom(payload.room_id);
|
||||
|
||||
|
||||
@@ -12,15 +12,15 @@ import { NotificationLevel } from "./NotificationLevel";
|
||||
import { arrayDiff } from "../../utils/arrays";
|
||||
import { type RoomNotificationState } from "./RoomNotificationState";
|
||||
import { NotificationState, NotificationStateEvents } from "./NotificationState";
|
||||
import { type FetchRoomFn } from "./ListNotificationState";
|
||||
import { DefaultTagID } from "../room-list/models";
|
||||
import RoomListStore from "../room-list/RoomListStore";
|
||||
import { RoomNotificationStateStore } from "./RoomNotificationStateStore";
|
||||
|
||||
export class SpaceNotificationState extends NotificationState {
|
||||
public rooms: Room[] = []; // exposed only for tests
|
||||
private states: { [spaceId: string]: RoomNotificationState } = {};
|
||||
|
||||
public constructor(private getRoomFn: FetchRoomFn) {
|
||||
public constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ export class SpaceNotificationState extends NotificationState {
|
||||
state.off(NotificationStateEvents.Update, this.onRoomNotificationStateUpdate);
|
||||
}
|
||||
for (const newRoom of diff.added) {
|
||||
const state = this.getRoomFn(newRoom);
|
||||
const state = RoomNotificationStateStore.instance.getRoomState(newRoom);
|
||||
state.on(NotificationStateEvents.Update, this.onRoomNotificationStateUpdate);
|
||||
this.states[newRoom.roomId] = state;
|
||||
}
|
||||
|
||||
@@ -27,7 +27,6 @@ import defaultDispatcher from "../../dispatcher/dispatcher";
|
||||
import RoomListStore from "../room-list/RoomListStore";
|
||||
import SettingsStore from "../../settings/SettingsStore";
|
||||
import DMRoomMap from "../../utils/DMRoomMap";
|
||||
import { type FetchRoomFn } from "../notifications/ListNotificationState";
|
||||
import { SpaceNotificationState } from "../notifications/SpaceNotificationState";
|
||||
import { RoomNotificationStateStore } from "../notifications/RoomNotificationStateStore";
|
||||
import { DefaultTagID } from "../room-list/models";
|
||||
@@ -63,6 +62,7 @@ import { type ViewHomePagePayload } from "../../dispatcher/payloads/ViewHomePage
|
||||
import { type SwitchSpacePayload } from "../../dispatcher/payloads/SwitchSpacePayload";
|
||||
import { type AfterLeaveRoomPayload } from "../../dispatcher/payloads/AfterLeaveRoomPayload";
|
||||
import { SdkContextClass } from "../../contexts/SDKContext";
|
||||
import { ModuleApi } from "../../modules/Api.ts";
|
||||
|
||||
const ACTIVE_SPACE_LS_KEY = "mx_active_space";
|
||||
|
||||
@@ -111,10 +111,6 @@ export const getChildOrder = (
|
||||
return [validOrder(order) ?? NaN, ts, roomId]; // NaN has lodash sort it at the end in asc
|
||||
};
|
||||
|
||||
const getRoomFn: FetchRoomFn = (room: Room) => {
|
||||
return RoomNotificationStateStore.instance.getRoomState(room);
|
||||
};
|
||||
|
||||
type SpaceStoreActions =
|
||||
| SettingUpdatedPayload
|
||||
| ViewRoomPayload
|
||||
@@ -258,7 +254,9 @@ export class SpaceStoreClass extends AsyncStoreWithClient<EmptyObject> {
|
||||
if (!space || !this.matrixClient || space === this.activeSpace) return;
|
||||
|
||||
let cliSpace: Room | null = null;
|
||||
if (!isMetaSpace(space)) {
|
||||
if (ModuleApi.instance.extras.spacePanelItems.has(space)) {
|
||||
// it's a "space" provided by a module: that's good enough
|
||||
} else if (!isMetaSpace(space)) {
|
||||
cliSpace = this.matrixClient.getRoom(space);
|
||||
if (!cliSpace?.isSpaceRoom()) return;
|
||||
} else if (!this.enabledMetaSpaces.includes(space)) {
|
||||
@@ -293,6 +291,8 @@ export class SpaceStoreClass extends AsyncStoreWithClient<EmptyObject> {
|
||||
context_switch: true,
|
||||
metricsTrigger: "WebSpaceContextSwitch",
|
||||
});
|
||||
} else if (ModuleApi.instance.extras.spacePanelItems.has(space)) {
|
||||
// module will handle this
|
||||
} else {
|
||||
defaultDispatcher.dispatch<ViewHomePagePayload>({
|
||||
action: Action.ViewHomePage,
|
||||
@@ -1214,7 +1214,8 @@ export class SpaceStoreClass extends AsyncStoreWithClient<EmptyObject> {
|
||||
const lastSpaceId = window.localStorage.getItem(ACTIVE_SPACE_LS_KEY) as MetaSpace;
|
||||
const valid =
|
||||
lastSpaceId &&
|
||||
(!isMetaSpace(lastSpaceId) ? this.matrixClient.getRoom(lastSpaceId) : enabledMetaSpaces[lastSpaceId]);
|
||||
(ModuleApi.instance.extras.spacePanelItems.has(lastSpaceId) ||
|
||||
(!isMetaSpace(lastSpaceId) ? this.matrixClient.getRoom(lastSpaceId) : enabledMetaSpaces[lastSpaceId]));
|
||||
if (valid) {
|
||||
// don't context switch here as it may break permalinks
|
||||
this.setActiveSpace(lastSpaceId, false);
|
||||
@@ -1369,7 +1370,7 @@ export class SpaceStoreClass extends AsyncStoreWithClient<EmptyObject> {
|
||||
return this.notificationStateMap.get(key)!;
|
||||
}
|
||||
|
||||
const state = new SpaceNotificationState(getRoomFn);
|
||||
const state = new SpaceNotificationState();
|
||||
this.notificationStateMap.set(key, state);
|
||||
return state;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { type Room, type HierarchyRoom } from "matrix-js-sdk/src/matrix";
|
||||
import { type HierarchyRoom } from "matrix-js-sdk/src/matrix";
|
||||
|
||||
import { _t } from "../../languageHandler";
|
||||
|
||||
@@ -42,7 +42,15 @@ export const getMetaSpaceName = (spaceKey: MetaSpace, allRoomsInHome = false): s
|
||||
}
|
||||
};
|
||||
|
||||
export type SpaceKey = MetaSpace | Room["roomId"];
|
||||
/**
|
||||
* This can be:
|
||||
* - a MetaSpace
|
||||
* - space ID (ie. a room ID)
|
||||
* - A 'custom' space from a module
|
||||
* Unfortunately we can't type the last set as we don't know what modules will define,
|
||||
* so we can't do better than string here.
|
||||
*/
|
||||
export type SpaceKey = string;
|
||||
|
||||
export interface ISuggestedRoom extends HierarchyRoom {
|
||||
viaServers: string[];
|
||||
|
||||
@@ -30,6 +30,9 @@ import { ModuleRunner } from "../modules/ModuleRunner";
|
||||
import { parseQs } from "./url_utils";
|
||||
import { getInitialScreenAfterLogin, getScreenFromLocation, init as initRouting, onNewScreen } from "./routing";
|
||||
import { UserFriendlyError } from "../languageHandler";
|
||||
import { ModuleApi } from "../modules/Api";
|
||||
import { RoomView } from "../components/structures/RoomView";
|
||||
import RoomAvatar from "../components/views/avatars/RoomAvatar";
|
||||
|
||||
logger.log(`Application is running in ${process.env.NODE_ENV} mode`);
|
||||
|
||||
@@ -53,6 +56,10 @@ function onTokenLoginCompleted(): void {
|
||||
}
|
||||
|
||||
export async function loadApp(fragParams: QueryDict, matrixChatRef: React.Ref<MatrixChat>): Promise<ReactElement> {
|
||||
// XXX: This lives here because certain components import so many things that importing it in a sensible place (eg.
|
||||
// the builtins module or init.tsx) causes a circular dependency.
|
||||
ModuleApi.instance.builtins.setComponents({ roomView: RoomView, roomAvatar: RoomAvatar });
|
||||
|
||||
initRouting();
|
||||
const platform = PlatformPeg.get();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user