gravity/options.js

85 lines
2.1 KiB
JavaScript

import {
EVENT_OPTION_SET,
} from './config.js';
export class Options {
sim = undefined;
options = undefined;
values = {};
getStorageKey(path) {
return `${path}:options`;
}
constructor(sim, options) {
this.sim = sim;
this.options = options;
// Global methods to get/set current option values
this.sim.getOption = (path) => this.getOption(path);
this.sim.setOption = (path, value) => this.setOption(path, value);
this.sim.onOptionSet = (path, cb) => this.onOptionSet(path, cb);
// Initialize values from localStorage
for (const groupName of Object.keys(options)) {
for (const [name, [, , defaultValue]] of Object.entries(this.options[groupName])) {
const path = [groupName, name].join('.');
let value = this.getOption(path)
if (value === undefined) {
value = defaultValue;
this.setOption(path, value);
}
}
}
}
getOption(path) {
let value = this.values[path];
if (value === undefined) {
value = localStorage.getItem(this.getStorageKey(path));
if (value === 'false') value = false;
else if (value === 'true') value = true;
this.values[path] = value;
}
return value;
}
setOption(path, value) {
this.values[path] = value;
window.localStorage.setItem(this.getStorageKey(path), value);
const e = new CustomEvent(EVENT_OPTION_SET, {detail: {path, value}});
this.sim.div.dispatchEvent(e);
}
// cb: (value) => undefined
onOptionSet(path, cb) {
this.sim.div.addEventListener(EVENT_OPTION_SET, (e) => {
if (path === e.detail.path) {
cb(e.detail.value);
}
});
}
getSection(sectionName) {
const section = this.options[sectionName];
const group = {
type: 'group',
name: sectionName,
title: section._title,
items: [],
};
for (const name in section) {
if (name.startsWith('_')) continue;
const [title, type, defaultValue, opts] = section[name];
group.items.push({
name,
type,
title,
default: defaultValue,
...opts
})
}
return group;
}
}