Files
myrzx_bot/ranch_web/static/forms.js
T

189 lines
9.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {el, $, optionsList, pathKey} from './dom.js';
function readNumber(input, integer = true) {
if (input.value.trim() === '' || !input.checkValidity()) return undefined;
const value = Number(input.value);
return Number.isFinite(value) && (!integer || Number.isInteger(value)) ? value : undefined;
}
// A control is created once, then synchronized without replacing its input node.
export function control(field, {get, set, onError = () => {}}) {
const type = field.type || 'text';
const path = field.path || [];
const label = field.label || path.at(-1) || '设置';
let root, sync;
const commit = value => {
try { set(path, value, field); } catch (error) { onError(error); }
};
const value = () => get(path, field.value);
if (type === 'add_rule') {
const select = el('select', {'aria-label': label}, el('option', {value: '', text: '选择魔物蛋(含无库存)'}), ...optionsList(field.options).map(option => el('option', {value: option.value, text: `${option.label} [${option.value}]`})));
const add = el('button', {type: 'button', text: '添加无库存蛋规则'});
add.addEventListener('click', () => {
if (!select.value) { select.focus(); return; }
const defaults=field.defaults_by_id?.[select.value] || field.defaults || {};
set([...path, select.value], get([...path, select.value], defaults), field);
});
root = el('div', {class: 'inline-editor'}, select, add);
sync = () => {};
} else if (['boolean', 'bool', 'checkbox'].includes(type)) {
root = el('input', {type: 'checkbox', 'aria-label': label});
root.addEventListener('change', () => commit(root.checked));
sync = () => { root.checked = Boolean(value()); };
} else if (['select', 'enum'].includes(type)) {
root = el('select', {'aria-label': label});
let optionsSignature;
const fill = () => {
const options = optionsList(typeof field.options === 'function' ? field.options() : field.options);
const signature = JSON.stringify(options);
if (signature !== optionsSignature && document.activeElement !== root) {
root.replaceChildren(...options.map(option => el('option', {value: String(option.value), text: option.label, disabled: option.disabled})));
optionsSignature = signature;
}
return options;
};
root.addEventListener('change', () => {
const selected = fill().find(option => String(option.value) === root.value);
if (selected) commit(selected.value);
});
sync = () => {
fill();
if (document.activeElement !== root) root.value = String(value() ?? '');
};
} else if (['multiselect', 'multi_select'].includes(type)) {
root = el('div', {class: 'multi-select', role: 'group', 'aria-label': label});
const items = optionsList(field.options).map(option => {
const check = el('input', {type: 'checkbox', 'aria-label': option.label});
check.addEventListener('change', () => commit(items.filter(item => item.check.checked).map(item => item.option.value)));
root.append(el('label', {}, check, option.label));
return {check, option};
});
sync = () => items.forEach(({check, option}) => { check.checked = (value() || []).includes(option.value); });
} else if (['id_counts', 'counts', 'reserves'].includes(type)) {
root = el('div', {class: 'counts-editor', role: 'group', 'aria-label': label});
const lines = el('div', {class: 'counts-lines'});
const add = el('button', {type: 'button', class: 'small', text: '添加编号 / 数量'});
root.append(lines, add);
let signature;
const save = () => {
const result = {};
for (const line of [...lines.children]) {
const id = $('input[data-part=id]', line), count = $('input[data-part=count]', line);
if (!id.value.trim() && count.value === '') continue;
const number = readNumber(count);
if (!/^[1-9]\d*$/.test(id.value.trim()) || number === undefined || result[id.value.trim()] !== undefined) {
id.setCustomValidity('请输入不重复的正整数编号和有效数量');
return;
}
id.setCustomValidity('');
result[id.value.trim()] = number;
}
signature = JSON.stringify(result);
commit(result);
};
const addLine = (id = '', count = '') => {
const idInput = el('input', {type: 'text', inputmode: 'numeric', value: id, placeholder: '编号', 'aria-label': `${label}物品编号`, 'data-part': 'id', class: 'count-id'});
const countInput = el('input', {type: 'number', min: 0, max: 1000000000, step: 1, value: count, placeholder: '数量', 'aria-label': `${label}数量`, 'data-part': 'count'});
const line = el('div', {class: 'inline-editor'}, idInput, countInput);
line.append(el('button', {type: 'button', class: 'small', text: '移除', onClick: () => { line.remove(); save(); }}));
idInput.addEventListener('input', () => { idInput.setCustomValidity(''); save(); });
countInput.addEventListener('input', save);
lines.append(line);
return idInput;
};
add.addEventListener('click', () => addLine().focus());
sync = () => {
if (root.contains(document.activeElement)) return;
const next = value() || {};
if (JSON.stringify(next) === signature) return;
lines.replaceChildren();
Object.entries(next).forEach(([id, count]) => addLine(id, count));
signature = JSON.stringify(next);
};
} else {
const numeric = ['integer', 'int', 'number', 'float', 'priority'].includes(type);
root = el('input', {type: numeric ? 'number' : 'text', 'aria-label': label, min: field.min ?? (numeric ? 0 : undefined), max: field.max,
step: field.step ?? (['number', 'float'].includes(type) ? 'any' : numeric ? 1 : undefined), placeholder: field.placeholder});
root.addEventListener('input', () => {
if (numeric) {
const next = readNumber(root, !['number', 'float'].includes(type));
if (next !== undefined) commit(next);
} else if (['id_list', 'ids'].includes(type)) {
const parts = root.value.split(/[,,;;\s]+/).filter(Boolean);
if (parts.some(part => !/^[1-9]\d*$/.test(part))) { root.setCustomValidity('编号须为正整数,多个编号用逗号分隔'); return; }
root.setCustomValidity('');
commit([...new Set(parts.map(Number))]);
} else commit(root.value);
});
sync = () => {
if (document.activeElement === root) return;
const next = value();
root.value = ['id_list', 'ids'].includes(type) ? (next || []).join(', ') : next ?? '';
};
}
root.dataset.configPath = pathKey(path);
root.title = field.help || field.description || label;
root.disabled = Boolean(field.disabled || field.readonly);
sync();
return {root, sync, field};
}
export class PolicyForm {
constructor(host, context) {
this.host = host;
this.context = context;
this.controls = [];
this.signature = '';
}
update(fields = []) {
if (!Array.isArray(fields)) fields = fields.fields || [];
const signature = JSON.stringify(fields.map(({value, ...field}) => field));
if (signature !== this.signature && !this.host.contains(document.activeElement)) {
this.host.replaceChildren();
this.controls = [];
const groups = new Map();
fields.forEach(field => {
if (!Array.isArray(field.path) || field.hidden) return;
const group = field.group || '';
if (!groups.has(group)) {
const grid = el('div', {class: 'form-grid'});
const section = group ? el('fieldset', {class: 'form-section'}, el('legend', {text: group}), grid) : grid;
this.host.append(section);
groups.set(group, grid);
}
const entry = control(field, this.context);
entry.root.classList.add('field-input');
const boolean = ['boolean', 'bool', 'checkbox'].includes(field.type);
const wide = ['id_counts', 'counts', 'reserves', 'multiselect'].includes(field.type);
const row = el('label', {class: `field${boolean ? ' checkbox-field' : ''}${wide ? ' field-wide' : ''}`, title: field.help || field.description || ''});
if (entry.root.tagName === 'DIV') {
const fieldRow = el('div', {class: `field${wide ? ' field-wide' : ''}`}, el('span', {class: 'field-label', text: field.label}), entry.root);
groups.get(group).append(fieldRow);
entry.row = fieldRow;
} else {
row.append(el('span', {class: 'field-label', text: field.label}), entry.root);
groups.get(group).append(row);
entry.row = row;
}
if (field.help || field.description) groups.get(group).append(el('span', {class: 'field-help', text: field.help || field.description}));
this.controls.push(entry);
});
this.signature = signature;
}
this.host.hidden = !fields.length;
this.controls.forEach(entry => {
const latest = fields.find(field => pathKey(field.path) === pathKey(entry.field.path));
if (latest) Object.assign(entry.field, latest);
entry.sync();
entry.row.dataset.dirty = String(Boolean(this.context.dirty?.(entry.field.path)));
});
}
}
// Keep native number behavior only for the number field the user is editing.
document.addEventListener('wheel', event => {
const input = event.target.closest?.('input[type=number]');
if (input && document.activeElement !== input) event.preventDefault();
}, {passive: false});