Something went wrong on our end
Select Git revision
-
Volker Schukai authoredVolker Schukai authored
locale.mjs 2.24 KiB
/**
* Copyright schukai GmbH and contributors 2022. All Rights Reserved.
* Node module: @schukai/monster
* This file is licensed under the AGPLv3 License.
* License text available at https://www.gnu.org/licenses/agpl-3.0.en.html
*/
import { parseLocale } from "../i18n/locale.mjs";
import { getDocument } from "./util.mjs";
import { getGlobalObject } from "../types/global.mjs";
export { getLocaleOfDocument };
/**
* @private
* @type {string}
*/
const DEFAULT_LANGUAGE = "en";
/**
* With this function you can read the language version set by the document.
* For this the attribute `lang` in the html tag is read. If no attribute is set, `en` is used as default.
* Alternatively, the language version of the browser is used.
*
* ```html
* <html lang="en">
* ```
*
* You can call the function via `getLocaleOfDocument()`.
*
* @license AGPLv3
* @since 1.13.0
* @copyright schukai GmbH
* @memberOf Monster.DOM
* @throws {TypeError} value is not a string
* @throws {Error} unsupported locale
* @summary Tries to determine the locale used
*/
function getLocaleOfDocument() {
const document = getDocument();
let html = document.querySelector("html");
if (html instanceof HTMLElement && html.hasAttribute("lang")) {
let locale = html.getAttribute("lang");
if (locale) {
return new parseLocale(locale);
}
}
let navigatorLanguage = getNavigatorLanguage();
if (navigatorLanguage) {
return parseLocale(navigatorLanguage);
}
return parseLocale(DEFAULT_LANGUAGE);
}
/**
* @private
* @returns {string|undefined|*}
* @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/language
* @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/languages
*/
const getNavigatorLanguage = () => {
const navigator = getGlobalObject("navigator");
if (navigator === undefined) {
return undefined;
}
if (navigator.hasOwnProperty("language")) {
const language = navigator.language;
if (typeof language === "string" && language.length > 0) {
return language;
}
}
const languages = navigator?.languages;
if (Array.isArray(languages) && languages.length > 0) {
return languages[0];
}
return undefined;
};