cyp/app/js/settings.js

71 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-03-09 05:11:46 +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() {
super();
this._inputs = {
theme: this.querySelector("[name=theme]"),
color: Array.from(this.querySelectorAll("[name=color]"))
};
2019-04-03 01:52:53 +08:00
2020-03-09 05:11:46 +08:00
this._load();
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));
});
}
_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 05:11:46 +08:00
async _syncTheme() {
const app = await this._app;
this._inputs.theme.value = app.getAttribute("theme");
}
2019-04-03 01:52:53 +08:00
2020-03-09 05:11:46 +08:00
async _syncColor() {
const app = await this._app;
this._inputs.color.forEach(input => {
input.checked = (input.value == app.getAttribute("color"));
input.parentNode.style.color = input.value;
});
}
2019-04-03 01:52:53 +08:00
2020-03-09 05:11:46 +08:00
async _load() {
const app = await this._app;
2019-04-03 01:52:53 +08:00
2020-03-09 05:11:46 +08:00
const theme = loadFromStorage("theme");
(theme ? app.setAttribute("theme", theme) : this._syncTheme());
2019-04-03 01:52:53 +08:00
2020-03-09 05:11:46 +08:00
const color = loadFromStorage("color");
(color ? app.setAttribute("color", color) : this._syncColor());
}
async _setTheme(theme) {
const app = await this._app;
saveToStorage("theme", theme);
app.setAttribute("theme", theme);
}
async _setColor(color) {
const app = await this._app;
saveToStorage("color", color);
app.setAttribute("color", color);
}
2019-04-03 01:52:53 +08:00
}
2020-03-09 05:11:46 +08:00
customElements.define("cyp-settings", Settings);