Skip to content

Commit 1d109bb

Browse files
authored
Merge pull request element-hq#12869 from vector-im/t3chguy/app_load_tweaks
App load tweaks
2 parents 1697cdc + fd385f8 commit 1d109bb

8 files changed

Lines changed: 157 additions & 135 deletions

File tree

‎src/@types/global.d.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/*
2+
Copyright 2020 New Vector Ltd
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
interface Window {
18+
Olm: {
19+
init: () => Promise<void>;
20+
};
21+
mxSendRageshake: (text: string, withLogs?: boolean) => void;
22+
}

‎src/vector/app.js‎

Lines changed: 5 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,6 @@ See the License for the specific language governing permissions and
1818
limitations under the License.
1919
*/
2020

21-
import olmWasmPath from 'olm/olm.wasm';
22-
2321
import React from 'react';
2422
// add React and ReactPerf to the global namespace, to make them easier to
2523
// access via the console
@@ -29,7 +27,6 @@ import ReactDOM from 'react-dom';
2927
import * as sdk from 'matrix-react-sdk';
3028
import PlatformPeg from 'matrix-react-sdk/src/PlatformPeg';
3129
import * as VectorConferenceHandler from 'matrix-react-sdk/src/VectorConferenceHandler';
32-
import * as languageHandler from 'matrix-react-sdk/src/languageHandler';
3330
import {_t, _td, newTranslatableError} from 'matrix-react-sdk/src/languageHandler';
3431
import AutoDiscoveryUtils from 'matrix-react-sdk/src/utils/AutoDiscoveryUtils';
3532
import {AutoDiscovery} from "matrix-js-sdk/src/autodiscovery";
@@ -40,14 +37,11 @@ import url from 'url';
4037
import {parseQs, parseQsFromFragment} from './url_utils';
4138

4239
import {MatrixClientPeg} from 'matrix-react-sdk/src/MatrixClientPeg';
43-
import SettingsStore from "matrix-react-sdk/src/settings/SettingsStore";
4440
import SdkConfig from "matrix-react-sdk/src/SdkConfig";
4541
import {setTheme} from "matrix-react-sdk/src/theme";
4642

47-
import Olm from 'olm';
48-
4943
import CallHandler from 'matrix-react-sdk/src/CallHandler';
50-
import {loadConfig, preparePlatform} from "./initial-load";
44+
import {loadConfig, preparePlatform, loadLanguage, loadOlm} from "./init";
5145

5246
let lastLocationHashSet = null;
5347

@@ -193,7 +187,7 @@ export async function loadApp() {
193187
const platform = PlatformPeg.get();
194188

195189
// Load the config from the platform
196-
const configInfo = await loadConfig();
190+
const configError = await loadConfig();
197191

198192
// Load language after loading config.json so that settingsDefaults.language can be applied
199193
await loadLanguage();
@@ -222,7 +216,7 @@ export async function loadApp() {
222216
await setTheme();
223217

224218
// Now that we've loaded the theme (CSS), display the config syntax error if needed.
225-
if (configInfo.configSyntaxError) {
219+
if (configError && configError.err && configError.err instanceof SyntaxError) {
226220
const errorMessage = (
227221
<div>
228222
<p>
@@ -234,7 +228,7 @@ export async function loadApp() {
234228
<p>
235229
{_t(
236230
"The message from the parser is: %(message)s",
237-
{message: configInfo.configError.err.message || _t("Invalid JSON")},
231+
{message: configError.err.message || _t("Invalid JSON")},
238232
)}
239233
</p>
240234
</div>
@@ -254,7 +248,7 @@ export async function loadApp() {
254248

255249
const urlWithoutQuery = window.location.protocol + '//' + window.location.host + window.location.pathname;
256250
console.log("Vector starting at " + urlWithoutQuery);
257-
if (configInfo.configError) {
251+
if (configError) {
258252
window.matrixChat = ReactDOM.render(<div className="error">
259253
Unable to load config file: please refresh the page to try again.
260254
</div>, document.getElementById('matrixchat'));
@@ -308,62 +302,6 @@ export async function loadApp() {
308302
}
309303
}
310304

311-
function loadOlm() {
312-
/* Load Olm. We try the WebAssembly version first, and then the legacy,
313-
* asm.js version if that fails. For this reason we need to wait for this
314-
* to finish before continuing to load the rest of the app. In future
315-
* we could somehow pass a promise down to react-sdk and have it wait on
316-
* that so olm can be loading in parallel with the rest of the app.
317-
*
318-
* We also need to tell the Olm js to look for its wasm file at the same
319-
* level as index.html. It really should be in the same place as the js,
320-
* ie. in the bundle directory, but as far as I can tell this is
321-
* completely impossible with webpack. We do, however, use a hashed
322-
* filename to avoid caching issues.
323-
*/
324-
return Olm.init({
325-
locateFile: () => olmWasmPath,
326-
}).then(() => {
327-
console.log("Using WebAssembly Olm");
328-
}).catch((e) => {
329-
console.log("Failed to load Olm: trying legacy version", e);
330-
return new Promise((resolve, reject) => {
331-
const s = document.createElement('script');
332-
s.src = 'olm_legacy.js'; // XXX: This should be cache-busted too
333-
s.onload = resolve;
334-
s.onerror = reject;
335-
document.body.appendChild(s);
336-
}).then(() => {
337-
// Init window.Olm, ie. the one just loaded by the script tag,
338-
// not 'Olm' which is still the failed wasm version.
339-
return window.Olm.init();
340-
}).then(() => {
341-
console.log("Using legacy Olm");
342-
}).catch((e) => {
343-
console.log("Both WebAssembly and asm.js Olm failed!", e);
344-
});
345-
});
346-
}
347-
348-
async function loadLanguage() {
349-
const prefLang = SettingsStore.getValue("language", null, /*excludeDefault=*/true);
350-
let langs = [];
351-
352-
if (!prefLang) {
353-
languageHandler.getLanguagesFromBrowser().forEach((l) => {
354-
langs.push(...languageHandler.getNormalizedLanguageKeys(l));
355-
});
356-
} else {
357-
langs = [prefLang];
358-
}
359-
try {
360-
await languageHandler.setLanguage(langs);
361-
document.documentElement.setAttribute("lang", languageHandler.getCurrentLanguage());
362-
} catch (e) {
363-
console.error("Unable to set language", e);
364-
}
365-
}
366-
367305
async function verifyServerConfig() {
368306
let validatedConfig;
369307
try {
Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
Copyright 2018 New Vector Ltd
2+
Copyright 2018, 2020 New Vector Ltd
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.
@@ -18,22 +18,25 @@ import request from 'browser-request';
1818

1919
// Load the config file. First try to load up a domain-specific config of the
2020
// form "config.$domain.json" and if that fails, fall back to config.json.
21-
export async function getVectorConfig(relativeLocation) {
22-
if (relativeLocation === undefined) relativeLocation = '';
21+
export async function getVectorConfig(relativeLocation: string='') {
2322
if (relativeLocation !== '' && !relativeLocation.endsWith('/')) relativeLocation += '/';
23+
24+
const specificConfigPromise = getConfig(`${relativeLocation}config.${document.domain}.json`);
25+
const generalConfigPromise = getConfig(relativeLocation + "config.json");
26+
2427
try {
25-
const configJson = await getConfig(`${relativeLocation}config.${document.domain}.json`);
28+
const configJson = await specificConfigPromise;
2629
// 404s succeed with an empty json config, so check that there are keys
2730
if (Object.keys(configJson).length === 0) {
2831
throw new Error(); // throw to enter the catch
2932
}
3033
return configJson;
3134
} catch (e) {
32-
return await getConfig(relativeLocation + "config.json");
35+
return await generalConfigPromise;
3336
}
3437
}
3538

36-
function getConfig(configJsonFilename) {
39+
function getConfig(configJsonFilename: string): Promise<{}> {
3740
return new Promise(function(resolve, reject) {
3841
request(
3942
{ method: "GET", url: configJsonFilename, qs: { cachebuster: Date.now() } },

‎src/vector/init.ts‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
/*
2+
Copyright 2015, 2016 OpenMarket Ltd
3+
Copyright 2017 Vector Creations Ltd
4+
Copyright 2018, 2019, 2020 New Vector Ltd
5+
Copyright 2019 Michael Telatynski <7t3chguy@gmail.com>
6+
7+
Licensed under the Apache License, Version 2.0 (the "License");
8+
you may not use this file except in compliance with the License.
9+
You may obtain a copy of the License at
10+
11+
http://www.apache.org/licenses/LICENSE-2.0
12+
13+
Unless required by applicable law or agreed to in writing, software
14+
distributed under the License is distributed on an "AS IS" BASIS,
15+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
See the License for the specific language governing permissions and
17+
limitations under the License.
18+
*/
19+
20+
// @ts-ignore
21+
import olmWasmPath from "olm/olm.wasm";
22+
import Olm from 'olm';
23+
24+
import * as languageHandler from 'matrix-react-sdk/src/languageHandler';
25+
import SettingsStore from "matrix-react-sdk/src/settings/SettingsStore";
26+
import ElectronPlatform from "./platform/ElectronPlatform";
27+
import WebPlatform from "./platform/WebPlatform";
28+
import PlatformPeg from 'matrix-react-sdk/src/PlatformPeg';
29+
import SdkConfig from "matrix-react-sdk/src/SdkConfig";
30+
31+
32+
export function preparePlatform() {
33+
if ((<any>window).ipcRenderer) {
34+
console.log("Using Electron platform");
35+
const plaf = new ElectronPlatform();
36+
PlatformPeg.set(plaf);
37+
} else {
38+
console.log("Using Web platform");
39+
PlatformPeg.set(new WebPlatform());
40+
}
41+
}
42+
43+
export async function loadConfig(): Promise<Error | void> {
44+
const platform = PlatformPeg.get();
45+
46+
let configJson;
47+
try {
48+
configJson = await platform.getConfig();
49+
} catch (e) {
50+
return e;
51+
} finally {
52+
// XXX: We call this twice, once here and once in MatrixChat as a prop. We call it here to ensure
53+
// granular settings are loaded correctly and to avoid duplicating the override logic for the theme.
54+
//
55+
// Note: this isn't called twice for some wrappers, like the Jitsi wrapper.
56+
SdkConfig.put(configJson || {});
57+
}
58+
}
59+
60+
export function loadOlm(): Promise<void> {
61+
/* Load Olm. We try the WebAssembly version first, and then the legacy,
62+
* asm.js version if that fails. For this reason we need to wait for this
63+
* to finish before continuing to load the rest of the app. In future
64+
* we could somehow pass a promise down to react-sdk and have it wait on
65+
* that so olm can be loading in parallel with the rest of the app.
66+
*
67+
* We also need to tell the Olm js to look for its wasm file at the same
68+
* level as index.html. It really should be in the same place as the js,
69+
* ie. in the bundle directory, but as far as I can tell this is
70+
* completely impossible with webpack. We do, however, use a hashed
71+
* filename to avoid caching issues.
72+
*/
73+
return Olm.init({
74+
locateFile: () => olmWasmPath,
75+
}).then(() => {
76+
console.log("Using WebAssembly Olm");
77+
}).catch((e) => {
78+
console.log("Failed to load Olm: trying legacy version", e);
79+
return new Promise((resolve, reject) => {
80+
const s = document.createElement('script');
81+
s.src = 'olm_legacy.js'; // XXX: This should be cache-busted too
82+
s.onload = resolve;
83+
s.onerror = reject;
84+
document.body.appendChild(s);
85+
}).then(() => {
86+
// Init window.Olm, ie. the one just loaded by the script tag,
87+
// not 'Olm' which is still the failed wasm version.
88+
return window.Olm.init();
89+
}).then(() => {
90+
console.log("Using legacy Olm");
91+
}).catch((e) => {
92+
console.log("Both WebAssembly and asm.js Olm failed!", e);
93+
});
94+
});
95+
}
96+
97+
export async function loadLanguage() {
98+
const prefLang = SettingsStore.getValue("language", null, /*excludeDefault=*/true);
99+
let langs = [];
100+
101+
if (!prefLang) {
102+
languageHandler.getLanguagesFromBrowser().forEach((l) => {
103+
langs.push(...languageHandler.getNormalizedLanguageKeys(l));
104+
});
105+
} else {
106+
langs = [prefLang];
107+
}
108+
try {
109+
await languageHandler.setLanguage(langs);
110+
document.documentElement.setAttribute("lang", languageHandler.getCurrentLanguage());
111+
} catch (e) {
112+
console.error("Unable to set language", e);
113+
}
114+
}

‎src/vector/initial-load.ts‎

Lines changed: 0 additions & 58 deletions
This file was deleted.
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ function initRageshake() {
5050

5151
initRageshake();
5252

53-
global.mxSendRageshake = function(text, withLogs) {
53+
window.mxSendRageshake = function(text: string, withLogs?: boolean) {
5454
if (withLogs === undefined) withLogs = true;
5555
if (!text || !text.trim()) {
5656
console.error("Cannot send a rageshake without a message - please tell us what went wrong");

‎src/vector/url_utils.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
Copyright 2018 New Vector Ltd
2+
Copyright 2018, 2020 New Vector Ltd
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.
@@ -20,7 +20,7 @@ import * as qs from 'querystring';
2020
// so we're re-using query string like format
2121
//
2222
// returns {location, params}
23-
export function parseQsFromFragment(location) {
23+
export function parseQsFromFragment(location: Location) {
2424
// if we have a fragment, it will start with '#', which we need to drop.
2525
// (if we don't, this will return '').
2626
const fragment = location.hash.substring(1);
@@ -41,6 +41,6 @@ export function parseQsFromFragment(location) {
4141
return result;
4242
}
4343

44-
export function parseQs(location) {
44+
export function parseQs(location: Location) {
4545
return qs.parse(location.search.substring(1));
4646
}

0 commit comments

Comments
 (0)