Skip to content

Commit

Permalink
feat(#6): Use current steam language for steamdb extension & use colo…
Browse files Browse the repository at this point in the history
…r logger
  • Loading branch information
tddebart committed Dec 22, 2024
1 parent d37b2fe commit 7855e28
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 16 deletions.
59 changes: 46 additions & 13 deletions webkit/browser.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { callable } from "@steambrew/webkit";
import { CDN, VERSION } from "./shared";
import { CDN, Logger, VERSION } from "./shared";

// In this file we emulate the extension browser api for the steamdb extension

Expand All @@ -23,7 +23,7 @@ steamDBBrowser.storage.sync.get = async function (items: any): Promise<any> {
try {
parsedData = storedData ? JSON.parse(storedData) : {};
} catch (e) {
console.error('[SteamDB plugin] failed to parse JSON for steamdb-options');
Logger.Error('failed to parse JSON for steamdb-options');
}

if (Array.isArray(items)) {
Expand Down Expand Up @@ -52,7 +52,7 @@ steamDBBrowser.storage.sync.set = async function (item: { [key: string]: any })
try {
parsedData = storedData ? JSON.parse(storedData) : {};
} catch (e) {
console.error('[SteamDB plugin] failed to parse JSON for steamdb-options');
Logger.Error('failed to parse JSON for steamdb-options');
}

let key = Object.keys(item)[0];
Expand Down Expand Up @@ -90,16 +90,48 @@ steamDBBrowser.permissions.contains = function (_: any, callback: (result: boole

// #region i18n Translation
steamDBBrowser.i18n = {};
const langKey = "steamDB_en";
async function getLang() {
const langPrefix = "steamDB_";
let langKey = "";
export async function getLang() {
let language = navigator.language.toLowerCase().split("-")[0];
const longLanguage = navigator.language.replaceAll('-', "_");
langKey = langPrefix + language;

// Make an exception for es-419
if (navigator.language === "es-419") {
language = 'es_419';
langKey = langPrefix + language;
}

if (localStorage.getItem(langKey + VERSION) === null) {
console.log('[SteamDB plugin] getting EN lang');
if (localStorage.getItem(langPrefix + longLanguage + VERSION) !== null) {
Logger.Log(`using "${longLanguage}" lang`);
langKey = langPrefix + longLanguage;
return;
}
Logger.Log(`getting "${language}" lang`);

let response = await fetch(CDN + `/_locales/${language}/messages.json`);

if (!response.ok) {
// Try full language key
Logger.Warn(`failed to fetch SteamDB lang file for "${language}". Trying "${longLanguage}"`);
langKey = langPrefix + longLanguage;

response = await fetch(CDN + `/_locales/${longLanguage}/messages.json`);

const response = await fetch(CDN + "/_locales/en/messages.json");
if (!response.ok) {
Logger.Warn(`failed to fetch SteamDB lang file for "${language}". Falling back to EN.`);
langKey = langPrefix + "en";
response = await fetch(CDN + "/_locales/en/messages.json");

}
}
localStorage.setItem(langKey + VERSION, JSON.stringify(await response.json()));
}
}

Logger.Log(`using "${language}" lang`);
}
getLang();

/* example record
{
Expand All @@ -117,23 +149,24 @@ getLang();
}
*/
steamDBBrowser.i18n.getMessage = function (messageKey: string, substitutions: string|string[]) {
// Ignore invalid message key
if (messageKey === '@@bidi_dir') {
return messageKey;
}

if (!Array.isArray(substitutions)) {
substitutions = [substitutions];
}

let lang: Record<string, { message: string; placeholders?: Record<string, { content: string; }> }>|null = JSON.parse(localStorage.getItem(langKey + VERSION) ?? '{}');
type LangType = Record<string, { message: string; placeholders?: Record<string, { content: string; }> }>|null;
let lang: LangType = JSON.parse(localStorage.getItem(langKey + VERSION) ?? '{}');
if (lang === null || Object.keys(lang).length === 0) {
console.error('[SteamDB plugin] SteamDB lang file not loaded in.');
Logger.Error('SteamDB lang file not loaded in.');
return messageKey;
}

const langObject = lang[messageKey];
if (langObject === undefined) {
console.error(`[SteamDB plugin] Unknown message key: ${messageKey}`);
Logger.Error(`Unknown message key: ${messageKey}`);
return messageKey;
}

Expand Down
6 changes: 4 additions & 2 deletions webkit/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import './browser';
import { getLang } from './browser';
import { injectPreferences } from './preferences';
import { getNeededScripts } from './script-loading';
import { getCdn } from "./shared";
import { getCdn, Logger } from "./shared";

async function loadScript(src: string) {
return new Promise<void>((resolve, reject) => {
Expand Down Expand Up @@ -61,11 +62,12 @@ async function loadPageSpecificScripts() {
}

export default async function WebkitMain () {
console.log("SteamDB plugin is running...");
Logger.Log("plugin is running");
let commonScript = await (await fetch(getCdn('scripts/common.min.js'))).text();
commonScript = commonScript.replaceAll('browser', 'steamDBBrowser');
loadScriptWithContent(commonScript);
await loadScript(getCdn("scripts/global.min.js"));
await getLang();

loadPageSpecificScripts();

Expand Down
14 changes: 13 additions & 1 deletion webkit/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,16 @@ declare global{
interface Window {
steamDBBrowser: any;
}
}
}

export const Logger = {
Error: (...message: string[]) => {
console.error('%c SteamDB plugin ', 'background: red; color: white', ...message);
},
Log: (...message: string[]) => {
console.log('%c SteamDB plugin ', 'background: purple; color: white', ...message);
},
Warn: (...message: string[]) => {
console.warn('%c SteamDB plugin ', 'background: orange; color: white', ...message);
}
};

0 comments on commit 7855e28

Please sign in to comment.