Compare commits

...

7 commits

Author SHA1 Message Date
RMidhunSuresh
5d63069f31 Check status code instead of throwing error 2022-08-16 14:32:18 +05:30
RMidhunSuresh
08f9edaf68 Use Error LogLevel 2022-08-15 22:58:26 +05:30
RMidhunSuresh
6335da0932 Throw error from outside log method
This will show the error in the UI
2022-08-15 22:52:02 +05:30
RMidhunSuresh
7590c55404 Log error when loading css file fails 2022-08-15 22:28:40 +05:30
RMidhunSuresh
2e12ce74b7 Show parse errors in the UI as well 2022-08-15 17:23:27 +05:30
RMidhunSuresh
27363b3f63 Throw and log errors if manifests cannot be loaded 2022-08-10 22:25:56 +05:30
RMidhunSuresh
ff706e542d Throw ConnectionError instead of swallowing error 2022-08-10 22:23:51 +05:30
3 changed files with 61 additions and 22 deletions

View file

@ -192,7 +192,7 @@ export class Platform {
await this._themeLoader?.init(manifests, log); await this._themeLoader?.init(manifests, log);
const { themeName, themeVariant } = await this._themeLoader.getActiveTheme(); const { themeName, themeVariant } = await this._themeLoader.getActiveTheme();
log.log({ l: "Active theme", name: themeName, variant: themeVariant }); log.log({ l: "Active theme", name: themeName, variant: themeVariant });
this._themeLoader.setTheme(themeName, themeVariant, log); await this._themeLoader.setTheme(themeName, themeVariant, log);
} }
}); });
} catch (err) { } catch (err) {
@ -332,17 +332,34 @@ export class Platform {
return this._themeLoader; return this._themeLoader;
} }
replaceStylesheet(newPath) { async replaceStylesheet(newPath, log) {
const head = document.querySelector("head"); const error = await this.logger.wrapOrRun(log, { l: "replaceStylesheet", location: newPath, }, async (l) => {
// remove default theme let resolve, error;
document.querySelectorAll(".theme").forEach(e => e.remove()); const promise = new Promise(r => resolve = r);
// add new theme const head = document.querySelector("head");
const styleTag = document.createElement("link"); // remove default theme
styleTag.href = newPath; document.querySelectorAll(".theme").forEach(e => e.remove());
styleTag.rel = "stylesheet"; // add new theme
styleTag.type = "text/css"; const styleTag = document.createElement("link");
styleTag.className = "theme"; styleTag.href = newPath;
head.appendChild(styleTag); styleTag.rel = "stylesheet";
styleTag.type = "text/css";
styleTag.className = "theme";
styleTag.onerror = () => {
error = new Error(`Failed to load stylesheet from ${newPath}`);
l.catch(error);
resolve();
};
styleTag.onload = () => {
resolve();
};
head.appendChild(styleTag);
await promise;
return error;
});
if (error) {
throw error;
}
} }
get description() { get description() {

View file

@ -120,6 +120,7 @@ export function createFetchRequest(createTimeout, serviceWorkerHandler) {
} }
} catch (err) { } catch (err) {
// some error pages return html instead of json, ignore error // some error pages return html instead of json, ignore error
// detect these ignored errors from the response status
if (!(err.name === "SyntaxError" && status >= 400)) { if (!(err.name === "SyntaxError" && status >= 400)) {
throw err; throw err;
} }

View file

@ -14,12 +14,14 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import type {ILogItem} from "../../../logging/types";
import type {Platform} from "../Platform.js";
import {RuntimeThemeParser} from "./parsers/RuntimeThemeParser"; import {RuntimeThemeParser} from "./parsers/RuntimeThemeParser";
import type {Variant, ThemeInformation} from "./parsers/types";
import {ColorSchemePreference} from "./parsers/types"; import {ColorSchemePreference} from "./parsers/types";
import {BuiltThemeParser} from "./parsers/BuiltThemeParser"; import {BuiltThemeParser} from "./parsers/BuiltThemeParser";
import type {Variant, ThemeInformation} from "./parsers/types";
import type {ThemeManifest} from "../../types/theme";
import type {ILogItem} from "../../../logging/types";
import type {Platform} from "../Platform.js";
import {LogLevel} from "../../../logging/LogFilter";
export class ThemeLoader { export class ThemeLoader {
private _platform: Platform; private _platform: Platform;
@ -32,6 +34,9 @@ export class ThemeLoader {
async init(manifestLocations: string[], log?: ILogItem): Promise<void> { async init(manifestLocations: string[], log?: ILogItem): Promise<void> {
await this._platform.logger.wrapOrRun(log, "ThemeLoader.init", async (log) => { await this._platform.logger.wrapOrRun(log, "ThemeLoader.init", async (log) => {
let noManifestsAvailable = true;
const failedManifestLoads: string[] = [];
const parseErrors: string[] = [];
const results = await Promise.all( const results = await Promise.all(
manifestLocations.map(location => this._platform.request(location, { method: "GET", format: "json", cache: true, }).response()) manifestLocations.map(location => this._platform.request(location, { method: "GET", format: "json", cache: true, }).response())
); );
@ -39,14 +44,22 @@ export class ThemeLoader {
const builtThemeParser = new BuiltThemeParser(this.preferredColorScheme); const builtThemeParser = new BuiltThemeParser(this.preferredColorScheme);
const runtimeThemePromises: Promise<void>[] = []; const runtimeThemePromises: Promise<void>[] = [];
for (let i = 0; i < results.length; ++i) { for (let i = 0; i < results.length; ++i) {
const { body } = results[i]; const result = results[i];
const { status, body } = result;
if (!(status >= 200 && status <= 299)) {
console.error(`Failed to load manifest at ${manifestLocations[i]}, status: ${status}`);
log.log({ l: "Manifest fetch failed", location: manifestLocations[i], status }, LogLevel.Error);
failedManifestLoads.push(manifestLocations[i])
continue;
}
noManifestsAvailable = false;
try { try {
if (body.extends) { if (body.extends) {
const indexOfBaseManifest = results.findIndex(manifest => manifest.body.id === body.extends); const indexOfBaseManifest = results.findIndex(result => "value" in result && result.value.body.id === body.extends);
if (indexOfBaseManifest === -1) { if (indexOfBaseManifest === -1) {
throw new Error(`Base manifest for derived theme at ${manifestLocations[i]} not found!`); throw new Error(`Base manifest for derived theme at ${manifestLocations[i]} not found!`);
} }
const {body: baseManifest} = results[indexOfBaseManifest]; const { body: baseManifest } = (results[indexOfBaseManifest] as PromiseFulfilledResult<{ body: ThemeManifest }>).value;
const baseManifestLocation = manifestLocations[indexOfBaseManifest]; const baseManifestLocation = manifestLocations[indexOfBaseManifest];
const promise = runtimeThemeParser.parse(body, baseManifest, baseManifestLocation, log); const promise = runtimeThemeParser.parse(body, baseManifest, baseManifestLocation, log);
runtimeThemePromises.push(promise); runtimeThemePromises.push(promise);
@ -57,19 +70,27 @@ export class ThemeLoader {
} }
catch(e) { catch(e) {
console.error(e); console.error(e);
parseErrors.push(e.message);
} }
} }
await Promise.all(runtimeThemePromises); await Promise.all(runtimeThemePromises);
this._themeMapping = { ...builtThemeParser.themeMapping, ...runtimeThemeParser.themeMapping }; this._themeMapping = { ...builtThemeParser.themeMapping, ...runtimeThemeParser.themeMapping };
Object.assign(this._themeMapping, builtThemeParser.themeMapping, runtimeThemeParser.themeMapping); if (noManifestsAvailable) {
// We need at least one working theme manifest!
throw new Error(`All configured theme manifests failed to load, the following were tried: ${failedManifestLoads.join(", ")}`);
}
else if (Object.keys(this._themeMapping).length === 0 && parseErrors.length) {
// Something is wrong..., themeMapping is empty!
throw new Error(`Failed to parse theme manifests, the following errors were encountered: ${parseErrors.join(", ")}`);
}
this._addDefaultThemeToMapping(log); this._addDefaultThemeToMapping(log);
log.log({ l: "Preferred colorscheme", scheme: this.preferredColorScheme === ColorSchemePreference.Dark ? "dark" : "light" }); log.log({ l: "Preferred colorscheme", scheme: this.preferredColorScheme === ColorSchemePreference.Dark ? "dark" : "light" });
log.log({ l: "Result", themeMapping: this._themeMapping }); log.log({ l: "Result", themeMapping: this._themeMapping });
}); });
} }
setTheme(themeName: string, themeVariant?: "light" | "dark" | "default", log?: ILogItem) { async setTheme(themeName: string, themeVariant?: "light" | "dark" | "default", log?: ILogItem) {
this._platform.logger.wrapOrRun(log, { l: "change theme", name: themeName, variant: themeVariant }, () => { await this._platform.logger.wrapOrRun(log, { l: "change theme", name: themeName, variant: themeVariant }, async (l) => {
let cssLocation: string, variables: Record<string, string>; let cssLocation: string, variables: Record<string, string>;
let themeDetails = this._themeMapping[themeName]; let themeDetails = this._themeMapping[themeName];
if ("id" in themeDetails) { if ("id" in themeDetails) {
@ -83,7 +104,7 @@ export class ThemeLoader {
cssLocation = themeDetails[themeVariant].cssLocation; cssLocation = themeDetails[themeVariant].cssLocation;
variables = themeDetails[themeVariant].variables; variables = themeDetails[themeVariant].variables;
} }
this._platform.replaceStylesheet(cssLocation); await this._platform.replaceStylesheet(cssLocation, l);
if (variables) { if (variables) {
log?.log({l: "Derived Theme", variables}); log?.log({l: "Derived Theme", variables});
this._injectCSSVariables(variables); this._injectCSSVariables(variables);