Skip to content
This repository was archived by the owner on Sep 11, 2024. It is now read-only.

Commit dd8abb0

Browse files
authored
Merge pull request #5912 from matrix-org/jryans/convert-flow-to-ts
Convert some Flow-typed files to TypeScript
2 parents 96e00ca + b820304 commit dd8abb0

40 files changed

+1061
-848
lines changed

src/@types/global.d.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
Copyright 2020 The Matrix.org Foundation C.I.C.
2+
Copyright 2020-2021 The Matrix.org Foundation C.I.C.
33
44
Licensed under the Apache License, Version 2.0 (the "License");
55
you may not use this file except in compliance with the License.
@@ -40,6 +40,8 @@ import { WidgetLayoutStore } from "../stores/widgets/WidgetLayoutStore";
4040
import VoipUserMapper from "../VoipUserMapper";
4141
import {SpaceStoreClass} from "../stores/SpaceStore";
4242
import {VoiceRecording} from "../voice/VoiceRecording";
43+
import TypingStore from "../stores/TypingStore";
44+
import { EventIndexPeg } from "../indexing/EventIndexPeg";
4345

4446
declare global {
4547
interface Window {
@@ -72,11 +74,15 @@ declare global {
7274
mxVoipUserMapper: VoipUserMapper;
7375
mxSpaceStore: SpaceStoreClass;
7476
mxVoiceRecorder: typeof VoiceRecording;
77+
mxTypingStore: TypingStore;
78+
mxEventIndexPeg: EventIndexPeg;
7579
}
7680

7781
interface Document {
7882
// https://developer.mozilla.org/en-US/docs/Web/API/Document/hasStorageAccess
7983
hasStorageAccess?: () => Promise<boolean>;
84+
// https://developer.mozilla.org/en-US/docs/Web/API/Document/requestStorageAccess
85+
requestStorageAccess?: () => Promise<undefined>;
8086

8187
// Safari & IE11 only have this prefixed: we used prefixed versions
8288
// previously so let's continue to support them for now

src/CallHandler.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -673,7 +673,7 @@ export default class CallHandler {
673673
call.placeScreenSharingCall(
674674
remoteElement,
675675
localElement,
676-
async () : Promise<DesktopCapturerSource> => {
676+
async (): Promise<DesktopCapturerSource> => {
677677
const {finished} = Modal.createDialog(DesktopCapturerSourcePicker);
678678
const [source] = await finished;
679679
return source;

src/KeyBindingsManager.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -231,8 +231,10 @@ export class KeyBindingsManager {
231231
/**
232232
* Finds a matching KeyAction for a given KeyboardEvent
233233
*/
234-
private getAction<T extends string>(getters: KeyBindingGetter<T>[], ev: KeyboardEvent | React.KeyboardEvent)
235-
: T | undefined {
234+
private getAction<T extends string>(
235+
getters: KeyBindingGetter<T>[],
236+
ev: KeyboardEvent | React.KeyboardEvent,
237+
): T | undefined {
236238
for (const getter of getters) {
237239
const bindings = getter();
238240
const binding = bindings.find(it => isKeyComboMatch(ev, it.keyCombo, isMac));

src/Login.ts

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
/*
2-
Copyright 2015, 2016 OpenMarket Ltd
3-
Copyright 2017 Vector Creations Ltd
4-
Copyright 2018 New Vector Ltd
2+
Copyright 2015-2021 The Matrix.org Foundation C.I.C.
53
Copyright 2019 Michael Telatynski <[email protected]>
6-
Copyright 2020 The Matrix.org Foundation C.I.C.
74
85
Licensed under the Apache License, Version 2.0 (the "License");
96
you may not use this file except in compliance with the License.
@@ -59,7 +56,7 @@ export type LoginFlow = ISSOFlow | IPasswordFlow;
5956
// TODO: Move this to JS SDK
6057
/* eslint-disable camelcase */
6158
interface ILoginParams {
62-
identifier?: string;
59+
identifier?: object;
6360
password?: string;
6461
token?: string;
6562
device_id?: string;

src/ScalarAuthClient.js renamed to src/ScalarAuthClient.ts

Lines changed: 33 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
/*
2-
Copyright 2016 OpenMarket Ltd
3-
Copyright 2019 The Matrix.org Foundation C.I.C.
2+
Copyright 2016, 2019, 2021 The Matrix.org Foundation C.I.C.
43
54
Licensed under the Apache License, Version 2.0 (the "License");
65
you may not use this file except in compliance with the License.
@@ -17,23 +16,26 @@ limitations under the License.
1716

1817
import url from 'url';
1918
import SettingsStore from "./settings/SettingsStore";
20-
import { Service, startTermsFlow, TermsNotSignedError } from './Terms';
19+
import { Service, startTermsFlow, TermsInteractionCallback, TermsNotSignedError } from './Terms';
2120
import {MatrixClientPeg} from "./MatrixClientPeg";
2221
import request from "browser-request";
2322

2423
import SdkConfig from "./SdkConfig";
2524
import {WidgetType} from "./widgets/WidgetType";
2625
import {SERVICE_TYPES} from "matrix-js-sdk/src/service-types";
26+
import { Room } from "matrix-js-sdk/src/models/room";
2727

2828
// The version of the integration manager API we're intending to work with
2929
const imApiVersion = "1.1";
3030

3131
// TODO: Generify the name of this class and all components within - it's not just for Scalar.
3232

3333
export default class ScalarAuthClient {
34-
constructor(apiUrl, uiUrl) {
35-
this.apiUrl = apiUrl;
36-
this.uiUrl = uiUrl;
34+
private scalarToken: string;
35+
private termsInteractionCallback: TermsInteractionCallback;
36+
private isDefaultManager: boolean;
37+
38+
constructor(private apiUrl: string, private uiUrl: string) {
3739
this.scalarToken = null;
3840
// `undefined` to allow `startTermsFlow` to fallback to a default
3941
// callback if this is unset.
@@ -46,7 +48,7 @@ export default class ScalarAuthClient {
4648
this.isDefaultManager = apiUrl === configApiUrl && configUiUrl === uiUrl;
4749
}
4850

49-
_writeTokenToStore() {
51+
private writeTokenToStore() {
5052
window.localStorage.setItem("mx_scalar_token_at_" + this.apiUrl, this.scalarToken);
5153
if (this.isDefaultManager) {
5254
// We remove the old token from storage to migrate upwards. This is safe
@@ -56,41 +58,41 @@ export default class ScalarAuthClient {
5658
}
5759
}
5860

59-
_readTokenFromStore() {
61+
private readTokenFromStore(): string {
6062
let token = window.localStorage.getItem("mx_scalar_token_at_" + this.apiUrl);
6163
if (!token && this.isDefaultManager) {
6264
token = window.localStorage.getItem("mx_scalar_token");
6365
}
6466
return token;
6567
}
6668

67-
_readToken() {
69+
private readToken(): string {
6870
if (this.scalarToken) return this.scalarToken;
69-
return this._readTokenFromStore();
71+
return this.readTokenFromStore();
7072
}
7173

7274
setTermsInteractionCallback(callback) {
7375
this.termsInteractionCallback = callback;
7476
}
7577

76-
connect() {
78+
connect(): Promise<void> {
7779
return this.getScalarToken().then((tok) => {
7880
this.scalarToken = tok;
7981
});
8082
}
8183

82-
hasCredentials() {
84+
hasCredentials(): boolean {
8385
return this.scalarToken != null; // undef or null
8486
}
8587

8688
// Returns a promise that resolves to a scalar_token string
87-
getScalarToken() {
88-
const token = this._readToken();
89+
getScalarToken(): Promise<string> {
90+
const token = this.readToken();
8991

9092
if (!token) {
9193
return this.registerForToken();
9294
} else {
93-
return this._checkToken(token).catch((e) => {
95+
return this.checkToken(token).catch((e) => {
9496
if (e instanceof TermsNotSignedError) {
9597
// retrying won't help this
9698
throw e;
@@ -100,7 +102,7 @@ export default class ScalarAuthClient {
100102
}
101103
}
102104

103-
_getAccountName(token) {
105+
private getAccountName(token: string): Promise<string> {
104106
const url = this.apiUrl + "/account";
105107

106108
return new Promise(function(resolve, reject) {
@@ -125,8 +127,8 @@ export default class ScalarAuthClient {
125127
});
126128
}
127129

128-
_checkToken(token) {
129-
return this._getAccountName(token).then(userId => {
130+
private checkToken(token: string): Promise<string> {
131+
return this.getAccountName(token).then(userId => {
130132
const me = MatrixClientPeg.get().getUserId();
131133
if (userId !== me) {
132134
throw new Error("Scalar token is owned by someone else: " + me);
@@ -154,7 +156,7 @@ export default class ScalarAuthClient {
154156
parsedImRestUrl.pathname = '';
155157
return startTermsFlow([new Service(
156158
SERVICE_TYPES.IM,
157-
parsedImRestUrl.format(),
159+
url.format(parsedImRestUrl),
158160
token,
159161
)], this.termsInteractionCallback).then(() => {
160162
return token;
@@ -165,22 +167,22 @@ export default class ScalarAuthClient {
165167
});
166168
}
167169

168-
registerForToken() {
170+
registerForToken(): Promise<string> {
169171
// Get openid bearer token from the HS as the first part of our dance
170172
return MatrixClientPeg.get().getOpenIdToken().then((tokenObject) => {
171173
// Now we can send that to scalar and exchange it for a scalar token
172174
return this.exchangeForScalarToken(tokenObject);
173175
}).then((token) => {
174176
// Validate it (this mostly checks to see if the IM needs us to agree to some terms)
175-
return this._checkToken(token);
177+
return this.checkToken(token);
176178
}).then((token) => {
177179
this.scalarToken = token;
178-
this._writeTokenToStore();
180+
this.writeTokenToStore();
179181
return token;
180182
});
181183
}
182184

183-
exchangeForScalarToken(openidTokenObject) {
185+
exchangeForScalarToken(openidTokenObject: any): Promise<string> {
184186
const scalarRestUrl = this.apiUrl;
185187

186188
return new Promise(function(resolve, reject) {
@@ -194,7 +196,7 @@ export default class ScalarAuthClient {
194196
if (err) {
195197
reject(err);
196198
} else if (response.statusCode / 100 !== 2) {
197-
reject({statusCode: response.statusCode});
199+
reject(new Error(`Scalar request failed: ${response.statusCode}`));
198200
} else if (!body || !body.scalar_token) {
199201
reject(new Error("Missing scalar_token in response"));
200202
} else {
@@ -204,7 +206,7 @@ export default class ScalarAuthClient {
204206
});
205207
}
206208

207-
getScalarPageTitle(url) {
209+
getScalarPageTitle(url: string): Promise<string> {
208210
let scalarPageLookupUrl = this.apiUrl + '/widgets/title_lookup';
209211
scalarPageLookupUrl = this.getStarterLink(scalarPageLookupUrl);
210212
scalarPageLookupUrl += '&curl=' + encodeURIComponent(url);
@@ -218,7 +220,7 @@ export default class ScalarAuthClient {
218220
if (err) {
219221
reject(err);
220222
} else if (response.statusCode / 100 !== 2) {
221-
reject({statusCode: response.statusCode});
223+
reject(new Error(`Scalar request failed: ${response.statusCode}`));
222224
} else if (!body) {
223225
reject(new Error("Missing page title in response"));
224226
} else {
@@ -240,10 +242,10 @@ export default class ScalarAuthClient {
240242
* @param {string} widgetId The widget ID to disable assets for
241243
* @return {Promise} Resolves on completion
242244
*/
243-
disableWidgetAssets(widgetType: WidgetType, widgetId) {
245+
disableWidgetAssets(widgetType: WidgetType, widgetId: string): Promise<void> {
244246
let url = this.apiUrl + '/widgets/set_assets_state';
245247
url = this.getStarterLink(url);
246-
return new Promise((resolve, reject) => {
248+
return new Promise<void>((resolve, reject) => {
247249
request({
248250
method: 'GET', // XXX: Actions shouldn't be GET requests
249251
uri: url,
@@ -257,7 +259,7 @@ export default class ScalarAuthClient {
257259
if (err) {
258260
reject(err);
259261
} else if (response.statusCode / 100 !== 2) {
260-
reject({statusCode: response.statusCode});
262+
reject(new Error(`Scalar request failed: ${response.statusCode}`));
261263
} else if (!body) {
262264
reject(new Error("Failed to set widget assets state"));
263265
} else {
@@ -267,7 +269,7 @@ export default class ScalarAuthClient {
267269
});
268270
}
269271

270-
getScalarInterfaceUrlForRoom(room, screen, id) {
272+
getScalarInterfaceUrlForRoom(room: Room, screen: string, id: string): string {
271273
const roomId = room.roomId;
272274
const roomName = room.name;
273275
let url = this.uiUrl;
@@ -284,7 +286,7 @@ export default class ScalarAuthClient {
284286
return url;
285287
}
286288

287-
getStarterLink(starterLinkUrl) {
289+
getStarterLink(starterLinkUrl: string): string {
288290
return starterLinkUrl + "?scalar_token=" + encodeURIComponent(this.scalarToken);
289291
}
290292
}

src/Terms.js renamed to src/Terms.ts

Lines changed: 33 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
Copyright 2019 The Matrix.org Foundation C.I.C.
2+
Copyright 2019, 2021 The Matrix.org Foundation C.I.C.
33
44
Licensed under the Apache License, Version 2.0 (the "License");
55
you may not use this file except in compliance with the License.
@@ -17,7 +17,7 @@ limitations under the License.
1717
import classNames from 'classnames';
1818

1919
import {MatrixClientPeg} from './MatrixClientPeg';
20-
import * as sdk from './';
20+
import * as sdk from '.';
2121
import Modal from './Modal';
2222

2323
export class TermsNotSignedError extends Error {}
@@ -32,13 +32,30 @@ export class Service {
3232
* @param {string} baseUrl The Base URL of the service (ie. before '/_matrix')
3333
* @param {string} accessToken The user's access token for the service
3434
*/
35-
constructor(serviceType, baseUrl, accessToken) {
36-
this.serviceType = serviceType;
37-
this.baseUrl = baseUrl;
38-
this.accessToken = accessToken;
35+
constructor(public serviceType: string, public baseUrl: string, public accessToken: string) {
3936
}
4037
}
4138

39+
interface Policy {
40+
// @ts-ignore: No great way to express indexed types together with other keys
41+
version: string;
42+
[lang: string]: {
43+
url: string;
44+
};
45+
}
46+
type Policies = {
47+
[policy: string]: Policy,
48+
};
49+
50+
export type TermsInteractionCallback = (
51+
policiesAndServicePairs: {
52+
service: Service,
53+
policies: Policies,
54+
}[],
55+
agreedUrls: string[],
56+
extraClassNames?: string,
57+
) => Promise<string[]>;
58+
4259
/**
4360
* Start a flow where the user is presented with terms & conditions for some services
4461
*
@@ -51,8 +68,8 @@ export class Service {
5168
* if they cancel.
5269
*/
5370
export async function startTermsFlow(
54-
services,
55-
interactionCallback = dialogTermsInteractionCallback,
71+
services: Service[],
72+
interactionCallback: TermsInteractionCallback = dialogTermsInteractionCallback,
5673
) {
5774
const termsPromises = services.map(
5875
(s) => MatrixClientPeg.get().getTerms(s.serviceType, s.baseUrl),
@@ -77,7 +94,7 @@ export async function startTermsFlow(
7794
* }
7895
*/
7996

80-
const terms = await Promise.all(termsPromises);
97+
const terms: { policies: Policies }[] = await Promise.all(termsPromises);
8198
const policiesAndServicePairs = terms.map((t, i) => { return { 'service': services[i], 'policies': t.policies }; });
8299

83100
// fetch the set of agreed policy URLs from account data
@@ -158,10 +175,13 @@ export async function startTermsFlow(
158175
}
159176

160177
export function dialogTermsInteractionCallback(
161-
policiesAndServicePairs,
162-
agreedUrls,
163-
extraClassNames,
164-
) {
178+
policiesAndServicePairs: {
179+
service: Service,
180+
policies: { [policy: string]: Policy },
181+
}[],
182+
agreedUrls: string[],
183+
extraClassNames?: string,
184+
): Promise<string[]> {
165185
return new Promise((resolve, reject) => {
166186
console.log("Terms that need agreement", policiesAndServicePairs);
167187
const TermsDialog = sdk.getComponent("views.dialogs.TermsDialog");

0 commit comments

Comments
 (0)