gravity/tool/options.js
2026-01-01 13:02:12 -06:00

95 lines
2.8 KiB
JavaScript

// Options picker
import {
TOOL_INFO_CLASSNAME,
OPTION_GROUP_CLASSNAME,
WIDE_CLASSNAME,
TALL_CLASSNAME,
} from '../config.js';
import { Tool } from '../tool.js';
export class OptionsTool extends Tool {
sections = undefined;
constructor(sections) {
super();
this.sections = sections;
}
setContainer(container) {
super.setContainer(container);
for (const sectionName of this.sections) {
const option = this.sim.options.getSection(sectionName);
const child = this.visitItem(option);
this.div.appendChild(child);
}
}
visitItem(item, path) {
path = [path, item.name].filter(x => !!x).join('.');
switch (item.type) {
case 'group': {
const group = document.createElement('div');
group.classList.add(OPTION_GROUP_CLASSNAME);
if (item.title) {
const heading = document.createElement('h3');
heading.innerHTML = item.title;
group.appendChild(heading);
}
for (const next of item.items) {
const child = this.visitItem(next, path);
group.appendChild(child);
}
return group;
}
case 'boolean': {
const button = document.createElement('button');
button.innerHTML = item.title;
if (item.wide === true) button.classList.add(WIDE_CLASSNAME);
if (item.tall === true) button.classList.add(TALL_CLASSNAME);
const value = this.sim.getOption(path);
button.style.opacity = value ? '100%' : '50%';
this.sim.onOptionSet(path, value => {
button.style.opacity = value ? '100%' : '50%';
});
button.addEventListener('click', () => {
const value = this.sim.getOption(path);
this.sim.setOption(path, !value);
});
return button;
}
case 'number': {
const div = document.createElement('div');
const title = document.createElement('button');
const input = document.createElement('input');
const maxLength = item.maxLength || 8;
div.appendChild(title);
div.appendChild(input);
div.classList.add(WIDE_CLASSNAME);
title.classList.add(TOOL_INFO_CLASSNAME);
if (item.wide) {
title.classList.add(WIDE_CLASSNAME);
input.classList.add(WIDE_CLASSNAME);
}
title.innerHTML = item.title;
input.value = this.sim.getOption(path);
input.addEventListener('input', () => {
input.value = input.value.slice(0, maxLength);
});
input.addEventListener('change', () => {
this.sim.setOption(path, input.value);
});
this.sim.onOptionSet(path, value => {
input.value = value;
});
return div;
}
default:
throw new Error('Unknown option type');
}
}
}