Apply prettier formatting

This commit is contained in:
Michael Weimann
2022-12-12 12:24:14 +01:00
parent 1cac306093
commit 526645c791
1576 changed files with 65384 additions and 62477 deletions
+50 -37
View File
@@ -44,7 +44,7 @@ import { StopGapWidgetDriver } from "./StopGapWidgetDriver";
import { WidgetMessagingStore } from "./WidgetMessagingStore";
import { MatrixClientPeg } from "../../MatrixClientPeg";
import { OwnProfileStore } from "../OwnProfileStore";
import WidgetUtils from '../../utils/WidgetUtils';
import WidgetUtils from "../../utils/WidgetUtils";
import { IntegrationManagers } from "../../integrations/IntegrationManagers";
import SettingsStore from "../../settings/SettingsStore";
import { WidgetType } from "../../widgets/WidgetType";
@@ -108,13 +108,13 @@ export class ElementWidget extends Widget {
}
public get rawData(): IWidgetData {
let conferenceId = super.rawData['conferenceId'];
let conferenceId = super.rawData["conferenceId"];
if (conferenceId === undefined) {
// we'll need to parse the conference ID out of the URL for v1 Jitsi widgets
const parsedUrl = new URL(super.templateUrl); // use super to get the raw widget URL
conferenceId = parsedUrl.searchParams.get("confId");
}
let domain = super.rawData['domain'];
let domain = super.rawData["domain"];
if (domain === undefined) {
// v1 widgets default to meet.element.io regardless of user settings
domain = "meet.element.io";
@@ -144,10 +144,14 @@ export class ElementWidget extends Widget {
}
public getCompleteUrl(params: ITemplateParams, asPopout = false): string {
return runTemplate(asPopout ? this.popoutTemplateUrl : this.templateUrl, {
...this.rawDefinition,
data: this.rawData,
}, params);
return runTemplate(
asPopout ? this.popoutTemplateUrl : this.templateUrl,
{
...this.rawDefinition,
data: this.rawData,
},
params,
);
}
}
@@ -226,19 +230,19 @@ export class StopGapWidget extends EventEmitter {
// TODO: Replace these with proper widget params
// See https://github.com/matrix-org/matrix-doc/pull/1958/files#r405714833
if (!opts?.asPopout) {
parsed.searchParams.set('widgetId', this.mockWidget.id);
parsed.searchParams.set('parentUrl', window.location.href.split('#', 2)[0]);
parsed.searchParams.set("widgetId", this.mockWidget.id);
parsed.searchParams.set("parentUrl", window.location.href.split("#", 2)[0]);
// Give the widget a scalar token if we're supposed to (more legacy)
// TODO: Stop doing this
if (this.scalarToken) {
parsed.searchParams.set('scalar_token', this.scalarToken);
parsed.searchParams.set("scalar_token", this.scalarToken);
}
}
// Replace the encoded dollar signs back to dollar signs. They have no special meaning
// in HTTP, but URL parsers encode them anyways.
return parsed.toString().replace(/%24/g, '$');
return parsed.toString().replace(/%24/g, "$");
}
public get isManagedByManager(): boolean {
@@ -271,7 +275,11 @@ export class StopGapWidget extends EventEmitter {
const allowedCapabilities = this.appTileProps.whitelistCapabilities || [];
const driver = new StopGapWidgetDriver(
allowedCapabilities, this.mockWidget, this.kind, this.virtual, this.roomId,
allowedCapabilities,
this.mockWidget,
this.kind,
this.virtual,
this.roomId,
);
this.messaging = new ClientWidgetApi(this.mockWidget, iframe, driver);
@@ -333,11 +341,14 @@ export class StopGapWidget extends EventEmitter {
this.client.on(MatrixEventEvent.Decrypted, this.onEventDecrypted);
this.client.on(ClientEvent.ToDeviceEvent, this.onToDeviceEvent);
this.messaging.on(`action:${WidgetApiFromWidgetAction.UpdateAlwaysOnScreen}`,
this.messaging.on(
`action:${WidgetApiFromWidgetAction.UpdateAlwaysOnScreen}`,
(ev: CustomEvent<IStickyActionRequest>) => {
if (this.messaging.hasCapability(MatrixCapabilities.AlwaysOnScreen)) {
ActiveWidgetStore.instance.setWidgetPersistence(
this.mockWidget.id, this.roomId, ev.detail.data.value,
this.mockWidget.id,
this.roomId,
ev.detail.data.value,
);
ev.preventDefault();
this.messaging.transport.reply(ev.detail, <IWidgetApiRequestEmptyData>{}); // ack
@@ -347,7 +358,8 @@ export class StopGapWidget extends EventEmitter {
// TODO: Replace this event listener with appropriate driver functionality once the API
// establishes a sane way to send events back and forth.
this.messaging.on(`action:${WidgetApiFromWidgetAction.SendSticker}`,
this.messaging.on(
`action:${WidgetApiFromWidgetAction.SendSticker}`,
(ev: CustomEvent<IStickerActionRequest>) => {
if (this.messaging.hasCapability(MatrixCapabilities.StickerSending)) {
// Acknowledge first
@@ -356,7 +368,7 @@ export class StopGapWidget extends EventEmitter {
// Send the sticker
defaultDispatcher.dispatch({
action: 'm.sticker',
action: "m.sticker",
data: ev.detail.data,
widgetId: this.mockWidget.id,
});
@@ -365,7 +377,8 @@ export class StopGapWidget extends EventEmitter {
);
if (WidgetType.STICKERPICKER.matches(this.mockWidget.type)) {
this.messaging.on(`action:${ElementWidgetActions.OpenIntegrationManager}`,
this.messaging.on(
`action:${ElementWidgetActions.OpenIntegrationManager}`,
(ev: CustomEvent<IWidgetApiRequest>) => {
// Acknowledge first
ev.preventDefault();
@@ -381,30 +394,30 @@ export class StopGapWidget extends EventEmitter {
const integId = <string>data?.integId;
// noinspection JSIgnoredPromiseFromCall
IntegrationManagers.sharedInstance().getPrimaryManager().open(
this.client.getRoom(SdkContextClass.instance.roomViewStore.getRoomId()),
`type_${integType}`,
integId,
);
IntegrationManagers.sharedInstance()
.getPrimaryManager()
.open(
this.client.getRoom(SdkContextClass.instance.roomViewStore.getRoomId()),
`type_${integType}`,
integId,
);
},
);
}
if (WidgetType.JITSI.matches(this.mockWidget.type)) {
this.messaging.on(`action:${ElementWidgetActions.HangupCall}`,
(ev: CustomEvent<IHangupCallApiRequest>) => {
ev.preventDefault();
if (ev.detail.data?.errorMessage) {
Modal.createDialog(ErrorDialog, {
title: _t("Connection lost"),
description: _t("You were disconnected from the call. (Error: %(message)s)", {
message: ev.detail.data.errorMessage,
}),
});
}
this.messaging.transport.reply(ev.detail, <IWidgetApiRequestEmptyData>{});
},
);
this.messaging.on(`action:${ElementWidgetActions.HangupCall}`, (ev: CustomEvent<IHangupCallApiRequest>) => {
ev.preventDefault();
if (ev.detail.data?.errorMessage) {
Modal.createDialog(ErrorDialog, {
title: _t("Connection lost"),
description: _t("You were disconnected from the call. (Error: %(message)s)", {
message: ev.detail.data.errorMessage,
}),
});
}
this.messaging.transport.reply(ev.detail, <IWidgetApiRequestEmptyData>{});
});
}
}
@@ -510,7 +523,7 @@ export class StopGapWidget extends EventEmitter {
this.readUpToMap[ev.getRoomId()] = ev.getId();
const raw = ev.getEffectiveEvent();
this.messaging.feedEvent(raw as IRoomEvent, this.eventListenerRoomId).catch(e => {
this.messaging.feedEvent(raw as IRoomEvent, this.eventListenerRoomId).catch((e) => {
logger.error("Error sending event to widget: ", e);
});
}
+44 -37
View File
@@ -89,9 +89,11 @@ export class StopGapWidgetDriver extends WidgetDriver {
// Always allow screenshots to be taken because it's a client-induced flow. The widget can't
// spew screenshots at us and can't request screenshots of us, so it's up to us to provide the
// button if the widget says it supports screenshots.
this.allowedCapabilities = new Set([...allowedCapabilities,
this.allowedCapabilities = new Set([
...allowedCapabilities,
MatrixCapabilities.Screenshots,
ElementWidgetCapabilities.RequiresClient]);
ElementWidgetCapabilities.RequiresClient,
]);
// Grant the permissions that are specific to given widget types
if (WidgetType.JITSI.matches(this.forWidget.type) && forWidgetKind === WidgetKind.Room) {
@@ -105,8 +107,8 @@ export class StopGapWidgetDriver extends WidgetDriver {
// Widgets don't technically need to request this capability, but Scalar still does.
this.allowedCapabilities.add("visibility");
} else if (
virtual
&& new URL(SdkConfig.get("element_call").url ?? DEFAULTS.element_call.url).origin === this.forWidget.origin
virtual &&
new URL(SdkConfig.get("element_call").url ?? DEFAULTS.element_call.url).origin === this.forWidget.origin
) {
// This is a trusted Element Call widget that we control
this.allowedCapabilities.add(MatrixCapabilities.AlwaysOnScreen);
@@ -127,7 +129,9 @@ export class StopGapWidgetDriver extends WidgetDriver {
);
this.allowedCapabilities.add(
WidgetEventCapability.forStateEvent(
EventDirection.Send, "org.matrix.msc3401.call.member", MatrixClientPeg.get().getUserId()!,
EventDirection.Send,
"org.matrix.msc3401.call.member",
MatrixClientPeg.get().getUserId()!,
).raw,
);
this.allowedCapabilities.add(
@@ -164,14 +168,14 @@ export class StopGapWidgetDriver extends WidgetDriver {
const diff = iterableDiff(requested, this.allowedCapabilities);
const missing = new Set(diff.removed); // "removed" is "in A (requested) but not in B (allowed)"
const allowedSoFar = new Set(this.allowedCapabilities);
getRememberedCapabilitiesForWidget(this.forWidget).forEach(cap => {
getRememberedCapabilitiesForWidget(this.forWidget).forEach((cap) => {
allowedSoFar.add(cap);
missing.delete(cap);
});
if (WidgetPermissionCustomisations.preapproveCapabilities) {
const approved = await WidgetPermissionCustomisations.preapproveCapabilities(this.forWidget, requested);
if (approved) {
approved.forEach(cap => {
approved.forEach((cap) => {
allowedSoFar.add(cap);
missing.delete(cap);
});
@@ -181,14 +185,12 @@ export class StopGapWidgetDriver extends WidgetDriver {
let rememberApproved = false;
if (missing.size > 0) {
try {
const [result] = await Modal.createDialog(
WidgetCapabilitiesPromptDialog,
{
requestedCapabilities: missing,
widget: this.forWidget,
widgetKind: this.forWidgetKind,
}).finished;
(result.approved || []).forEach(cap => allowedSoFar.add(cap));
const [result] = await Modal.createDialog(WidgetCapabilitiesPromptDialog, {
requestedCapabilities: missing,
widget: this.forWidget,
widgetKind: this.forWidgetKind,
}).finished;
(result.approved || []).forEach((cap) => allowedSoFar.add(cap));
rememberApproved = result.remember;
} catch (e) {
logger.error("Non-fatal error getting capabilities: ", e);
@@ -223,7 +225,7 @@ export class StopGapWidgetDriver extends WidgetDriver {
r = await client.sendStateEvent(roomId, eventType, content, stateKey);
} else if (eventType === EventType.RoomRedaction) {
// special case: extract the `redacts` property and call redact
r = await client.redactEvent(roomId, content['redacts']);
r = await client.redactEvent(roomId, content["redacts"]);
} else {
// message event
r = await client.sendEvent(roomId, eventType, content);
@@ -261,8 +263,9 @@ export class StopGapWidgetDriver extends WidgetDriver {
if (deviceId === "*") {
// Send the message to all devices we have keys for
await client.encryptAndSendToDevices(
Object.values(deviceInfoMap[userId]).map(deviceInfo => ({
userId, deviceInfo,
Object.values(deviceInfoMap[userId]).map((deviceInfo) => ({
userId,
deviceInfo,
})),
content,
);
@@ -280,9 +283,11 @@ export class StopGapWidgetDriver extends WidgetDriver {
await client.queueToDevice({
eventType,
batch: Object.entries(contentMap).flatMap(([userId, userContentMap]) =>
Object.entries(userContentMap).map(([deviceId, content]) =>
({ userId, deviceId, payload: content }),
),
Object.entries(userContentMap).map(([deviceId, content]) => ({
userId,
deviceId,
payload: content,
})),
),
});
}
@@ -293,9 +298,11 @@ export class StopGapWidgetDriver extends WidgetDriver {
if (!client) throw new Error("Not attached to a client");
const targetRooms = roomIds
? (roomIds.includes(Symbols.AnyRoom) ? client.getVisibleRooms() : roomIds.map(r => client.getRoom(r)))
? roomIds.includes(Symbols.AnyRoom)
? client.getVisibleRooms()
: roomIds.map((r) => client.getRoom(r))
: [client.getRoom(SdkContextClass.instance.roomViewStore.getRoomId())];
return targetRooms.filter(r => !!r);
return targetRooms.filter((r) => !!r);
}
public async readRoomEvents(
@@ -316,11 +323,11 @@ export class StopGapWidgetDriver extends WidgetDriver {
const ev = events[i];
if (ev.getType() !== eventType || ev.isState()) continue;
if (eventType === EventType.RoomMessage && msgtype && msgtype !== ev.getContent()['msgtype']) continue;
if (eventType === EventType.RoomMessage && msgtype && msgtype !== ev.getContent()["msgtype"]) continue;
results.push(ev);
}
results.forEach(e => allResults.push(e.getEffectiveEvent() as IRoomEvent));
results.forEach((e) => allResults.push(e.getEffectiveEvent() as IRoomEvent));
}
return allResults;
}
@@ -347,14 +354,16 @@ export class StopGapWidgetDriver extends WidgetDriver {
}
}
results.slice(0, limitPerRoom).forEach(e => allResults.push(e.getEffectiveEvent() as IRoomEvent));
results.slice(0, limitPerRoom).forEach((e) => allResults.push(e.getEffectiveEvent() as IRoomEvent));
}
return allResults;
}
public async askOpenID(observer: SimpleObservable<IOpenIDUpdate>) {
const oidcState = SdkContextClass.instance.widgetPermissionStore.getOIDCState(
this.forWidget, this.forWidgetKind, this.inRoomId,
this.forWidget,
this.forWidgetKind,
this.inRoomId,
);
const getToken = (): Promise<IOpenIDCredentials> => {
@@ -389,7 +398,7 @@ export class StopGapWidgetDriver extends WidgetDriver {
navigateToPermalink(uri);
}
public async* getTurnServers(): AsyncGenerator<ITurnServer> {
public async *getTurnServers(): AsyncGenerator<ITurnServer> {
const client = MatrixClientPeg.get();
if (!client.pollingTurnServers || !client.getTurnServers().length) return;
@@ -397,7 +406,9 @@ export class StopGapWidgetDriver extends WidgetDriver {
let setError: (error: Error) => void;
const onTurnServers = ([server]: IClientTurnServer[]) => setTurnServer(normalizeTurnServer(server));
const onTurnServersError = (error: Error, fatal: boolean) => { if (fatal) setError(error); };
const onTurnServersError = (error: Error, fatal: boolean) => {
if (fatal) setError(error);
};
client.on(ClientEvent.TurnServers, onTurnServers);
client.on(ClientEvent.TurnServersError, onTurnServersError);
@@ -429,21 +440,17 @@ export class StopGapWidgetDriver extends WidgetDriver {
from?: string,
to?: string,
limit?: number,
direction?: 'f' | 'b',
direction?: "f" | "b",
): Promise<IReadEventRelationsResult> {
const client = MatrixClientPeg.get();
const dir = direction as Direction;
roomId = roomId ?? SdkContextClass.instance.roomViewStore.getRoomId() ?? undefined;
if (typeof roomId !== "string") {
throw new Error('Error while reading the current room');
throw new Error("Error while reading the current room");
}
const {
events,
nextBatch,
prevBatch,
} = await client.relations(
const { events, nextBatch, prevBatch } = await client.relations(
roomId,
eventId,
relationType ?? null,
@@ -452,7 +459,7 @@ export class StopGapWidgetDriver extends WidgetDriver {
);
return {
chunk: events.map(e => e.getEffectiveEvent() as IRoomEvent),
chunk: events.map((e) => e.getEffectiveEvent() as IRoomEvent),
nextBatch,
prevBatch,
};
+21 -17
View File
@@ -41,7 +41,7 @@ export enum Container {
// changes needed", though this may change in the future.
Right = "right",
Center = "center"
Center = "center",
}
export interface IStoredLayout {
@@ -210,7 +210,7 @@ export class WidgetLayoutStore extends ReadyWatchingStore {
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) ? manualContainer === Container.Center : stateContainer === Container.Center) {
if (manualContainer ? manualContainer === Container.Center : stateContainer === Container.Center) {
if (centerWidgets.length) {
console.error("Tried to push a second widget into the center container");
} else {
@@ -221,7 +221,7 @@ export class WidgetLayoutStore extends ReadyWatchingStore {
}
let targetContainer = defaultContainer;
if (!!manualContainer || !!stateContainer) {
targetContainer = (manualContainer) ? manualContainer : stateContainer;
targetContainer = manualContainer ? manualContainer : stateContainer;
} else if (isLegacyPinned && !stateContainer) {
// Special legacy case
targetContainer = Container.Top;
@@ -299,7 +299,7 @@ export class WidgetLayoutStore extends ReadyWatchingStore {
// 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);
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
@@ -311,9 +311,9 @@ export class WidgetLayoutStore extends ReadyWatchingStore {
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]);
.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;
}
@@ -352,18 +352,22 @@ export class WidgetLayoutStore extends ReadyWatchingStore {
}
public isInContainer(room: Optional<Room>, widget: IApp, container: Container): boolean {
return this.getContainerWidgets(room, container).some(w => w.id === widget.id);
return this.getContainerWidgets(room, container).some((w) => w.id === widget.id);
}
public canAddToContainer(room: Room, container: Container): boolean {
switch (container) {
case Container.Top: return this.getContainerWidgets(room, container).length < MAX_PINNED;
case Container.Right: return this.getContainerWidgets(room, container).length < MAX_PINNED;
case Container.Center: return this.getContainerWidgets(room, container).length < 1;
case Container.Top:
return this.getContainerWidgets(room, container).length < MAX_PINNED;
case Container.Right:
return this.getContainerWidgets(room, container).length < MAX_PINNED;
case Container.Center:
return this.getContainerWidgets(room, container).length < 1;
}
}
public getResizerDistributions(room: Room, container: Container): string[] { // yes, string.
public getResizerDistributions(room: Room, container: Container): string[] {
// yes, string.
let distributions = this.byRoom[room.roomId]?.[container]?.distributions;
if (!distributions || distributions.length < 2) return [];
@@ -373,13 +377,13 @@ export class WidgetLayoutStore extends ReadyWatchingStore {
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
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 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.
@@ -420,7 +424,7 @@ export class WidgetLayoutStore extends ReadyWatchingStore {
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);
const currentIdx = widgets.findIndex((w) => w.id === widget.id);
if (currentIdx < 0) return; // no change needed
widgets.splice(currentIdx, 1); // remove existing widget
@@ -494,7 +498,7 @@ export class WidgetLayoutStore extends ReadyWatchingStore {
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 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] = {
@@ -527,7 +531,7 @@ export class WidgetLayoutStore extends ReadyWatchingStore {
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 idx = containerWidgets.findIndex((w) => w.id === widget.id);
const widths = this.byRoom[room.roomId]?.[container]?.distributions;
if (!newLayout[widget.id]) {
newLayout[widget.id] = {
+4 -5
View File
@@ -27,8 +27,7 @@ export enum OIDCState {
}
export class WidgetPermissionStore {
public constructor(private readonly context: SdkContextClass) {
}
public constructor(private readonly context: SdkContextClass) {}
// TODO (all functions here): Merge widgetKind with the widget definition
@@ -38,7 +37,7 @@ export class WidgetPermissionStore {
location = this.context.client?.getUserId();
}
if (kind === WidgetKind.Modal) {
location = '*MODAL*-' + location; // to guarantee differentiation from whatever spawned it
location = "*MODAL*-" + location; // to guarantee differentiation from whatever spawned it
}
if (!location) {
throw new Error("Failed to determine a location to check the widget's OIDC state with");
@@ -74,8 +73,8 @@ export class WidgetPermissionStore {
} else if (newState === OIDCState.Denied) {
currentValues.deny.push(settingsKey);
} else {
currentValues.allow = currentValues.allow.filter(c => c !== settingsKey);
currentValues.deny = currentValues.deny.filter(c => c !== settingsKey);
currentValues.allow = currentValues.allow.filter((c) => c !== settingsKey);
currentValues.deny = currentValues.deny.filter((c) => c !== settingsKey);
}
SettingsStore.setValue("widgetOpenIDPermissions", null, SettingLevel.DEVICE, currentValues);