@lucsoft/webgen
Version:
Collection of lucsofts Components
82 lines (81 loc) • 3.23 kB
JavaScript
import { blur, dark, light } from '../css/themes';
import { createElement } from "../components/Components";
export class Style {
constructor(options) {
this.current = 1 /* gray */;
this.mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
this.getTheme = () => this.current;
this.getColors = () => ({
["critical" /* Critical */]: [360, 86, 65, "#333333"],
["colored" /* Colored */]: [227, 85, 65, "#FFFFFF"],
["grayscaled" /* Grayscaled */]: [0, 0, 100, "#333333"],
["disabled" /* Disabled */]: [0, 0, 75, "#A0A0A0"],
});
this.getMapping = () => ({
[0 /* light */]: light,
[1 /* gray */]: {},
[2 /* dark */]: dark,
[3 /* blur */]: blur,
[6 /* autoLight */]: light,
[5 /* autoDark */]: dark,
});
const styleAppendTo = options.defaultElementToHookStylesIn ?? document.documentElement;
this.options = options;
if (options.autoLoadFonts ?? true) {
var roboto = createElement('link');
roboto.rel = "stylesheet";
roboto.href = "https://fonts.googleapis.com/css?family=Roboto:100,200,300,400,500&display=swap";
styleAppendTo.append(roboto);
}
this.theme = styleAppendTo;
this.mediaQuery.addEventListener('change', e => {
if (this.current == 5 /* autoDark */ || this.current == 6 /* autoLight */)
this.updateTheme(e.matches ? 5 /* autoDark */ : 6 /* autoLight */);
});
}
setImage(src) {
document.body.style.background = `url(${src}) no-repeat center center fixed`;
document.body.style.backgroundAttachment = "cover";
}
clearImage() {
document.body.style.background = "";
}
overrideTheme(data) {
const dataWithDefaults = {
...this.getMapping()[this.current],
...data
};
this.applyStyles(dataWithDefaults);
}
mapColorDef(data) {
const object = {};
Object.entries(data).forEach(([color, values]) => {
const indexToName = ["hue", "saturation", "lightness", "font"];
values.forEach((value, index) => {
object[`--color-${color}-${indexToName[index]}`] = value.toString() + (["deg", "%", "%", ""][index]);
});
});
return object;
}
applyStyles(data) {
const extendData = {
...this.mapColorDef(this.getColors()),
...data
};
Object.entries(extendData).forEach(([key, value]) => this.theme.style.setProperty(key, value));
}
updateTheme(theme) {
this.options.events?.themeRefreshed?.(theme, this);
if (theme === 4 /* auto */)
this.updateTheme(this.mediaQuery.matches ? 5 /* autoDark */ : 6 /* autoLight */);
else {
if (this.current == theme)
return;
if (theme === 1 /* gray */)
this.theme.removeAttribute("style");
this.applyStyles(this.getMapping()[theme]);
this.current = theme;
this.options.events?.themeChanged?.(theme, this);
}
}
}