frontend/js/common/dom/apply_themes_on_element.js
Paulus Schoutsen 912969111f
Move all of hassUtil to JS ()
* Move all of hassUtil to JS

* Fix tests
2018-05-09 21:33:31 -04:00

42 lines
1.4 KiB
JavaScript

/**
* Apply a theme to an element by setting the CSS variables on it.
*
* element: Element to apply theme on.
* themes: HASS Theme information
* localTheme: selected theme.
* updateMeta: boolean if we should update the theme-color meta element.
*/
export default function applyThemesOnElement(element, themes, localTheme, updateMeta = false) {
if (!element._themes) {
element._themes = {};
}
let themeName = themes.default_theme;
if (localTheme === 'default' || (localTheme && themes.themes[localTheme])) {
themeName = localTheme;
}
const styles = Object.assign({}, element._themes);
if (themeName !== 'default') {
var theme = themes.themes[themeName];
Object.keys(theme).forEach((key) => {
var prefixedKey = '--' + key;
element._themes[prefixedKey] = '';
styles[prefixedKey] = theme[key];
});
}
// implement updateStyles() method of Polemer elements
if (window.ShadyCSS) {
window.ShadyCSS.styleSubtree(/** @type {!HTMLElement} */(element), styles);
}
if (!updateMeta) return;
const meta = document.querySelector('meta[name=theme-color]');
if (meta) {
if (!meta.hasAttribute('default-content')) {
meta.setAttribute('default-content', meta.getAttribute('content'));
}
const themeColor = styles['--primary-color'] || meta.getAttribute('default-content');
meta.setAttribute('content', themeColor);
}
}