Files
ThreadNet-Web/src/utils/WidgetUtils.ts
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

573 lines
22 KiB
TypeScript
Raw Normal View History

/*
2024-09-09 14:57:16 +01:00
Copyright 2024 New Vector Ltd.
Copyright 2017-2020 The Matrix.org Foundation C.I.C.
Copyright 2019 Travis Ralston
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
2024-09-09 14:57:16 +01:00
Please see LICENSE files in the repository root for full details.
*/
import { useCallback, useEffect, useState } from "react";
2022-03-22 18:14:11 -04:00
import { base32 } from "rfc4648";
2025-01-21 13:54:57 +00:00
import { capitalize } from "lodash";
import { IWidget, IWidgetData } from "matrix-widget-api";
import { Room, ClientEvent, MatrixClient, RoomStateEvent, MatrixEvent } from "matrix-js-sdk/src/matrix";
import { KnownMembership } from "matrix-js-sdk/src/types";
2021-10-22 17:23:32 -05:00
import { logger } from "matrix-js-sdk/src/logger";
2022-03-22 18:14:11 -04:00
import { CallType } from "matrix-js-sdk/src/webrtc/call";
2025-01-21 13:54:57 +00:00
import { LOWERCASE, secureRandomString, secureRandomStringFrom } from "matrix-js-sdk/src/randomstring";
import PlatformPeg from "../PlatformPeg";
2018-06-26 11:59:16 +01:00
import SdkConfig from "../SdkConfig";
2020-05-13 20:41:41 -06:00
import dis from "../dispatcher/dispatcher";
2018-07-03 11:16:44 +01:00
import WidgetEchoStore from "../stores/WidgetEchoStore";
2021-06-18 16:21:46 +01:00
import { IntegrationManagers } from "../integrations/IntegrationManagers";
import { WidgetType } from "../widgets/WidgetType";
2022-03-22 18:14:11 -04:00
import { Jitsi } from "../widgets/Jitsi";
2021-06-18 16:21:46 +01:00
import { objectClone } from "./objects";
import { _t } from "../languageHandler";
import WidgetStore, { IApp, isAppWidget } from "../stores/WidgetStore";
import { parseUrl } from "./UrlUtils";
import { useEventEmitter } from "../hooks/useEventEmitter";
import { WidgetLayoutStore } from "../stores/widgets/WidgetLayoutStore";
import { IWidgetEvent, UserWidget } from "./WidgetUtils-types";
// How long we wait for the state event echo to come back from the server
// before waitFor[Room/User]Widget rejects its promise
const WIDGET_WAIT_TIME = 20000;
export type { IWidgetEvent, UserWidget };
2018-07-12 18:43:49 +01:00
export default class WidgetUtils {
/**
* Returns true if user is able to send state events to modify widgets in this room
2018-04-02 10:02:41 +01:00
* (Does not apply to non-room-based / user widgets)
* @param client The matrix client of the logged-in user
* @param roomId -- The ID of the room to check
* @return Boolean -- true if the user can modify widgets in this room
* @throws Error -- specifies the error reason
*/
public static canUserModifyWidgets(client: MatrixClient, roomId?: string): boolean {
if (!roomId) {
2021-10-15 16:31:29 +02:00
logger.warn("No room ID specified");
2017-08-01 11:39:17 +01:00
return false;
}
if (!client) {
2021-10-15 16:31:29 +02:00
logger.warn("User must be be logged in");
2017-08-01 11:39:17 +01:00
return false;
}
const room = client.getRoom(roomId);
if (!room) {
2021-10-15 16:31:29 +02:00
logger.warn(`Room ID ${roomId} is not recognised`);
2017-08-01 11:39:17 +01:00
return false;
}
const me = client.getUserId();
if (!me) {
2021-10-15 16:31:29 +02:00
logger.warn("Failed to get user ID");
2017-08-01 11:39:17 +01:00
return false;
}
if (room.getMyMembership() !== KnownMembership.Join) {
2021-10-15 16:31:29 +02:00
logger.warn(`User ${me} is not in room ${roomId}`);
2017-08-01 11:39:17 +01:00
return false;
}
// TODO: Enable support for m.widget event type (https://github.com/vector-im/element-web/issues/13111)
2017-08-01 11:41:41 +01:00
return room.currentState.maySendStateEvent("im.vector.modular.widgets", me);
}
2018-05-27 11:12:55 -06:00
// TODO: Generify the name of this function. It's not just scalar.
2018-05-27 11:12:55 -06:00
/**
* Returns true if specified url is a scalar URL, typically https://scalar.vector.im/api
* @param matrixClient The matrix client of the logged-in user
2018-05-27 11:12:55 -06:00
* @param {[type]} testUrlString URL to check
* @return {Boolean} True if specified URL is a scalar URL
*/
public static isScalarUrl(testUrlString?: string): boolean {
2018-05-27 11:12:55 -06:00
if (!testUrlString) {
2021-10-15 16:30:53 +02:00
logger.error("Scalar URL check failed. No URL specified");
2018-05-27 11:12:55 -06:00
return false;
}
const testUrl = parseUrl(testUrlString);
2018-05-27 11:12:55 -06:00
let scalarUrls = SdkConfig.get().integrations_widgets_urls;
if (!scalarUrls || scalarUrls.length === 0) {
const defaultManager = IntegrationManagers.sharedInstance().getPrimaryManager();
if (defaultManager) {
scalarUrls = [defaultManager.apiUrl];
} else {
scalarUrls = [];
}
2018-05-27 11:12:55 -06:00
}
for (let i = 0; i < scalarUrls.length; i++) {
const scalarUrl = parseUrl(scalarUrls[i]);
2018-05-27 11:12:55 -06:00
if (testUrl && scalarUrl) {
if (
testUrl.protocol === scalarUrl.protocol &&
testUrl.host === scalarUrl.host &&
scalarUrl.pathname &&
testUrl.pathname?.startsWith(scalarUrl.pathname)
2018-05-27 11:12:55 -06:00
) {
return true;
}
}
}
return false;
}
2018-06-13 10:39:52 +01:00
/**
* Returns a promise that resolves when a widget with the given
* ID has been added as a user widget (ie. the accountData event
* arrives) or rejects after a timeout
*
* @param client The matrix client of the logged-in user
* @param widgetId The ID of the widget to wait for
* @param add True to wait for the widget to be added,
2018-06-13 10:39:52 +01:00
* false to wait for it to be deleted.
2018-06-14 13:49:23 +01:00
* @returns {Promise} that resolves when the widget is in the
2018-06-14 13:03:42 +01:00
* requested state according to the `add` param
2018-06-13 10:39:52 +01:00
*/
public static waitForUserWidget(client: MatrixClient, widgetId: string, add: boolean): Promise<void> {
2018-06-13 10:39:52 +01:00
return new Promise((resolve, reject) => {
// Tests an account data event, returning true if it's in the state
// we're waiting for it to be in
function eventInIntendedState(ev?: MatrixEvent): boolean {
if (!ev) return false;
2018-06-13 10:39:52 +01:00
if (add) {
return ev.getContent()[widgetId] !== undefined;
} else {
return ev.getContent()[widgetId] === undefined;
}
}
const startingAccountDataEvent = client.getAccountData("m.widgets");
if (eventInIntendedState(startingAccountDataEvent)) {
2018-06-13 10:39:52 +01:00
resolve();
return;
}
2023-02-13 11:39:16 +00:00
function onAccountData(ev: MatrixEvent): void {
const currentAccountDataEvent = client.getAccountData("m.widgets");
2018-06-13 10:39:52 +01:00
if (eventInIntendedState(currentAccountDataEvent)) {
client.removeListener(ClientEvent.AccountData, onAccountData);
2018-06-13 10:39:52 +01:00
clearTimeout(timerId);
resolve();
}
}
2022-11-30 11:32:56 +00:00
const timerId = window.setTimeout(() => {
client.removeListener(ClientEvent.AccountData, onAccountData);
2018-06-13 10:39:52 +01:00
reject(new Error("Timed out waiting for widget ID " + widgetId + " to appear"));
2018-07-03 11:55:41 +01:00
}, WIDGET_WAIT_TIME);
client.on(ClientEvent.AccountData, onAccountData);
2018-06-13 10:39:52 +01:00
});
}
/**
* Returns a promise that resolves when a widget with the given
* ID has been added as a room widget in the given room (ie. the
* room state event arrives) or rejects after a timeout
*
* @param client The matrix client of the logged-in user
* @param {string} widgetId The ID of the widget to wait for
* @param {string} roomId The ID of the room to wait for the widget in
* @param {boolean} add True to wait for the widget to be added,
* false to wait for it to be deleted.
2018-06-14 13:49:23 +01:00
* @returns {Promise} that resolves when the widget is in the
2018-06-14 13:03:42 +01:00
* requested state according to the `add` param
*/
public static waitForRoomWidget(
client: MatrixClient,
widgetId: string,
roomId: string,
add: boolean,
): Promise<void> {
return new Promise((resolve, reject) => {
// Tests a list of state events, returning true if it's in the state
// we're waiting for it to be in
function eventsInIntendedState(evList?: MatrixEvent[]): boolean {
const widgetPresent = evList?.some((ev) => {
return ev.getContent() && ev.getContent()["id"] === widgetId;
});
if (add) {
return !!widgetPresent;
} else {
return !widgetPresent;
}
}
const room = client.getRoom(roomId);
// TODO: Enable support for m.widget event type (https://github.com/vector-im/element-web/issues/13111)
const startingWidgetEvents = room?.currentState.getStateEvents("im.vector.modular.widgets");
if (eventsInIntendedState(startingWidgetEvents)) {
resolve();
return;
}
function onRoomStateEvents(ev: MatrixEvent): void {
if (ev.getRoomId() !== roomId || ev.getType() !== "im.vector.modular.widgets") return;
// TODO: Enable support for m.widget event type (https://github.com/vector-im/element-web/issues/13111)
const currentWidgetEvents = room?.currentState.getStateEvents("im.vector.modular.widgets");
if (eventsInIntendedState(currentWidgetEvents)) {
client.removeListener(RoomStateEvent.Events, onRoomStateEvents);
clearTimeout(timerId);
resolve();
}
}
2022-11-30 11:32:56 +00:00
const timerId = window.setTimeout(() => {
client.removeListener(RoomStateEvent.Events, onRoomStateEvents);
reject(new Error("Timed out waiting for widget ID " + widgetId + " to appear"));
2018-07-03 11:55:41 +01:00
}, WIDGET_WAIT_TIME);
client.on(RoomStateEvent.Events, onRoomStateEvents);
});
}
2018-06-25 15:30:04 +01:00
public static setUserWidget(
client: MatrixClient,
2020-09-24 09:49:30 +01:00
widgetId: string,
widgetType: WidgetType,
widgetUrl: string,
widgetName: string,
2020-10-19 20:56:41 +01:00
widgetData: IWidgetData,
): Promise<void> {
// Get the current widgets and clone them before we modify them, otherwise
// we'll modify the content of the old event.
const userWidgets = objectClone(WidgetUtils.getUserWidgets(client));
2018-06-25 15:30:04 +01:00
// Delete existing widget with ID
try {
delete userWidgets[widgetId];
2024-10-16 16:43:07 +01:00
} catch {
2021-10-15 16:30:53 +02:00
logger.error(`$widgetId is non-configurable`);
2018-06-25 15:30:04 +01:00
}
2018-06-26 16:33:28 +01:00
const addingWidget = Boolean(widgetUrl);
2018-06-26 15:21:22 +01:00
const userId = client.getSafeUserId();
const content = {
id: widgetId,
type: widgetType.preferred,
url: widgetUrl,
name: widgetName,
data: widgetData,
creatorUserId: userId,
};
2018-06-25 15:30:04 +01:00
// Add new widget / update
2018-06-26 15:21:22 +01:00
if (addingWidget) {
2018-06-25 15:30:04 +01:00
userWidgets[widgetId] = {
content: content,
sender: userId,
2018-06-25 15:30:04 +01:00
state_key: widgetId,
type: "m.widget",
id: widgetId,
};
}
// This starts listening for when the echo comes back from the server
// since the widget won't appear added until this happens. If we don't
// wait for this, the action will complete but if the user is fast enough,
// the widget still won't actually be there.
return client
.setAccountData("m.widgets", userWidgets)
.then(() => {
return WidgetUtils.waitForUserWidget(client, widgetId, addingWidget);
2018-06-25 15:30:04 +01:00
})
.then(() => {
dis.dispatch({ action: "user_widget_updated" });
});
}
public static setRoomWidget(
client: MatrixClient,
2020-09-24 09:49:30 +01:00
roomId: string,
widgetId: string,
2020-10-19 21:02:48 +01:00
widgetType?: WidgetType,
widgetUrl?: string,
widgetName?: string,
widgetData?: IWidgetData,
widgetAvatarUrl?: string,
): Promise<void> {
let content: Partial<IWidget> & { avatar_url?: string };
2018-06-25 15:30:04 +01:00
2018-06-26 16:33:28 +01:00
const addingWidget = Boolean(widgetUrl);
2018-06-26 15:21:22 +01:00
if (addingWidget) {
2018-06-25 15:30:04 +01:00
content = {
// TODO: Enable support for m.widget event type (https://github.com/vector-im/element-web/issues/13111)
// For now we'll send the legacy event type for compatibility with older apps/elements
type: widgetType?.legacy,
2018-06-25 15:30:04 +01:00
url: widgetUrl,
name: widgetName,
data: widgetData,
avatar_url: widgetAvatarUrl,
2018-06-25 15:30:04 +01:00
};
2018-06-26 15:21:22 +01:00
} else {
content = {};
2018-06-25 15:30:04 +01:00
}
return WidgetUtils.setRoomWidgetContent(client, roomId, widgetId, content as IWidget);
}
public static setRoomWidgetContent(
client: MatrixClient,
roomId: string,
widgetId: string,
content: IWidget & Record<string, any>,
): Promise<void> {
const addingWidget = !!content.url;
2018-07-05 18:43:20 +01:00
WidgetEchoStore.setRoomWidgetEcho(roomId, widgetId, content);
2018-07-03 11:16:44 +01:00
// TODO: Enable support for m.widget event type (https://github.com/vector-im/element-web/issues/13111)
2018-06-25 15:30:04 +01:00
return client
.sendStateEvent(roomId, "im.vector.modular.widgets", content, widgetId)
.then(() => {
return WidgetUtils.waitForRoomWidget(client, widgetId, roomId, addingWidget);
2018-07-03 11:16:44 +01:00
})
.finally(() => {
2018-07-05 18:43:20 +01:00
WidgetEchoStore.removeRoomWidgetEcho(roomId, widgetId);
2018-06-25 15:30:04 +01:00
});
}
2018-06-26 11:52:21 +01:00
/**
* Get room specific widgets
* @param {Room} room The room to get widgets force
2018-06-26 11:52:21 +01:00
* @return {[object]} Array containing current / active room widgets
*/
public static getRoomWidgets(room: Room): MatrixEvent[] {
// TODO: Enable support for m.widget event type (https://github.com/vector-im/element-web/issues/13111)
2018-06-26 11:52:21 +01:00
const appsStateEvents = room.currentState.getStateEvents("im.vector.modular.widgets");
if (!appsStateEvents) {
return [];
}
return appsStateEvents.filter((ev) => {
return ev.getContent().type && ev.getContent().url;
});
}
/**
* Get user specific widgets (not linked to a specific room)
* @param client The matrix client of the logged-in user
2018-06-26 11:52:21 +01:00
* @return {object} Event content object containing current / active user widgets
*/
public static getUserWidgets(client: MatrixClient | undefined): Record<string, UserWidget> {
2018-06-26 11:52:21 +01:00
if (!client) {
throw new Error("User not logged in");
}
const userWidgets = client.getAccountData("m.widgets");
if (userWidgets && userWidgets.getContent()) {
2018-06-26 15:41:43 +01:00
return userWidgets.getContent();
2018-06-26 11:52:21 +01:00
}
2018-06-26 15:41:43 +01:00
return {};
2018-06-26 11:52:21 +01:00
}
/**
* Get user specific widgets (not linked to a specific room) as an array
* @param client The matrix client of the logged-in user
2018-06-26 11:52:21 +01:00
* @return {[object]} Array containing current / active user widgets
*/
public static getUserWidgetsArray(client: MatrixClient | undefined): UserWidget[] {
return Object.values(WidgetUtils.getUserWidgets(client));
2018-06-26 11:52:21 +01:00
}
/**
* Get active stickerpicker widgets (stickerpickers are user widgets by nature)
* @param client The matrix client of the logged-in user
2018-06-26 11:52:21 +01:00
* @return {[object]} Array containing current / active stickerpicker widgets
*/
public static getStickerpickerWidgets(client: MatrixClient | undefined): UserWidget[] {
const widgets = WidgetUtils.getUserWidgetsArray(client);
return widgets.filter((widget) => widget.content?.type === "m.stickerpicker");
2018-06-26 11:52:21 +01:00
}
2019-08-09 17:35:59 -06:00
/**
* Get all integration manager widgets for this user.
* @param client The matrix client of the logged-in user
2019-08-09 17:35:59 -06:00
* @returns {Object[]} An array of integration manager user widgets.
*/
public static getIntegrationManagerWidgets(client: MatrixClient | undefined): UserWidget[] {
const widgets = WidgetUtils.getUserWidgetsArray(client);
return widgets.filter((w) => w.content?.type === "m.integration_manager");
2019-08-09 17:35:59 -06:00
}
2018-06-26 11:52:21 +01:00
/**
* Remove all stickerpicker widgets (stickerpickers are user widgets by nature)
* @param client The matrix client of the logged-in user
2018-06-26 11:52:21 +01:00
* @return {Promise} Resolves on account data updated
*/
public static async removeStickerpickerWidgets(client: MatrixClient | undefined): Promise<void> {
2018-06-26 11:52:21 +01:00
if (!client) {
throw new Error("User not logged in");
}
2019-08-21 18:43:29 -06:00
const widgets = client.getAccountData("m.widgets");
if (!widgets) return;
2020-10-19 20:56:41 +01:00
const userWidgets: Record<string, IWidgetEvent> = widgets.getContent() || {};
2018-06-26 11:52:21 +01:00
Object.entries(userWidgets).forEach(([key, widget]) => {
if (widget.content && widget.content.type === "m.stickerpicker") {
delete userWidgets[key];
}
});
2021-07-10 15:43:46 +01:00
await client.setAccountData("m.widgets", userWidgets);
2018-06-26 11:52:21 +01:00
}
2018-07-12 18:43:49 +01:00
public static async addJitsiWidget(
client: MatrixClient,
2022-03-22 18:14:11 -04:00
roomId: string,
type: CallType,
name: string,
isVideoChannel: boolean,
2022-03-22 18:14:11 -04:00
oobRoomName?: string,
): Promise<void> {
const domain = Jitsi.getInstance().preferredDomain;
const auth = (await Jitsi.getInstance().getJitsiAuth()) ?? undefined;
2025-01-21 13:54:57 +00:00
// Must be globally unique, although predicatablity is not important, the js-sdk has functions to generate
// secure ranom strings, and speed is not important here.
const widgetId = secureRandomString(24);
2022-03-22 18:14:11 -04:00
let confId: string;
2022-03-22 18:14:11 -04:00
if (auth === "openidtoken-jwt") {
// Create conference ID from room ID
// For compatibility with Jitsi, use base32 without padding.
// More details here:
// https://github.com/matrix-org/prosody-mod-auth-matrix-user-verification
2024-12-04 11:46:48 +00:00
confId = base32.stringify(new TextEncoder().encode(roomId), { pad: false });
2022-03-22 18:14:11 -04:00
} else {
2025-01-21 13:54:57 +00:00
// Create a random conference ID (capitalised so the name looks sensible in Jitsi)
confId = `Jitsi${capitalize(secureRandomStringFrom(24, LOWERCASE))}`;
2022-03-22 18:14:11 -04:00
}
// TODO: Remove URL hacks when the mobile clients eventually support v2 widgets
const widgetUrl = new URL(WidgetUtils.getLocalJitsiWrapperUrl({ auth }));
widgetUrl.search = ""; // Causes the URL class use searchParams instead
widgetUrl.searchParams.set("confId", confId);
await WidgetUtils.setRoomWidget(client, roomId, widgetId, WidgetType.JITSI, widgetUrl.toString(), name, {
2022-03-22 18:14:11 -04:00
conferenceId: confId,
roomName: oobRoomName ?? client.getRoom(roomId)?.name,
2022-03-22 18:14:11 -04:00
isAudioOnly: type === CallType.Voice,
isVideoChannel,
2022-03-22 18:14:11 -04:00
domain,
auth,
});
}
public static makeAppConfig(
2020-09-24 09:49:30 +01:00
appId: string,
app: Partial<IApp>,
senderUserId: string,
2022-09-16 11:12:27 -04:00
roomId: string | undefined,
eventId: string | undefined,
2020-09-24 09:49:30 +01:00
): IApp {
if (!senderUserId) {
throw new Error("Widgets must be created by someone - provide a senderUserId");
}
app.creatorUserId = senderUserId;
2018-07-12 18:43:49 +01:00
app.id = appId;
2020-09-07 16:17:25 +01:00
app.roomId = roomId;
app.eventId = eventId;
2018-07-12 18:43:49 +01:00
app.name = app.name || app.type;
2020-09-24 09:28:49 +01:00
return app as IApp;
2018-07-12 18:43:49 +01:00
}
public static getLocalJitsiWrapperUrl(opts: { forLocalRender?: boolean; auth?: string } = {}): string {
2020-03-18 15:50:05 -06:00
// NB. we can't just encodeURIComponent all of these because the $ signs need to be there
2020-09-08 11:31:40 +03:00
const queryStringParts = [
2020-03-18 15:50:05 -06:00
"conferenceDomain=$domain",
"conferenceId=$conferenceId",
"isAudioOnly=$isAudioOnly",
"startWithAudioMuted=$startWithAudioMuted",
"startWithVideoMuted=$startWithVideoMuted",
"isVideoChannel=$isVideoChannel",
2020-03-18 15:50:05 -06:00
"displayName=$matrix_display_name",
"avatarUrl=$matrix_avatar_url",
"userId=$matrix_user_id",
"roomId=$matrix_room_id",
2020-10-19 18:47:27 +01:00
"theme=$theme",
"roomName=$roomName",
`supportsScreensharing=${PlatformPeg.get()?.supportsJitsiScreensharing()}`,
2022-10-06 21:19:01 +02:00
"language=$org.matrix.msc2873.client_language",
];
if (opts.auth) {
2020-09-08 11:31:40 +03:00
queryStringParts.push(`auth=${opts.auth}`);
}
2020-09-08 11:31:40 +03:00
const queryString = queryStringParts.join("&");
2020-03-18 15:50:05 -06:00
let baseUrl = window.location.href;
if (window.location.protocol !== "https:" && !opts.forLocalRender) {
2020-03-18 15:50:05 -06:00
// Use an external wrapper if we're not locally rendering the widget. This is usually
// the URL that will end up in the widget event, so we want to make sure it's relatively
// safe to send.
// We'll end up using a local render URL when we see a Jitsi widget anyways, so this is
// really just for backwards compatibility and to appease the spec.
baseUrl = PlatformPeg.get()!.baseUrl;
2020-03-18 15:50:05 -06:00
}
const url = new URL("jitsi.html#" + queryString, baseUrl); // this strips hash fragment from baseUrl
return url.href;
2020-03-18 15:50:05 -06:00
}
2020-09-07 16:17:25 +01:00
public static getWidgetName(app?: IWidget): string {
return app?.name?.trim() || _t("widget|no_name");
2020-08-28 10:50:27 +01:00
}
public static getWidgetDataTitle(app?: IWidget): string {
2020-09-08 17:40:57 +01:00
return app?.data?.title?.trim() || "";
2020-08-28 10:50:27 +01:00
}
2020-09-08 10:19:51 +01:00
public static getWidgetUid(app?: IApp | IWidget): string {
return app ? WidgetUtils.calcWidgetUid(app.id, isAppWidget(app) ? app.roomId : undefined) : "";
}
public static calcWidgetUid(widgetId: string, roomId?: string): string {
return roomId ? `room_${roomId}_${widgetId}` : `user_${widgetId}`;
}
public static editWidget(room: Room, app: IWidget): void {
2022-05-06 12:46:26 -06:00
// noinspection JSIgnoredPromiseFromCall
IntegrationManagers.sharedInstance()
.getPrimaryManager()
?.open(room, "type_" + app.type, app.id);
2020-09-08 10:19:51 +01:00
}
2020-10-09 08:42:21 +01:00
public static isManagedByManager(app: IWidget): boolean {
2020-10-09 08:42:21 +01:00
if (WidgetUtils.isScalarUrl(app.url)) {
const managers = IntegrationManagers.sharedInstance();
if (managers.hasManager()) {
// TODO: Pick the right manager for the widget
const defaultManager = managers.getPrimaryManager();
return WidgetUtils.isScalarUrl(defaultManager?.apiUrl);
2020-10-09 08:42:21 +01:00
}
}
return false;
}
}
/**
* Hook to get the widgets for a room and update when they change
* @param room the room to get widgets for
*/
export const useWidgets = (room: Room): IApp[] => {
const [apps, setApps] = useState<IApp[]>(() => WidgetStore.instance.getApps(room.roomId));
const updateApps = useCallback(() => {
// Copy the array so that we always trigger a re-render, as some updates mutate the array of apps/settings
setApps([...WidgetStore.instance.getApps(room.roomId)]);
}, [room]);
useEffect(updateApps, [room, updateApps]);
useEventEmitter(WidgetStore.instance, room.roomId, updateApps);
useEventEmitter(WidgetLayoutStore.instance, WidgetLayoutStore.emissionForRoom(room), updateApps);
return apps;
};