Skip to content

Commit

Permalink
refactor & fix regex
Browse files Browse the repository at this point in the history
  • Loading branch information
jemikanegara committed Apr 26, 2024
1 parent bffb342 commit 043a023
Show file tree
Hide file tree
Showing 19 changed files with 841 additions and 668 deletions.
2 changes: 1 addition & 1 deletion browser.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const { getTranslations, isBrowser, createLanguageSelect, setOptions } = require("./index.js");

if (isBrowser) {
if (isBrowser()) {
window.weployScriptTag = document.currentScript;

// get options
Expand Down
686 changes: 54 additions & 632 deletions index.js

Large diffs are not rendered by default.

39 changes: 18 additions & 21 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 5 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,6 @@
},
"homepage": "https://github.com/desentio/weploy-translate#readme",
"dependencies": {
"webpack": "^5.88.2",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^4.15.1"
},
"devDependencies": {
"@babel/core": "^7.22.11",
Expand All @@ -41,6 +38,10 @@
"css-minimizer-webpack-plugin": "^6.0.0",
"mini-css-extract-plugin": "^2.8.1",
"raw-loader": "^4.0.2",
"terser-webpack-plugin": "^5.3.10"
"terser-webpack-plugin": "^5.3.10",
"circular-dependency-plugin": "^5.2.2",
"webpack": "^5.88.2",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^4.15.1"
}
}
23 changes: 23 additions & 0 deletions utils/compressions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
function compressToArrayBuffer(string, encoding) {
const byteArray = new TextEncoder().encode(string);
const cs = new CompressionStream(encoding);
const writer = cs.writable.getWriter();
writer.write(byteArray);
writer.close();
return new Response(cs.readable).arrayBuffer();
}

function decompressArrayBuffer(byteArray, encoding) {
const cs = new DecompressionStream(encoding);
const writer = cs.writable.getWriter();
writer.write(byteArray);
writer.close();
return new Response(cs.readable).arrayBuffer().then(function (arrayBuffer) {
return new TextDecoder().decode(arrayBuffer);
});
}

module.exports = {
compressToArrayBuffer,
decompressArrayBuffer,
};
69 changes: 69 additions & 0 deletions utils/configs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// check if code runs on server or client
const isBrowser = () => typeof window !== 'undefined'
const API_URL = "https://api.tasksource.io"

/** Translation Options */
var weployOptions;

function getWeployOptions() {
if (isBrowser()) {
if (!window.weployOptions) {
setWeployOptions({})
}
return window.weployOptions;
} else {
if (!weployOptions) {
setWeployOptions({})
}
return weployOptions;
}
}

function setWeployOptions(value = {}) {
if (isBrowser()) {
window.weployOptions = {
...(window.weployOptions || {}),
...value
};
} else {
weployOptions = {
...(weployOptions || {}),
...value
};
}
}

/** Active Language */
var weployActiveLang;

function getWeployActiveLang() {
if (isBrowser()){
if (!window.weployActiveLang) {
setWeployActiveLang(null)
}
return window.weployActiveLang;
} else {
if (!weployActiveLang) {
setWeployActiveLang(null)
}
return weployActiveLang;
}
}

function setWeployActiveLang(language) {
if (isBrowser()) {
window.weployActiveLang = language
} else {
weployActiveLang = language
}
}

module.exports = {
isBrowser,
getWeployOptions,
setWeployOptions,
getWeployActiveLang,
setWeployActiveLang,
API_URL,
weployOptions
}
35 changes: 35 additions & 0 deletions utils/debounce.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const { isBrowser } = require("./configs");

function getWeployTimer() {
if (!isBrowser()) return null;
if (!window.weployTimer) {
setWeployTimer(null);
}
return window.weployTimer;
}

function setWeployTimer(value) {
if (!isBrowser()) return null;
window.weployTimer = value;
}

const debounce = (mainFunction, delay = 2000) => {
if (!isBrowser()) return mainFunction();

// Return an anonymous function that takes in any number of arguments
return function (...args) {
// Clear the previous timer to prevent the execution of 'mainFunction'
clearTimeout(getWeployTimer());

// Set a new timer that will execute 'mainFunction' after the specified delay
setWeployTimer(setTimeout(() => {
mainFunction(...args);
}, delay));
};
};

module.exports = {
debounce,
getWeployTimer,
setWeployTimer
}
5 changes: 5 additions & 0 deletions utils/delay.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
function delay(time) {
return new Promise(resolve => setTimeout(resolve, time));
}

module.exports = delay;
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

const AllWeployLanguagesList = [
const allWeployLanguagesList = [
{ "label": "Afar", "lang": "aa" },
{ "label": "Avestan", "lang": "ae" },
{ "label": "Afrikaans", "lang": "af" },
Expand Down Expand Up @@ -85,4 +85,4 @@ const AllWeployLanguagesList = [
{ "label": "Chinese", "lang": "zh" },
];

module.exports = AllWeployLanguagesList;
module.exports = allWeployLanguagesList;
46 changes: 46 additions & 0 deletions utils/languages/fetchLanguageList.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
const { isBrowser, API_URL, getWeployOptions, setWeployActiveLang, setWeployOptions } = require("../configs");
const { renderWeploySelectorState } = require("../selector/renderWeploySelectorState");

async function fetchLanguageList(apiKey) {
const options = getWeployOptions();
const langs = options.definedLanguages;
if (langs && Array.isArray(langs) && langs.length) return langs;
if (window.weployError) return [];

const availableLangs = await fetch(API_URL + "/weploy-projects/by-api-key", {
headers: {
"X-Api-Key": apiKey
}
})
.then((res) => res.json())
.then((res) => {
if (res.error) {
throw new Error(res.error?.message || res.error || "Error fetching languages")
}
const languages = [res.language, ...res.allowedLanguages]
const languagesWithFlagAndLabel = languages.map((lang, index) => ({
lang,
flag: (res.flags || [])?.[index] || lang, // fallback to text if flag unavailable
label: (res.labels || [])?.[index] || lang // fallback to text if flag unavailable
}))
setWeployOptions({ definedLanguages: languagesWithFlagAndLabel })
setWeployActiveLang(languagesWithFlagAndLabel[0].lang)
return languagesWithFlagAndLabel
})
.catch((err) => {
console.error(err);
// if (isBrowser()) window.weployOptions.definedLanguages = [] // store in global scope
// else weployOptions.definedLanguages = [] // for npm package
if (isBrowser()) {
window.weployError = err.message;
renderWeploySelectorState({ shouldUpdateActiveLang: false });
}
return [];
})

return availableLangs
}

module.exports = {
fetchLanguageList,
}
63 changes: 63 additions & 0 deletions utils/languages/getSelectedLanguage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
const { getWeployOptions } = require("../configs");
const { fetchLanguageList } = require("./fetchLanguageList");

function getSelectedLanguage() {
return new Promise((resolve, reject) => {
const search = window.location.search;
const params = new URLSearchParams(search);
const paramsLang = params.get('lang');
const localStorageLang = localStorage.getItem("language");

if (paramsLang && (paramsLang != localStorageLang)) {
localStorage.setItem("language", paramsLang);
}

let language = paramsLang || localStorageLang;
if (language) {
resolve(language); // Resolve the promise
}
});
}

async function getLanguageFromLocalStorage() {
const optsArgs = getWeployOptions()
const apiKey = optsArgs.apiKey

const search = window.location.search;
const params = new URLSearchParams(search);
const paramsLang = params.get('lang');
const localStorageLang = localStorage.getItem("language");

if (paramsLang && (paramsLang != localStorageLang)) {
localStorage.setItem("language", paramsLang);
}
let language = paramsLang || localStorageLang;

const availableLangs = await fetchLanguageList(apiKey);
if (!availableLangs.find(l => l.lang == language)) {
saveLanguageToLocalStorage(availableLangs, optsArgs.useBrowserLanguage);
}
return language; // Get the language from local storage
}

function saveLanguageToLocalStorage(availableLangs = [], useBrowserLang = true) {
const language = window.navigator.language; // Get browser language (usually in this format: en-US)
const langIsoCode = language && language.length >= 2 ? language.substring(0, 2) : null // Get the language ISO code
const langInAvailableLangs = availableLangs.find(lang => lang.lang == langIsoCode) // Check if the language is in the available languages

// if no available languages, return
if (!availableLangs.length) {
return;
}

const langInAvailableLangsOrFirst = langInAvailableLangs?.lang || availableLangs[0].lang // If the language is not in the available languages, use the first available language
const langToSave = useBrowserLang ? langInAvailableLangsOrFirst : availableLangs[0].lang // If useBrowserLang is true, use the language from the browser, otherwise use the first available language
// Save the language to local storage
localStorage.setItem("language", langToSave);
}

module.exports = {
getSelectedLanguage,
getLanguageFromLocalStorage,
saveLanguageToLocalStorage
}
Loading

0 comments on commit 043a023

Please sign in to comment.