cyp/app/js/elements/settings.js

72 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-03-10 05:24:31 +08:00
import Component from "../component.js";
2019-04-09 22:08:09 +08:00
2019-04-03 01:52:53 +08:00
const prefix = "cyp";
2020-03-09 05:11:46 +08:00
function loadFromStorage(key) {
return localStorage.getItem(`${prefix}-${key}`);
2019-04-03 01:52:53 +08:00
}
function saveToStorage(key, value) {
return localStorage.setItem(`${prefix}-${key}`, value);
}
2020-03-09 05:11:46 +08:00
class Settings extends Component {
constructor() {
2020-03-10 17:42:13 +08:00
super();
2020-03-09 05:11:46 +08:00
this._inputs = {
theme: this.querySelector("[name=theme]"),
color: Array.from(this.querySelectorAll("[name=color]"))
};
2020-03-09 16:26:10 +08:00
}
2019-04-03 01:52:53 +08:00
2020-03-09 16:26:10 +08:00
_onAppLoad() {
let mo = new MutationObserver(mrs => {
mrs.forEach(mr => this._onAppAttributeChange(mr));
});
mo.observe(this._app, {attributes:true});
2019-04-03 01:52:53 +08:00
2020-03-09 05:11:46 +08:00
this._inputs.theme.addEventListener("change", e => this._setTheme(e.target.value));
this._inputs.color.forEach(input => {
input.addEventListener("click", e => this._setColor(e.target.value));
});
2020-03-09 16:26:10 +08:00
const theme = loadFromStorage("theme");
(theme ? this._app.setAttribute("theme", theme) : this._syncTheme());
const color = loadFromStorage("color");
(color ? this._app.setAttribute("color", color) : this._syncColor());
2020-03-09 05:11:46 +08:00
}
_onAppAttributeChange(mr) {
if (mr.attributeName == "theme") { this._syncTheme(); }
if (mr.attributeName == "color") { this._syncColor(); }
}
2019-04-03 01:52:53 +08:00
2020-03-09 16:26:10 +08:00
_syncTheme() {
this._inputs.theme.value = this._app.getAttribute("theme");
2020-03-09 05:11:46 +08:00
}
2019-04-03 01:52:53 +08:00
2020-03-09 16:26:10 +08:00
_syncColor() {
2020-03-09 05:11:46 +08:00
this._inputs.color.forEach(input => {
2020-03-09 16:26:10 +08:00
input.checked = (input.value == this._app.getAttribute("color"));
2020-03-09 05:11:46 +08:00
input.parentNode.style.color = input.value;
});
}
2019-04-03 01:52:53 +08:00
2020-03-09 16:26:10 +08:00
_setTheme(theme) {
2020-03-09 05:11:46 +08:00
saveToStorage("theme", theme);
2020-03-09 16:26:10 +08:00
this._app.setAttribute("theme", theme);
2020-03-09 05:11:46 +08:00
}
2020-03-09 16:26:10 +08:00
_setColor(color) {
2020-03-09 05:11:46 +08:00
saveToStorage("color", color);
2020-03-09 16:26:10 +08:00
this._app.setAttribute("color", color);
}
_onComponentChange(c, isThis) {
this.hidden = !isThis;
2020-03-09 05:11:46 +08:00
}
2019-04-03 01:52:53 +08:00
}
2020-03-09 05:11:46 +08:00
customElements.define("cyp-settings", Settings);