-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslation.js
81 lines (65 loc) · 2.66 KB
/
translation.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import enUS from "../locales/en-us.js"
import ptBR from "../locales/pt-br.js"
import { inputState } from "./cryptography.js"
const languages = { en: enUS, pt: ptBR }
const localStorageKey = "novcmbro_decoder_language"
const separator = { nesting: ".", word: "_" }
const translation = {
language: () => localStorage.getItem(localStorageKey),
get: undefined,
translateElements: undefined,
change: undefined,
init: undefined
}
translation.get = (key) => {
const nestedId = key.split(separator.nesting)
let text = languages[translation.language()]
for (let i = 0; i < nestedId.length; i++) {
const key = nestedId[i]
text = text && text[key]
}
return text
}
translation.translateElements = () => {
document.querySelectorAll("meta[name='description']").forEach(description => description.content = translation.get("description"))
document.querySelector("meta[name='keywords']").content = translation.get("keywords")
document.querySelector("#input-field").placeholder = translation.get("input.placeholder")
document.querySelector("#output-placeholder-image").alt = translation.get("output.placeholder.image")
}
translation.change = ({ target }) => {
const selectedLanguage = target.textContent.toLowerCase()
if (translation.language() !== selectedLanguage) {
localStorage.setItem(localStorageKey, selectedLanguage.toLowerCase())
translation.init()
translation.translateElements()
document.querySelector("#sr-alert").textContent = translation.get("footer.language.alert")
}
}
translation.init = () => {
const navigatorLanguage = navigator.language.split("-")[0].toLowerCase()
const navigatorOrFallbackLanguage = (navigatorLanguage === "en" || navigatorLanguage === "pt") ? navigatorLanguage : "en"
const elements = document.querySelectorAll("[data-translation]")
if (!translation.language()) {
localStorage.setItem(localStorageKey, navigatorOrFallbackLanguage)
window.location.href = "/"
}
document.documentElement.lang = translation.language()
document.querySelector("meta[http-equiv='Content-Language']").content = translation.language()
for (const element of elements) {
const id = element.dataset.translation
const hasId = id.trim()
const hasInvalidId = hasId && !id.match(`^[a-z${separator.nesting}${separator.word}]+$`)
if (hasId && !hasInvalidId) {
element.textContent = translation.get(id)
}
}
translation.translateElements()
document.querySelectorAll("[name='language-link']").forEach(languageLink => {
languageLink.addEventListener("click", (e) => {
translation.change(e)
inputState.clearError()
})
})
}
const { get, init } = translation
export default { get, init }