Skip to content
Snippets Groups Projects
Select Git revision
  • e9cbcfc578d58748bb45e1355a5a3d9e4a1d24d8
  • master default protected
  • 1.31
  • 4.38.5
  • 4.38.4
  • 4.38.3
  • 4.38.2
  • 4.38.1
  • 4.38.0
  • 4.37.2
  • 4.37.1
  • 4.37.0
  • 4.36.0
  • 4.35.0
  • 4.34.1
  • 4.34.0
  • 4.33.1
  • 4.33.0
  • 4.32.2
  • 4.32.1
  • 4.32.0
  • 4.31.0
  • 4.30.1
23 results

locale.mjs

Blame
  • Volker Schukai's avatar
    14beaadb
    History
    locale.mjs 2.13 KiB
    /**
     * Copyright schukai GmbH and contributors 2023. 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();
    
    	const html = document.querySelector("html");
    	if (html instanceof HTMLElement && html.hasAttribute("lang")) {
    		const locale = html.getAttribute("lang");
    		if (locale) {
    			return new parseLocale(locale);
    		}
    	}
    
    	const 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;
    };