dom/theme.js

'use strict';

/**
 * @author schukai GmbH
 */

import {Monster, Base} from '../types/base.js';
import {validateString} from "../types/validate.js";
import {getGlobalObject} from '../types/global.js';

/**
 * default theme
 * @type {string}
 */
const DEFAULT_THEME = 'monster';

/**
 * @private
 * @type {string}
 */
const THEME_ATTRIBUTE_NAME = 'data-monster-theme-name';

/**
 * you can call the method via the monster namespace `new Monster.DOM.Theme()`.
 *
 * ```
 * <script type="module">
 * import {Monster} from 'https://cdn.jsdelivr.net/npm/@schukai/monster@1.7.0/dist/modules/dom/theme.js';
 * console.log(new Monster.DOM.Theme())
 * </script>
 * ```
 *
 * Alternatively, you can also integrate this function individually.
 *
 * ```
 * <script type="module">
 * import {Template} from 'https://cdn.jsdelivr.net/npm/@schukai/monster@1.7.0/dist/modules/dom/theme.js';
 * console.log(new Theme())
 * </script>
 * ```
 *
 * @since 1.7.0
 * @copyright schukai GmbH
 * @memberOf Monster/DOM
 */
class Theme extends Base {

    /**
     *
     * @param name
     * @throws {TypeError} value is not a string
     */
    constructor(name) {
        super();
        validateString(name);
        this.name = name;
    }

    /**
     *
     * @returns {string}
     */
    getName() {
        return this.name;
    }

}

/**
 * the theming used in the document can be defined via the html-tag.
 * the theming is specified via the attribute `data-monster-theme-name`.
 *
 * as name for a theme all characters are valid, which are also allowed for a HTMLElement-ID.
 *
 * ```
 * <html data-monster-theme-name="my-theme">
 * ```
 *
 * the default theme name is `monster`.
 *
 * @return {Theme}
 * @since 1.7.0
 */
function findDocumentTheme() {
    let document = getGlobalObject('document');
    let name = DEFAULT_THEME;

    let element = document.querySelector('html');
    if (element instanceof HTMLElement) {
        let theme = element.getAttribute(THEME_ATTRIBUTE_NAME);
        if (theme) {
            name = theme;
        }
    }

    return new Theme(name);

}

Monster.assignToNamespace('Monster.DOM', Theme, findDocumentTheme);
export {Monster, Theme, findDocumentTheme}