Files
myrzx_bot/ranch_web/static/table.js
T
AttilaNet e26d37e9c5 revert: restore the original pre-redesign web console
Revert 688aad3, 39ac03a, c84dc36, and ff6a828 in reverse chronological order. Restore the exact tracked tree from 99aff42 while preserving history.

Validation: 29 authentication and base-path tests passed offline. All 23 prior UI browser tests ran in system Edge: 22 passed initially; the fake-login test passed on an unchanged isolated retry. Live game HTTP was blocked throughout browser validation.
2026-11-11 10:08:02 +08:00

293 lines
14 KiB
JavaScript

import {el, $, optionsList, pathKey, textValue, number} from './dom.js';
import {control} from './forms.js';
export function editPath(template, row) {
return (template || []).map(part => {
if (typeof part !== 'string') return part;
if (['*', '{id}', '$id', ':id'].includes(part)) return String(row.id);
const match = part.match(/^\{(?:row\.)?([^}]+)\}$|^\$row\.(.+)$/);
if (match) return String(row[match[1] || match[2]] ?? row.id);
return part;
});
}
function editableSpec(column, row) {
const edit = column.edit || row.edits?.[column.key] ? {...column.edit, ...row.edits?.[column.key]} : null;
if (!edit) return null;
return {...edit, path: editPath(edit.path, row), label: `${column.label} · ${row.name || row.label || row.id}`,
options: row[edit.options_key] || row[`${column.key}_options`] || edit.options,
disabled: edit.disabled || row[`${column.key}_disabled`] || row.editable === false};
}
function createCellControl(spec, row, context, key) {
const get = (path, fallback) => context.get(path, fallback ?? row[key]);
const set = (path, value, field) => context.set(path, value, field, row);
const target = ['target', 'priority_target', 'target_priority'].includes(spec.type);
if (target) {
const checkbox = el('input', {type: 'checkbox', 'aria-label': spec.label});
const root = el('div', {class: 'inline-editor'}, checkbox);
root.dataset.configPath = pathKey(spec.path);
checkbox.addEventListener('change', () => set(spec.path, checkbox.checked ? spec.default || 100 : undefined, spec));
const sync = () => {
const current = context.get(spec.path);
checkbox.checked = current !== undefined && current !== null && current !== false && current !== 0;
checkbox.disabled = Boolean(spec.disabled);
};
sync();
return {root, sync, field: spec};
}
if (['members', 'monster_list', 'team_members'].includes(spec.type)) {
const root = el('div', {class: 'member-selects', 'data-config-path': pathKey(spec.path)});
const options = optionsList(spec.options || row.member_options || row.members_options || []);
let drafting=false;
const hint=el('span',{class:'member-draft-note',hidden:true});
const selects = Array.from({length: spec.count || 3}, (_, index) => {
const select = el('select', {'aria-label': `${spec.label}${index === 0 ? '队长' : `队员${index}`}`, disabled: spec.disabled},
el('option', {value: '', text: index === 0 ? '自动选择队长' : '自动选择队员'}),
...options.map(option => el('option', {value: option.value, text: option.label, disabled: option.disabled})));
select.addEventListener('change', () => {
selects.forEach(item=>item.setCustomValidity(''));
const slots=selects.map(item=>item.value), selected=slots.filter(Boolean).map(Number);
if(!select.value){drafting=false;selects.forEach(item=>item.value='');hint.hidden=true;set(spec.path,[],spec);return;}
drafting=true;
const invalid=message=>{hint.textContent=message;hint.hidden=false;select.setCustomValidity(message);};
if (new Set(selected).size !== selected.length) {invalid('探险队员不可重复');return;}
if(selected.length!==3){invalid(`已选择 ${selected.length}/3 只;选满队长和两名队员后保存`);return;}
const leader=options.find(option=>Number(option.value)===selected[0]);
if(leader&&selected.slice(1).some(id=>(options.find(option=>Number(option.value)===id)?.level || 0)>leader.level)){invalid('队员等级不可高于队长');return;}
drafting=false;hint.hidden=true;set(spec.path, selected, spec);
});
root.append(select);
return select;
});
const auto = el('button', {type: 'button', class: 'small', text: '自动选三只', disabled: spec.disabled,
title: '清除手动指定,由核心选择未被战斗队和培养目标占用的空闲魔物', onClick: () => {drafting=false;selects.forEach(item=>{item.value='';item.setCustomValidity('');});hint.hidden=true;set(spec.path, [], spec);}});
root.append(auto,hint);
const sync = () => {
if(drafting)return;
const selected = get(spec.path, []) || [];
selects.forEach((select, index) => { if (document.activeElement !== select) select.value = String(selected[index] ?? ''); });
};
sync();
return {root, sync, field: spec};
}
return control(spec, {get, set, onError: context.onError});
}
export class DataTable {
constructor(host, context, {selection = true, emptyMessage = '当前筛选下没有条目。'} = {}) {
this.host = host;
this.context = context;
this.selection = selection;
this.emptyMessage = emptyMessage;
this.rows = [];
this.nodes = new Map();
this.selected = new Set();
this.sort = null;
this.table = el('table', {class: 'data-table'});
this.head = el('thead');
this.body = el('tbody');
this.table.append(this.head, this.body);
this.empty = el('div', {class: 'empty-state', text: emptyMessage});
this.scroller = el('div', {class: 'table-scroll'}, this.table, this.empty);
this.footer = el('div', {class: 'table-footer'});
this.count = el('span');
this.selectionCount = el('span');
this.footer.append(this.count, this.selectionCount);
host.append(this.scroller, this.footer);
this.table.addEventListener('contextmenu', event => {
const tr = event.target.closest('tr[data-row-id]');
if (!tr) return;
event.preventDefault();
const id = tr.dataset.rowId;
if (!this.selected.has(id)) {
this.selected.clear();
this.selected.add(id);
this.syncSelection();
}
context.onContext?.(event, this.selectedRows(), this.rows.find(row => String(row.id) === id));
});
}
selectedRows() { return this.rows.filter(row => this.selected.has(String(row.id))); }
syncSelection() {
for (const [id, item] of this.nodes) {
item.tr.setAttribute('aria-selected', String(this.selected.has(id)));
if (item.check) item.check.checked = this.selected.has(id);
}
this.selectionCount.textContent = this.selected.size ? `已选择 ${this.selected.size} 项` : '';
if (this.allCheck) {
const selected = this.rows.filter(row => this.selected.has(String(row.id))).length;
this.allCheck.checked = selected > 0 && selected === this.rows.length;
this.allCheck.indeterminate = selected > 0 && selected < this.rows.length;
}
this.context.onSelection?.(this.selectedRows());
}
buildHead(columns) {
this.head.replaceChildren();
this.nodes.clear();
this.body.replaceChildren();
const row = el('tr');
if (this.selection) {
this.allCheck = el('input', {type: 'checkbox', 'aria-label': '选择当前表格全部条目'});
this.allCheck.addEventListener('change', () => {
this.selected.clear();
if (this.allCheck.checked) this.rows.forEach(item => this.selected.add(String(item.id)));
this.syncSelection();
});
row.append(el('th', {scope: 'col', class: 'selection-cell'}, this.allCheck));
}
columns.forEach(column => {
const mark = el('span', {class: 'sort-mark', 'aria-hidden': 'true'});
const label = column.key === 'keep_count' ? '牧场保留' : column.label;
const button = el('button', {type: 'button', title: `按${label}排序`}, label, mark);
const th = el('th', {scope: 'col', 'data-column': column.key}, button);
if (column.width) th.style.minWidth = `${Number(column.width)}px`;
button.addEventListener('click', () => {
this.sort = {key: column.key, direction: this.sort?.key === column.key && this.sort.direction === 1 ? -1 : 1};
this.update(this.columns, this.rows);
});
row.append(th);
});
this.head.append(row);
}
update(columns = [], rows = []) {
const signature = JSON.stringify(columns);
if (this.signature !== signature) {
if (this.host.contains(document.activeElement) && this.signature) return;
this.columns = columns;
this.signature = signature;
this.buildHead(columns);
}
this.rows = rows;
const active = new Set(rows.map(row => String(row.id)));
for (const [id, node] of this.nodes) {
if (!active.has(id) && !node.tr.contains(document.activeElement)) { node.tr.remove(); this.nodes.delete(id); this.selected.delete(id); }
}
const sorted = [...rows];
if (this.sort) {
const {key, direction} = this.sort;
sorted.sort((a, b) => {
const aValue = a[key], bValue = b[key];
if (typeof aValue === 'number' && typeof bValue === 'number') return (aValue - bValue) * direction;
return textValue(aValue).localeCompare(textValue(bValue), 'zh-CN', {numeric: true}) * direction;
});
}
sorted.forEach((row, index) => {
const id = String(row.id ?? index);
let node = this.nodes.get(id);
if (!node) {
const tr = el('tr', {'data-row-id': id, 'aria-selected': 'false', tabindex: -1});
const check = this.selection ? el('input', {type: 'checkbox', 'aria-label': `选择 ${row.name || row.label || id}`}) : null;
if (check) {
check.addEventListener('change', () => { check.checked ? this.selected.add(id) : this.selected.delete(id); this.syncSelection(); });
tr.append(el('td', {class: 'selection-cell'}, check));
}
tr.addEventListener('click', event => {
if (event.target.closest('input,select,button,a,label')) return;
if (!event.ctrlKey && !event.metaKey && !event.shiftKey) this.selected.clear();
this.selected.add(id);
this.syncSelection();
});
tr.addEventListener('dblclick', event => {
if (!event.target.closest('input,select,button,a,label')) this.context.onDetail?.(node.row);
});
node = {tr, check, cells: new Map(), row};
this.nodes.set(id, node);
}
node.row = row;
columns.forEach(column => {
let cell = node.cells.get(column.key);
if (!cell) {
const td = el('td', {'data-column': column.key});
cell = {td};
node.cells.set(column.key, cell);
node.tr.append(td);
}
const spec = editableSpec(column, row);
if (spec) {
const controlSignature = JSON.stringify(spec);
if (!cell.control || cell.controlSignature !== controlSignature && !cell.td.contains(document.activeElement)) {
cell.control = createCellControl(spec, row, this.context, column.key);
cell.controlSignature = controlSignature;
cell.td.replaceChildren(cell.control.root);
cell.td.className = 'cell-edit';
}
cell.control?.sync();
} else {
const value = row[column.key];
const text = typeof value==='number'?number(value):textValue(value);
if (cell.td.textContent !== text) cell.td.textContent = text;
cell.td.title = row.tooltips?.[column.key] || text;
cell.td.className = `${typeof value === 'number' || ['number', 'integer'].includes(column.type) ? 'number ' : ''}${column.type === 'wrap' ? 'cell-wrap' : 'cell-ellipsis'}`;
}
});
// Inserting a node unnecessarily can blur a focused native number input.
const existing = this.body.children[index];
if (existing !== node.tr && !node.tr.contains(document.activeElement)) this.body.insertBefore(node.tr, existing || null);
});
this.empty.hidden = Boolean(rows.length);
this.table.hidden = !columns.length;
this.count.textContent = `共 ${rows.length} 项`;
for (const th of this.head.querySelectorAll('[data-column]')) {
const activeSort = this.sort?.key === th.dataset.column;
th.setAttribute('aria-sort', activeSort ? this.sort.direction === 1 ? 'ascending' : 'descending' : 'none');
$('.sort-mark', th).textContent = activeSort ? this.sort.direction === 1 ? '▲' : '▼' : '';
}
this.syncSelection();
}
}
export class GroupedTables {
constructor(host, context, {collapsed = true} = {}) {
this.host = host;
this.context = context;
this.collapsed = collapsed;
this.groups = new Map();
this.host.classList.add('grouped-tables');
}
update(columns, rows, groupBy, labels = {}, metadata = {}) {
const grouped = new Map();
rows.forEach(row => {
const key = String(typeof groupBy === 'function' ? groupBy(row) : row[groupBy] ?? '其他');
if (!grouped.has(key)) grouped.set(key, []);
grouped.get(key).push(row);
});
for (const [key, group] of this.groups) if (!grouped.has(key)) { group.root.remove(); this.groups.delete(key); }
grouped.forEach((items, key) => {
let group = this.groups.get(key);
if (!group) {
const summary = el('summary');
const container = el('div', {class: 'group-table'});
const root = el('details', {class: 'table-group', open: metadata[key]?.collapsed === false || !this.collapsed}, summary, container);
container.style.display = 'flex';
container.style.flexDirection = 'column';
group = {root, summary, container, table:null};
const item=group;
root.addEventListener('toggle',()=>{if(root.open)this.renderGroup(item);});
this.groups.set(key, group);
this.host.append(root);
}
group.summary.replaceChildren(document.createTextNode(labels[key] || key), el('small', {text: `${items.length} 项`}));
group.columns=columns;group.items=items;
if(group.root.open)this.renderGroup(group);
});
if (!grouped.size) {
if (!this.empty) { this.empty = el('div', {class: 'empty-state', text: '当前筛选下没有条目。'}); this.host.append(this.empty); }
}
if (this.empty) this.empty.hidden = Boolean(grouped.size);
}
renderGroup(group) {
if(!group.table)group.table=new DataTable(group.container,this.context);
group.table.update(group.columns || [],group.items || []);
}
expand(open) { this.groups.forEach(group => { group.root.open = open; }); }
selectedRows() { return [...this.groups.values()].flatMap(group => group.table?.selectedRows() || []); }
}