Merge branch 'develop' into jaywink/hosting-provider-iframe-minimize-wip

This commit is contained in:
Jason Robinson 2021-02-03 22:35:22 +02:00
commit 6ccce7142c
156 changed files with 7020 additions and 5218 deletions

View file

@ -18,22 +18,33 @@ import { MatrixClient } from "matrix-js-sdk/src/client";
import { AsyncStore } from "./AsyncStore";
import { ActionPayload } from "../dispatcher/payloads";
import { Dispatcher } from "flux";
import { MatrixClientPeg } from "../MatrixClientPeg";
import { ReadyWatchingStore } from "./ReadyWatchingStore";
export abstract class AsyncStoreWithClient<T extends Object> extends AsyncStore<T> {
protected matrixClient: MatrixClient;
protected abstract async onAction(payload: ActionPayload);
protected readyStore: ReadyWatchingStore;
protected constructor(dispatcher: Dispatcher<ActionPayload>, initialState: T = <T>{}) {
super(dispatcher, initialState);
if (MatrixClientPeg.get()) {
this.matrixClient = MatrixClientPeg.get();
// Create an anonymous class to avoid code duplication
const asyncStore = this; // eslint-disable-line @typescript-eslint/no-this-alias
this.readyStore = new (class extends ReadyWatchingStore {
public get mxClient(): MatrixClient {
return this.matrixClient;
}
// noinspection JSIgnoredPromiseFromCall
this.onReady();
}
protected async onReady(): Promise<any> {
return asyncStore.onReady();
}
protected async onNotReady(): Promise<any> {
return asyncStore.onNotReady();
}
})(dispatcher);
}
get matrixClient(): MatrixClient {
return this.readyStore.mxClient;
}
protected async onReady() {
@ -44,30 +55,9 @@ export abstract class AsyncStoreWithClient<T extends Object> extends AsyncStore<
// Default implementation is to do nothing.
}
protected abstract onAction(payload: ActionPayload): Promise<void>;
protected async onDispatch(payload: ActionPayload) {
await this.onAction(payload);
if (payload.action === 'MatrixActions.sync') {
// Only set the client on the transition into the PREPARED state.
// Everything after this is unnecessary (we only need to know once we have a client)
// and we intentionally don't set the client before this point to avoid stores
// updating for every event emitted during the cached sync.
if (!(payload.prevState === 'PREPARED' && payload.state !== 'PREPARED')) {
return;
}
if (this.matrixClient !== payload.matrixClient) {
if (this.matrixClient) {
await this.onNotReady();
}
this.matrixClient = payload.matrixClient;
await this.onReady();
}
} else if (payload.action === 'on_client_not_viable' || payload.action === 'on_logged_out') {
if (this.matrixClient) {
await this.onNotReady();
this.matrixClient = null;
}
}
}
}

View file

@ -48,6 +48,10 @@ export class CommunityPrototypeStore extends AsyncStoreWithClient<IState> {
return CommunityPrototypeStore.internalInstance;
}
public static getUpdateEventName(roomId: string): string {
return `${UPDATE_EVENT}:${roomId}`;
}
public getSelectedCommunityId(): string {
if (SettingsStore.getValue("feature_communities_v2_prototypes")) {
return GroupFilterOrderStore.getSelectedTags()[0];
@ -134,7 +138,8 @@ export class CommunityPrototypeStore extends AsyncStoreWithClient<IState> {
}
} else if (payload.action === "MatrixActions.accountData") {
if (payload.event_type.startsWith("im.vector.group_info.")) {
this.emit(UPDATE_EVENT, payload.event_type.substring("im.vector.group_info.".length));
const roomId = payload.event_type.substring("im.vector.group_info.".length);
this.emit(CommunityPrototypeStore.getUpdateEventName(roomId), roomId);
}
} else if (payload.action === "select_tag") {
// Automatically select the general chat when switching communities
@ -167,7 +172,7 @@ export class CommunityPrototypeStore extends AsyncStoreWithClient<IState> {
if (getEffectiveMembership(myMember.membership) === EffectiveMembership.Invite) {
// Fake an update for anything that might have started listening before the invite
// data was available (eg: RoomPreviewBar after a refresh)
this.emit(UPDATE_EVENT, room.roomId);
this.emit(CommunityPrototypeStore.getUpdateEventName(room.roomId), room.roomId);
}
}
}

View file

@ -48,11 +48,16 @@ export class ModalWidgetStore extends AsyncStoreWithClient<IState> {
return !this.modalInstance;
};
public openModalWidget = (requestData: IModalWidgetOpenRequestData, sourceWidget: Widget) => {
public openModalWidget = (
requestData: IModalWidgetOpenRequestData,
sourceWidget: Widget,
widgetRoomId?: string,
) => {
if (this.modalInstance) return;
this.openSourceWidgetId = sourceWidget.id;
this.modalInstance = Modal.createTrackedDialog('Modal Widget', '', ModalWidgetDialog, {
widgetDefinition: {...requestData},
widgetRoomId,
sourceWidgetId: sourceWidget.id,
onFinished: (success: boolean, data?: IModalWidgetReturnData) => {
if (!success) {

View file

@ -0,0 +1,85 @@
/*
* Copyright 2021 The Matrix.org Foundation C.I.C.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { MatrixClient } from "matrix-js-sdk/src/client";
import { MatrixClientPeg } from "../MatrixClientPeg";
import { ActionPayload } from "../dispatcher/payloads";
import { Dispatcher } from "flux";
import { IDestroyable } from "../utils/IDestroyable";
import { EventEmitter } from "events";
export abstract class ReadyWatchingStore extends EventEmitter implements IDestroyable {
protected matrixClient: MatrixClient;
private readonly dispatcherRef: string;
constructor(protected readonly dispatcher: Dispatcher<ActionPayload>) {
super();
this.dispatcherRef = this.dispatcher.register(this.onAction);
if (MatrixClientPeg.get()) {
this.matrixClient = MatrixClientPeg.get();
// noinspection JSIgnoredPromiseFromCall
this.onReady();
}
}
public get mxClient(): MatrixClient {
return this.matrixClient; // for external readonly access
}
public useUnitTestClient(cli: MatrixClient) {
this.matrixClient = cli;
}
public destroy() {
this.dispatcher.unregister(this.dispatcherRef);
}
protected async onReady() {
// Default implementation is to do nothing.
}
protected async onNotReady() {
// Default implementation is to do nothing.
}
private onAction = async (payload: ActionPayload) => {
if (payload.action === 'MatrixActions.sync') {
// Only set the client on the transition into the PREPARED state.
// Everything after this is unnecessary (we only need to know once we have a client)
// and we intentionally don't set the client before this point to avoid stores
// updating for every event emitted during the cached sync.
if (!(payload.prevState === 'PREPARED' && payload.state !== 'PREPARED')) {
return;
}
if (this.matrixClient !== payload.matrixClient) {
if (this.matrixClient) {
await this.onNotReady();
}
this.matrixClient = payload.matrixClient;
await this.onReady();
}
} else if (payload.action === 'on_client_not_viable' || payload.action === 'on_logged_out') {
if (this.matrixClient) {
await this.onNotReady();
this.matrixClient = null;
}
}
};
}

View file

@ -21,16 +21,12 @@ import { IWidget } from "matrix-widget-api";
import { ActionPayload } from "../dispatcher/payloads";
import { AsyncStoreWithClient } from "./AsyncStoreWithClient";
import defaultDispatcher from "../dispatcher/dispatcher";
import SettingsStore from "../settings/SettingsStore";
import WidgetEchoStore from "../stores/WidgetEchoStore";
import RoomViewStore from "../stores/RoomViewStore";
import ActiveWidgetStore from "../stores/ActiveWidgetStore";
import WidgetUtils from "../utils/WidgetUtils";
import {SettingLevel} from "../settings/SettingLevel";
import {WidgetType} from "../widgets/WidgetType";
import {UPDATE_EVENT} from "./AsyncStore";
import { MatrixClientPeg } from "../MatrixClientPeg";
import { arrayDiff, arrayHasDiff, arrayUnion } from "../utils/arrays";
interface IState {}
@ -41,15 +37,10 @@ export interface IApp extends IWidget {
avatar_url: string; // MSC2765 https://github.com/matrix-org/matrix-doc/pull/2765
}
type PinnedWidgets = Record<string, boolean>;
interface IRoomWidgets {
widgets: IApp[];
pinned: PinnedWidgets;
}
export const MAX_PINNED = 3;
function widgetUid(app: IApp): string {
return `${app.roomId ?? MatrixClientPeg.get().getUserId()}::${app.id}`;
}
@ -65,7 +56,6 @@ export default class WidgetStore extends AsyncStoreWithClient<IState> {
private constructor() {
super(defaultDispatcher, {});
SettingsStore.watchSetting("Widgets.pinned", null, this.onPinnedWidgetsChange);
WidgetEchoStore.on("update", this.onWidgetEchoStoreUpdate);
}
@ -76,31 +66,22 @@ export default class WidgetStore extends AsyncStoreWithClient<IState> {
private initRoom(roomId: string) {
if (!this.roomMap.has(roomId)) {
this.roomMap.set(roomId, {
pinned: {}, // ordered
widgets: [],
});
}
}
protected async onReady(): Promise<any> {
this.matrixClient.on("Room", this.onRoom);
this.matrixClient.on("RoomState.events", this.onRoomStateEvents);
this.matrixClient.getRooms().forEach((room: Room) => {
const pinned = SettingsStore.getValue("Widgets.pinned", room.roomId);
if (pinned || WidgetUtils.getRoomWidgets(room).length) {
this.initRoom(room.roomId);
}
if (pinned) {
this.getRoom(room.roomId).pinned = pinned;
}
this.loadRoomWidgets(room);
});
this.emit(UPDATE_EVENT);
this.emit(UPDATE_EVENT, null); // emit for all rooms
}
protected async onNotReady(): Promise<any> {
this.matrixClient.off("Room", this.onRoom);
this.matrixClient.off("RoomState.events", this.onRoomStateEvents);
this.widgetMap = new Map();
this.roomMap = new Map();
@ -115,7 +96,7 @@ export default class WidgetStore extends AsyncStoreWithClient<IState> {
private onWidgetEchoStoreUpdate = (roomId: string, widgetId: string) => {
this.initRoom(roomId);
this.loadRoomWidgets(this.matrixClient.getRoom(roomId));
this.emit(UPDATE_EVENT);
this.emit(UPDATE_EVENT, roomId);
};
private generateApps(room: Room): IApp[] {
@ -128,7 +109,7 @@ export default class WidgetStore extends AsyncStoreWithClient<IState> {
private loadRoomWidgets(room: Room) {
if (!room) return;
const roomInfo = this.roomMap.get(room.roomId);
const roomInfo = this.roomMap.get(room.roomId) || <IRoomWidgets>{};
roomInfo.widgets = [];
// first clean out old widgets from the map which originate from this room
@ -138,6 +119,7 @@ export default class WidgetStore extends AsyncStoreWithClient<IState> {
this.widgetMap.delete(widgetUid(app));
});
let edited = false;
this.generateApps(room).forEach(app => {
// Sanity check for https://github.com/vector-im/element-web/issues/15705
const existingApp = this.widgetMap.get(widgetUid(app));
@ -150,172 +132,33 @@ export default class WidgetStore extends AsyncStoreWithClient<IState> {
this.widgetMap.set(widgetUid(app), app);
roomInfo.widgets.push(app);
edited = true;
});
if (edited && !this.roomMap.has(room.roomId)) {
this.roomMap.set(room.roomId, roomInfo);
}
this.emit(room.roomId);
}
private onRoom = (room: Room) => {
this.initRoom(room.roomId);
this.loadRoomWidgets(room);
this.emit(UPDATE_EVENT, room.roomId);
};
private onRoomStateEvents = (ev: MatrixEvent) => {
if (ev.getType() !== "im.vector.modular.widgets") return;
if (ev.getType() !== "im.vector.modular.widgets") return; // TODO: Support m.widget too
const roomId = ev.getRoomId();
this.initRoom(roomId);
this.loadRoomWidgets(this.matrixClient.getRoom(roomId));
this.emit(UPDATE_EVENT);
this.emit(UPDATE_EVENT, roomId);
};
public getRoom = (roomId: string) => {
public getRoom = (roomId: string, initIfNeeded = false) => {
if (initIfNeeded) this.initRoom(roomId); // internally handles "if needed"
return this.roomMap.get(roomId);
};
private onPinnedWidgetsChange = (settingName: string, roomId: string) => {
this.initRoom(roomId);
const pinned: PinnedWidgets = SettingsStore.getValue(settingName, roomId);
// Sanity check for https://github.com/vector-im/element-web/issues/15705
const roomInfo = this.getRoom(roomId);
const remappedPinned: PinnedWidgets = {};
for (const widgetId of Object.keys(pinned)) {
const isPinned = pinned[widgetId];
if (!roomInfo.widgets?.some(w => w.id === widgetId)) {
console.warn(`Skipping pinned widget update for ${widgetId} in ${roomId} -- wrong room`);
} else {
remappedPinned[widgetId] = isPinned;
}
}
roomInfo.pinned = remappedPinned;
this.emit(roomId);
this.emit(UPDATE_EVENT);
};
public isPinned(roomId: string, widgetId: string) {
return !!this.getPinnedApps(roomId).find(w => w.id === widgetId);
}
// dev note: we don't need the widgetId on this function, but the contract makes more sense
// when we require it.
public canPin(roomId: string, widgetId: string) {
return this.getPinnedApps(roomId).length < MAX_PINNED;
}
public pinWidget(roomId: string, widgetId: string) {
const roomInfo = this.getRoom(roomId);
if (!roomInfo) return;
// When pinning, first confirm all the widgets (Jitsi) which were autopinned so that the order is correct
const autoPinned = this.getPinnedApps(roomId).filter(app => !roomInfo.pinned[app.id]);
autoPinned.forEach(app => {
this.setPinned(roomId, app.id, true);
});
this.setPinned(roomId, widgetId, true);
// Show the apps drawer upon the user pinning a widget
if (RoomViewStore.getRoomId() === roomId) {
defaultDispatcher.dispatch({
action: "appsDrawer",
show: true,
});
}
}
public unpinWidget(roomId: string, widgetId: string) {
this.setPinned(roomId, widgetId, false);
}
private setPinned(roomId: string, widgetId: string, value: boolean) {
const roomInfo = this.getRoom(roomId);
if (!roomInfo) return;
if (roomInfo.pinned[widgetId] === false && value) {
// delete this before write to maintain the correct object insertion order
delete roomInfo.pinned[widgetId];
}
roomInfo.pinned[widgetId] = value;
// Clean up the pinned record
Object.keys(roomInfo).forEach(wId => {
if (!roomInfo.widgets.some(w => w.id === wId) || !roomInfo.pinned[wId]) {
delete roomInfo.pinned[wId];
}
});
SettingsStore.setValue("Widgets.pinned", roomId, SettingLevel.ROOM_ACCOUNT, roomInfo.pinned);
this.emit(roomId);
this.emit(UPDATE_EVENT);
}
public movePinnedWidget(roomId: string, widgetId: string, delta: 1 | -1) {
// TODO simplify this by changing the storage medium of pinned to an array once the Jitsi default-on goes away
const roomInfo = this.getRoom(roomId);
if (!roomInfo || roomInfo.pinned[widgetId] === false) return;
const pinnedApps = this.getPinnedApps(roomId).map(app => app.id);
const i = pinnedApps.findIndex(id => id === widgetId);
if (delta > 0) {
pinnedApps.splice(i, 2, pinnedApps[i + 1], pinnedApps[i]);
} else {
pinnedApps.splice(i - 1, 2, pinnedApps[i], pinnedApps[i - 1]);
}
const reorderedPinned: IRoomWidgets["pinned"] = {};
pinnedApps.forEach(id => {
reorderedPinned[id] = true;
});
Object.keys(roomInfo.pinned).forEach(id => {
if (reorderedPinned[id] === undefined) {
reorderedPinned[id] = roomInfo.pinned[id];
}
});
roomInfo.pinned = reorderedPinned;
SettingsStore.setValue("Widgets.pinned", roomId, SettingLevel.ROOM_ACCOUNT, roomInfo.pinned);
this.emit(roomId);
this.emit(UPDATE_EVENT);
}
public getPinnedApps(roomId: string): IApp[] {
// returns the apps in the order they were pinned with, up to the maximum
const roomInfo = this.getRoom(roomId);
if (!roomInfo) return [];
// Show Jitsi widgets even if the user already had the maximum pinned, instead of their latest pinned,
// except if the user already explicitly unpinned the Jitsi widget
const priorityWidget = roomInfo.widgets.find(widget => {
return roomInfo.pinned[widget.id] === undefined && WidgetType.JITSI.matches(widget.type);
});
const order = Object.keys(roomInfo.pinned).filter(k => roomInfo.pinned[k]);
const apps = order
.map(wId => Array.from(this.widgetMap.values())
.find(w2 => w2.roomId === roomId && w2.id === wId))
.filter(Boolean)
.slice(0, priorityWidget ? MAX_PINNED - 1 : MAX_PINNED);
if (priorityWidget) {
apps.push(priorityWidget);
}
// Sanity check for https://github.com/vector-im/element-web/issues/15705
// We union the app IDs the above generated with the roomInfo's known widgets to
// get a list of IDs which both exist. We then diff that against the generated app
// IDs above to ensure that all of the app IDs are captured by the union with the
// room - if we grabbed a widget that wasn't part of the roomInfo's list, it wouldn't
// be in the union and thus result in a diff.
const appIds = apps.map(a => widgetUid(a));
const roomAppIds = roomInfo.widgets.map(a => widgetUid(a));
const roomAppIdsUnion = arrayUnion(appIds, roomAppIds);
const missingSomeApps = arrayHasDiff(roomAppIdsUnion, appIds);
if (missingSomeApps) {
const diff = arrayDiff(roomAppIdsUnion, appIds);
console.warn(
`${roomId} appears to have a conflict for which widgets belong to it. ` +
`Widget UIDs are: `, [...diff.added, ...diff.removed],
);
}
return apps;
}
public getApps(roomId: string): IApp[] {
const roomInfo = this.getRoom(roomId);
return roomInfo?.widgets || [];

View file

@ -30,7 +30,7 @@ import { UPDATE_EVENT } from "../AsyncStore";
// Emitted event for when a room's preview has changed. First argument will the room for which
// the change happened.
export const ROOM_PREVIEW_CHANGED = "room_preview_changed";
const ROOM_PREVIEW_CHANGED = "room_preview_changed";
const PREVIEWS = {
'm.room.message': {
@ -84,6 +84,10 @@ export class MessagePreviewStore extends AsyncStoreWithClient<IState> {
return MessagePreviewStore.internalInstance;
}
public static getPreviewChangedEventName(room: Room): string {
return `${ROOM_PREVIEW_CHANGED}:${room?.roomId}`;
}
/**
* Gets the pre-translated preview for a given room
* @param room The room to get the preview for.
@ -150,7 +154,7 @@ export class MessagePreviewStore extends AsyncStoreWithClient<IState> {
// We've muted the underlying Map, so just emit that we've changed.
this.previews.set(room.roomId, map);
this.emit(UPDATE_EVENT, this);
this.emit(ROOM_PREVIEW_CHANGED, room);
this.emit(MessagePreviewStore.getPreviewChangedEventName(room), room);
}
return; // we're done
}
@ -158,7 +162,7 @@ export class MessagePreviewStore extends AsyncStoreWithClient<IState> {
// At this point, we didn't generate a preview so clear it
this.previews.set(room.roomId, new Map<TagID|TAG_ANY, string|null>());
this.emit(UPDATE_EVENT, this);
this.emit(ROOM_PREVIEW_CHANGED, room);
this.emit(MessagePreviewStore.getPreviewChangedEventName(room), room);
}
protected async onAction(payload: ActionPayload) {

View file

@ -89,10 +89,6 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
return this.algorithm.getOrderedRooms();
}
public get matrixClient(): MatrixClient {
return super.matrixClient;
}
// Intended for test usage
public async resetStore() {
await this.reset();
@ -114,7 +110,7 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
// Public for test usage. Do not call this.
public async makeReady(forcedClient?: MatrixClient) {
if (forcedClient) {
super.matrixClient = forcedClient;
this.readyStore.useUnitTestClient(forcedClient);
}
this.checkLoggingEnabled();

View file

@ -16,6 +16,7 @@
import {Room} from "matrix-js-sdk/src/models/room";
import { RoomListCustomisations } from "../../../customisations/RoomList";
import { isVirtualRoom, voipUserMapperEnabled } from "../../../VoipUserMapper";
export class VisibilityProvider {
private static internalInstance: VisibilityProvider;
@ -31,18 +32,13 @@ export class VisibilityProvider {
}
public isRoomVisible(room: Room): boolean {
/* eslint-disable prefer-const */
let isVisible = true; // Returned at the end of this function
let forced = false; // When true, this function won't bother calling the customisation points
/* eslint-enable prefer-const */
// ------
// TODO: The `if` statements to control visibility of custom room types
// would go here. The remainder of this function assumes that the statements
// will be here.
//
// When removing this comment block, please remove the lint disable lines in the area.
// ------
if (voipUserMapperEnabled() && isVirtualRoom(room.roomId)) {
isVisible = false;
forced = true;
}
const isVisibleFn = RoomListCustomisations.isRoomVisible;
if (!forced && isVisibleFn) {

View file

@ -20,9 +20,16 @@ export enum ElementWidgetActions {
ClientReady = "im.vector.ready",
HangupCall = "im.vector.hangup",
OpenIntegrationManager = "integration_manager_open",
/**
* @deprecated Use MSC2931 instead
*/
ViewRoom = "io.element.view_room",
}
/**
* @deprecated Use MSC2931 instead
*/
export interface IViewRoomApiRequest extends IWidgetApiRequest {
data: {
room_id: string; // eslint-disable-line camelcase

View file

@ -15,5 +15,8 @@
*/
export enum ElementWidgetCapabilities {
/**
* @deprecated Use MSC2931 instead.
*/
CanChangeViewedRoom = "io.element.view_room",
}

View file

@ -190,7 +190,7 @@ export class StopGapWidget extends EventEmitter {
private runUrlTemplate(opts = {asPopout: false}): string {
const templated = this.mockWidget.getCompleteUrl({
currentRoomId: RoomViewStore.getRoomId(),
widgetRoomId: this.roomId,
currentUserId: MatrixClientPeg.get().getUserId(),
userDisplayName: OwnProfileStore.instance.displayName,
userHttpAvatarUrl: OwnProfileStore.instance.getHttpAvatarUrl(),

View file

@ -43,6 +43,7 @@ import { EventType } from "matrix-js-sdk/src/@types/event";
import { CHAT_EFFECTS } from "../../effects";
import { containsEmoji } from "../../effects/utils";
import dis from "../../dispatcher/dispatcher";
import {tryTransformPermalinkToLocalHref} from "../../utils/permalinks/Permalinks";
// TODO: Purge this from the universe
@ -70,6 +71,10 @@ export class StopGapWidgetDriver extends WidgetDriver {
const stickerSendingCap = WidgetEventCapability.forRoomEvent(EventDirection.Send, EventType.Sticker).raw;
this.allowedCapabilities.add(MatrixCapabilities.StickerSending); // legacy as far as MSC2762 is concerned
this.allowedCapabilities.add(stickerSendingCap);
// Auto-approve the legacy visibility capability. We send it regardless of capability.
// Widgets don't technically need to request this capability, but Scalar still does.
this.allowedCapabilities.add("visibility");
}
}
@ -171,4 +176,12 @@ export class StopGapWidgetDriver extends WidgetDriver {
},
});
}
public async navigate(uri: string): Promise<void> {
const localUri = tryTransformPermalinkToLocalHref(uri);
if (!localUri || localUri === uri) { // parse failure can lead to an unmodified URL
throw new Error("Failed to transform URI");
}
window.location.hash = localUri; // it'll just be a fragment
}
}

View file

@ -0,0 +1,497 @@
/*
* Copyright 2021 The Matrix.org Foundation C.I.C.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import SettingsStore from "../../settings/SettingsStore";
import { Room } from "matrix-js-sdk/src/models/room";
import WidgetStore, { IApp } from "../WidgetStore";
import { WidgetType } from "../../widgets/WidgetType";
import { clamp, defaultNumber, sum } from "../../utils/numbers";
import defaultDispatcher from "../../dispatcher/dispatcher";
import { ReadyWatchingStore } from "../ReadyWatchingStore";
import { MatrixEvent } from "matrix-js-sdk/src/models/event";
import { SettingLevel } from "../../settings/SettingLevel";
import { arrayFastClone } from "../../utils/arrays";
import { UPDATE_EVENT } from "../AsyncStore";
export const WIDGET_LAYOUT_EVENT_TYPE = "io.element.widgets.layout";
export enum Container {
// "Top" is the app drawer, and currently the only sensible value.
Top = "top",
// "Right" is the right panel, and the default for widgets. Setting
// this as a container on a widget is essentially like saying "no
// changes needed", though this may change in the future.
Right = "right",
// ... more as needed. Note that most of this code assumes that there
// are only two containers, and that only the top container is special.
}
export interface IStoredLayout {
// Where to store the widget. Required.
container: Container;
// The index (order) to position the widgets in. Only applies for
// ordered containers (like the top container). Smaller numbers first,
// and conflicts resolved by comparing widget IDs.
index?: number;
// Percentage (integer) for relative width of the container to consume.
// Clamped to 0-100 and may have minimums imposed upon it. Only applies
// to containers which support inner resizing (currently only the top
// container).
width?: number;
// Percentage (integer) for relative height of the container. Note that
// this only applies to the top container currently, and that container
// will take the highest value among widgets in the container. Clamped
// to 0-100 and may have minimums imposed on it.
height?: number;
// TODO: [Deferred] Maximizing (fullscreen) widgets by default.
}
interface IWidgetLayouts {
[widgetId: string]: IStoredLayout;
}
interface ILayoutStateEvent {
// TODO: [Deferred] Forced layout (fixed with no changes)
// The widget layouts.
widgets: IWidgetLayouts;
}
interface ILayoutSettings extends ILayoutStateEvent {
overrides?: string; // event ID for layout state event, if present
}
// Dev note: "Pinned" widgets are ones in the top container.
export const MAX_PINNED = 3;
// These two are whole percentages and don't really mean anything. Later values will decide
// minimum, but these help determine proportions during our calculations here. In fact, these
// values should be *smaller* than the actual minimums imposed by later components.
const MIN_WIDGET_WIDTH_PCT = 10; // 10%
const MIN_WIDGET_HEIGHT_PCT = 2; // 2%
export class WidgetLayoutStore extends ReadyWatchingStore {
private static internalInstance: WidgetLayoutStore;
private byRoom: {
[roomId: string]: {
// @ts-ignore - TS wants a string key, but we know better
[container: Container]: {
ordered: IApp[];
height?: number;
distributions?: number[];
};
};
} = {};
private pinnedRef: string;
private layoutRef: string;
private constructor() {
super(defaultDispatcher);
}
public static get instance(): WidgetLayoutStore {
if (!WidgetLayoutStore.internalInstance) {
WidgetLayoutStore.internalInstance = new WidgetLayoutStore();
}
return WidgetLayoutStore.internalInstance;
}
public static emissionForRoom(room: Room): string {
return `update_${room.roomId}`;
}
private emitFor(room: Room) {
this.emit(WidgetLayoutStore.emissionForRoom(room));
}
protected async onReady(): Promise<any> {
this.updateAllRooms();
this.matrixClient.on("RoomState.events", this.updateRoomFromState);
this.pinnedRef = SettingsStore.watchSetting("Widgets.pinned", null, this.updateFromSettings);
this.layoutRef = SettingsStore.watchSetting("Widgets.layout", null, this.updateFromSettings);
WidgetStore.instance.on(UPDATE_EVENT, this.updateFromWidgetStore);
}
protected async onNotReady(): Promise<any> {
this.byRoom = {};
SettingsStore.unwatchSetting(this.pinnedRef);
SettingsStore.unwatchSetting(this.layoutRef);
WidgetStore.instance.off(UPDATE_EVENT, this.updateFromWidgetStore);
}
private updateAllRooms = () => {
this.byRoom = {};
for (const room of this.matrixClient.getVisibleRooms()) {
this.recalculateRoom(room);
}
};
private updateFromWidgetStore = (roomId?: string) => {
if (roomId) {
const room = this.matrixClient.getRoom(roomId);
if (room) this.recalculateRoom(room);
} else {
this.updateAllRooms();
}
};
private updateRoomFromState = (ev: MatrixEvent) => {
if (ev.getType() !== WIDGET_LAYOUT_EVENT_TYPE) return;
const room = this.matrixClient.getRoom(ev.getRoomId());
if (room) this.recalculateRoom(room);
};
private updateFromSettings = (settingName: string, roomId: string /* and other stuff */) => {
if (roomId) {
const room = this.matrixClient.getRoom(roomId);
if (room) this.recalculateRoom(room);
} else {
this.updateAllRooms();
}
};
private recalculateRoom(room: Room) {
const widgets = WidgetStore.instance.getApps(room.roomId);
if (!widgets?.length) {
this.byRoom[room.roomId] = {};
this.emitFor(room);
return;
}
const beforeChanges = JSON.stringify(this.byRoom[room.roomId]);
const layoutEv = room.currentState.getStateEvents(WIDGET_LAYOUT_EVENT_TYPE, "");
const legacyPinned = SettingsStore.getValue("Widgets.pinned", room.roomId);
let userLayout = SettingsStore.getValue<ILayoutSettings>("Widgets.layout", room.roomId);
if (layoutEv && userLayout && userLayout.overrides !== layoutEv.getId()) {
// For some other layout that we don't really care about. The user can reset this
// by updating their personal layout.
userLayout = null;
}
const roomLayout: ILayoutStateEvent = layoutEv ? layoutEv.getContent() : null;
// We essentially just need to find the top container's widgets because we
// only have two containers. Anything not in the top widget by the end of this
// function will go into the right container.
const topWidgets: IApp[] = [];
const rightWidgets: IApp[] = [];
for (const widget of widgets) {
const stateContainer = roomLayout?.widgets?.[widget.id]?.container;
const manualContainer = userLayout?.widgets?.[widget.id]?.container;
const isLegacyPinned = !!legacyPinned?.[widget.id];
const defaultContainer = WidgetType.JITSI.matches(widget.type) ? Container.Top : Container.Right;
if (manualContainer === Container.Right) {
rightWidgets.push(widget);
} else if (manualContainer === Container.Top || stateContainer === Container.Top) {
topWidgets.push(widget);
} else if (isLegacyPinned && !stateContainer) {
topWidgets.push(widget);
} else {
(defaultContainer === Container.Top ? topWidgets : rightWidgets).push(widget);
}
}
// Trim to MAX_PINNED
const runoff = topWidgets.slice(MAX_PINNED);
rightWidgets.push(...runoff);
// Order the widgets in the top container, putting autopinned Jitsi widgets first
// unless they have a specific order in mind
topWidgets.sort((a, b) => {
const layoutA = roomLayout?.widgets?.[a.id];
const layoutB = roomLayout?.widgets?.[b.id];
const userLayoutA = userLayout?.widgets?.[a.id];
const userLayoutB = userLayout?.widgets?.[b.id];
// Jitsi widgets are defaulted to be the leftmost widget whereas other widgets
// default to the right side.
const defaultA = WidgetType.JITSI.matches(a.type) ? Number.MIN_SAFE_INTEGER : Number.MAX_SAFE_INTEGER;
const defaultB = WidgetType.JITSI.matches(b.type) ? Number.MIN_SAFE_INTEGER : Number.MAX_SAFE_INTEGER;
const orderA = defaultNumber(userLayoutA?.index, defaultNumber(layoutA?.index, defaultA));
const orderB = defaultNumber(userLayoutB?.index, defaultNumber(layoutB?.index, defaultB));
if (orderA === orderB) {
// We just need a tiebreak
return a.id.localeCompare(b.id);
}
return orderA - orderB;
});
// Determine width distribution and height of the top container now (the only relevant one)
const widths: number[] = [];
let maxHeight = null; // null == default
let doAutobalance = true;
for (let i = 0; i < topWidgets.length; i++) {
const widget = topWidgets[i];
const widgetLayout = roomLayout?.widgets?.[widget.id];
const userWidgetLayout = userLayout?.widgets?.[widget.id];
if (Number.isFinite(userWidgetLayout?.width) || Number.isFinite(widgetLayout?.width)) {
const val = userWidgetLayout?.width || widgetLayout?.width;
const normalized = clamp(val, MIN_WIDGET_WIDTH_PCT, 100);
widths.push(normalized);
doAutobalance = false; // a manual width was specified
} else {
widths.push(100); // we'll figure this out later
}
if (widgetLayout?.height || userWidgetLayout?.height) {
const defRoomHeight = defaultNumber(widgetLayout?.height, MIN_WIDGET_HEIGHT_PCT);
const h = defaultNumber(userWidgetLayout?.height, defRoomHeight);
maxHeight = Math.max(maxHeight, clamp(h, MIN_WIDGET_HEIGHT_PCT, 100));
}
}
if (doAutobalance) {
for (let i = 0; i < widths.length; i++) {
widths[i] = 100 / widths.length;
}
} else {
// If we're not autobalancing then it means that we're trying to make
// sure that widgets make up exactly 100% of space (not over, not under)
const difference = sum(...widths) - 100; // positive = over, negative = under
if (difference < 0) {
// For a deficit we just fill everything in equally
for (let i = 0; i < widths.length; i++) {
widths[i] += Math.abs(difference) / widths.length;
}
} else if (difference > 0) {
// When we're over, we try to scale all the widgets within range first.
// We clamp values to try and keep ourselves sane and within range.
for (let i = 0; i < widths.length; i++) {
widths[i] = clamp(widths[i] - (difference / widths.length), MIN_WIDGET_WIDTH_PCT, 100);
}
// If we're still over, find the widgets which have more width than the minimum
// and balance them out until we're at 100%. This should keep us as close as possible
// to the intended distributions.
//
// Note: if we ever decide to set a minimum which is larger than 100%/MAX_WIDGETS then
// we probably have other issues - this code assumes we don't do that.
const toReclaim = sum(...widths) - 100;
if (toReclaim > 0) {
const largeIndices = widths
.map((v, i) => ([i, v]))
.filter(p => p[1] > MIN_WIDGET_WIDTH_PCT)
.map(p => p[0]);
for (const idx of largeIndices) {
widths[idx] -= toReclaim / largeIndices.length;
}
}
}
}
// Finally, fill in our cache and update
this.byRoom[room.roomId] = {};
if (topWidgets.length) {
this.byRoom[room.roomId][Container.Top] = {
ordered: topWidgets,
distributions: widths,
height: maxHeight,
};
}
if (rightWidgets.length) {
this.byRoom[room.roomId][Container.Right] = {
ordered: rightWidgets,
};
}
const afterChanges = JSON.stringify(this.byRoom[room.roomId]);
if (afterChanges !== beforeChanges) {
this.emitFor(room);
}
}
public getContainerWidgets(room: Room, container: Container): IApp[] {
return this.byRoom[room.roomId]?.[container]?.ordered || [];
}
public isInContainer(room: Room, widget: IApp, container: Container): boolean {
return this.getContainerWidgets(room, container).some(w => w.id === widget.id);
}
public canAddToContainer(room: Room, container: Container): boolean {
return this.getContainerWidgets(room, container).length < MAX_PINNED;
}
public getResizerDistributions(room: Room, container: Container): string[] { // yes, string.
let distributions = this.byRoom[room.roomId]?.[container]?.distributions;
if (!distributions || distributions.length < 2) return [];
// The distributor actually expects to be fed N-1 sizes and expands the middle section
// instead of the edges. Therefore, we need to return [0] when there's two widgets or
// [0, 2] when there's three (skipping [1] because it's irrelevant).
if (distributions.length === 2) distributions = [distributions[0]];
if (distributions.length === 3) distributions = [distributions[0], distributions[2]];
return distributions.map(d => `${d.toFixed(1)}%`); // actual percents - these are decoded later
}
public setResizerDistributions(room: Room, container: Container, distributions: string[]) {
if (container !== Container.Top) return; // ignore - not relevant
const numbers = distributions.map(d => Number(Number(d.substring(0, d.length - 1)).toFixed(1)));
const widgets = this.getContainerWidgets(room, container);
// From getResizerDistributions, we need to fill in the middle size if applicable.
const remaining = 100 - sum(...numbers);
if (numbers.length === 2) numbers.splice(1, 0, remaining);
if (numbers.length === 1) numbers.push(remaining);
const localLayout = {};
widgets.forEach((w, i) => {
localLayout[w.id] = {
container: container,
width: numbers[i],
index: i,
height: this.byRoom[room.roomId]?.[container]?.height || MIN_WIDGET_HEIGHT_PCT,
};
});
this.updateUserLayout(room, localLayout);
}
public getContainerHeight(room: Room, container: Container): number {
return this.byRoom[room.roomId]?.[container]?.height; // let the default get returned if needed
}
public setContainerHeight(room: Room, container: Container, height: number) {
const widgets = this.getContainerWidgets(room, container);
const widths = this.byRoom[room.roomId]?.[container]?.distributions;
const localLayout = {};
widgets.forEach((w, i) => {
localLayout[w.id] = {
container: container,
width: widths[i],
index: i,
height: height,
};
});
this.updateUserLayout(room, localLayout);
}
public moveWithinContainer(room: Room, container: Container, widget: IApp, delta: number) {
const widgets = arrayFastClone(this.getContainerWidgets(room, container));
const currentIdx = widgets.findIndex(w => w.id === widget.id);
if (currentIdx < 0) return; // no change needed
widgets.splice(currentIdx, 1); // remove existing widget
const newIdx = clamp(currentIdx + delta, 0, widgets.length);
widgets.splice(newIdx, 0, widget);
const widths = this.byRoom[room.roomId]?.[container]?.distributions;
const height = this.byRoom[room.roomId]?.[container]?.height;
const localLayout = {};
widgets.forEach((w, i) => {
localLayout[w.id] = {
container: container,
width: widths[i],
index: i,
height: height,
};
});
this.updateUserLayout(room, localLayout);
}
public moveToContainer(room: Room, widget: IApp, toContainer: Container) {
const allWidgets = this.getAllWidgets(room);
if (!allWidgets.some(([w])=> w.id === widget.id)) return; // invalid
this.updateUserLayout(room, {
[widget.id]: {container: toContainer},
});
}
public canCopyLayoutToRoom(room: Room): boolean {
if (!this.matrixClient) return false; // not ready yet
return room.currentState.maySendStateEvent(WIDGET_LAYOUT_EVENT_TYPE, this.matrixClient.getUserId());
}
public copyLayoutToRoom(room: Room) {
const allWidgets = this.getAllWidgets(room);
const evContent: ILayoutStateEvent = {widgets: {}};
for (const [widget, container] of allWidgets) {
evContent.widgets[widget.id] = {container};
if (container === Container.Top) {
const containerWidgets = this.getContainerWidgets(room, container);
const idx = containerWidgets.findIndex(w => w.id === widget.id);
const widths = this.byRoom[room.roomId]?.[container]?.distributions;
const height = this.byRoom[room.roomId]?.[container]?.height;
evContent.widgets[widget.id] = {
...evContent.widgets[widget.id],
height: height ? Math.round(height) : null,
width: widths[idx] ? Math.round(widths[idx]) : null,
index: idx,
};
}
}
this.matrixClient.sendStateEvent(room.roomId, WIDGET_LAYOUT_EVENT_TYPE, evContent, "");
}
private getAllWidgets(room: Room): [IApp, Container][] {
const containers = this.byRoom[room.roomId];
if (!containers) return [];
const ret = [];
for (const container of Object.keys(containers)) {
const widgets = containers[container].ordered;
for (const widget of widgets) {
ret.push([widget, container]);
}
}
return ret;
}
private updateUserLayout(room: Room, newLayout: IWidgetLayouts) {
// Polyfill any missing widgets
const allWidgets = this.getAllWidgets(room);
for (const [widget, container] of allWidgets) {
const containerWidgets = this.getContainerWidgets(room, container);
const idx = containerWidgets.findIndex(w => w.id === widget.id);
const widths = this.byRoom[room.roomId]?.[container]?.distributions;
if (!newLayout[widget.id]) {
newLayout[widget.id] = {
container: container,
index: idx,
height: this.byRoom[room.roomId]?.[container]?.height,
width: widths?.[idx],
};
}
}
const layoutEv = room.currentState.getStateEvents(WIDGET_LAYOUT_EVENT_TYPE, "");
SettingsStore.setValue("Widgets.layout", room.roomId, SettingLevel.ROOM_ACCOUNT, {
overrides: layoutEv?.getId(),
widgets: newLayout,
}).catch(() => this.recalculateRoom(room));
this.recalculateRoom(room); // call to try local echo on changes (the catch above undoes any errors)
}
}
window.mxWidgetLayoutStore = WidgetLayoutStore.instance;