Files
myrzx_bot/ranch_web/static/table.js
T

422 lines
22 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, 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 columnEdit(column, row) {
return row.edits?.[column.key] ? {...column.edit, ...row.edits[column.key]} : column.edit;
}
function editableSpec(column, row) {
const edit = columnEdit(column, row);
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, getRow, context, key) {
const get = (path, fallback) => context.get(path, fallback ?? getRow()[key]);
const set = (path, value, field) => {
try { context.set(path, value, field, getRow()); }
catch (error) { context.onError?.(error); }
};
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);
if (document.activeElement !== checkbox) 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 || getRow().member_options || getRow().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, isDrafting: () => drafting};
}
return control(spec, {get, set, onError: context.onError});
}
const rowId = (row, index) => String(row.id ?? index);
const collator = new Intl.Collator('zh-CN', {numeric: true});
export class DataTable {
constructor(host, context, {selection = true, emptyMessage = '当前筛选下没有条目。', pageSize = 50} = {}) {
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.page = 1;
this.pageSize = [25, 50, 100].includes(pageSize) ? pageSize : 50;
this.pageCount = 1;
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('nav', {class: 'table-footer table-pagination', 'aria-label': '表格分页'});
this.count = el('span', {class: 'table-pagination-summary', role: 'status', 'aria-live': 'polite', 'aria-atomic': 'true'});
this.selectionCount = el('span', {class: 'table-selection-summary', role: 'status', 'aria-live': 'polite', hidden: !selection});
this.sizeSelect = el('select', {'aria-label': '每页条目数'}, ...[25, 50, 100].map(size => el('option', {value: size, text: size})));
this.sizeSelect.value = String(this.pageSize);
this.sizeSelect.addEventListener('change', () => {
const size = Number(this.sizeSelect.value);
if (![25, 50, 100].includes(size)) return;
const first = (this.page - 1) * this.pageSize;
this.pageSize = size;
this.setPage(Math.floor(first / size) + 1);
});
this.firstPage = el('button', {type: 'button', text: '首页', onClick: () => this.setPage(1)});
this.previousPage = el('button', {type: 'button', text: '上一页', onClick: () => this.setPage(this.page - 1)});
this.nextPage = el('button', {type: 'button', text: '下一页', onClick: () => this.setPage(this.page + 1)});
this.lastPage = el('button', {type: 'button', text: '末页', onClick: () => this.setPage(this.pageCount)});
this.pageInput = el('input', {type: 'number', min: 1, step: 1, value: 1, 'aria-label': '当前页码'});
this.pageInput.addEventListener('input', () => this.pageInput.setCustomValidity(''));
this.pageInput.addEventListener('change', () => {
const page = Number(this.pageInput.value);
if (!Number.isInteger(page) || page < 1 || page > this.pageCount) {
this.pageInput.setCustomValidity(`请输入 1 到 ${this.pageCount} 之间的页码`);
this.pageInput.reportValidity();
return;
}
this.setPage(page);
});
this.pageInput.addEventListener('blur', () => {
this.pageInput.setCustomValidity('');
this.pageInput.value = String(this.page);
});
this.pageTotal = el('span');
this.footer.append(this.count, this.selectionCount,
el('label', {class: 'table-page-size'}, '每页', this.sizeSelect, '项'),
el('div', {class: 'table-page-controls'}, this.firstPage, this.previousPage,
el('label', {class: 'table-page-current'}, '第', this.pageInput, this.pageTotal), this.nextPage, this.lastPage));
if (selection) {
this.selectFiltered = el('button', {type: 'button', onClick: () => {
this.rows.forEach((row, index) => this.selected.add(rowId(row, index)));
this.syncSelection();
}});
this.clearSelection = el('button', {type: 'button', text: '清除选择', onClick: () => { this.selected.clear(); this.syncSelection(); }});
this.footer.append(el('div', {class: 'table-selection-controls'}, this.selectFiltered, this.clearSelection));
}
host.append(this.scroller, this.footer);
this.onFocusOut = () => queueMicrotask(() => {
if (this.pendingRender && !this.destroyed) this.update(this.columns, this.rows);
});
this.table.addEventListener('focusout', this.onFocusOut);
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.selection && !this.selected.has(id)) {
this.selected.clear();
this.selected.add(id);
this.syncSelection();
}
context.onContext?.(event, this.selectedRows(), this.rowById.get(id));
});
}
selectedRows() { return this.rows.filter((row, index) => this.selected.has(rowId(row, index))); }
setPage(page) {
if (this.body.contains(document.activeElement)) document.activeElement.blur();
this.page = Math.max(1, Math.min(Math.max(1, Math.ceil(this.rows.length / this.pageSize)), page));
this.update(this.columns, this.rows);
this.scroller.scrollTop = 0;
}
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);
}
const selectionText = this.selected.size ? `已选择 ${this.selected.size} 项(含其他分页)` : '';
if (this.selectionCount.textContent !== selectionText) this.selectionCount.textContent = selectionText;
if (this.allCheck) {
const ids = [...this.nodes.keys()];
const selected = ids.filter(id => this.selected.has(id)).length;
this.allCheck.checked = selected > 0 && selected === ids.length;
this.allCheck.indeterminate = selected > 0 && selected < ids.length;
this.allCheck.disabled = !ids.length;
this.allCheck.setAttribute('aria-label', `选择本页全部 ${ids.length} 项`);
this.allCheck.title = `仅选择本页 ${ids.length} 项;其他分页的选择保持不变`;
}
if (this.selectFiltered) {
this.selectFiltered.textContent = `全选筛选结果(${this.rows.length} 项,含其他分页)`;
this.selectFiltered.disabled = !this.rows.length || this.selected.size === this.rows.length;
this.clearSelection.disabled = !this.selected.size;
}
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.nodes.forEach((_, id) => this.allCheck.checked ? this.selected.add(id) : this.selected.delete(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.page = 1;
this.update(this.columns, this.rows);
});
row.append(th);
});
this.head.append(row);
}
setRows(rows) {
this.rows = rows;
this.rowById = new Map(rows.map((row, index) => [rowId(row, index), row]));
for (const id of this.selected) if (!this.rowById.has(id)) this.selected.delete(id);
}
update(columns = [], rows = []) {
if (this.destroyed) return;
this.columns = columns;
this.setRows(rows);
const focusedId = this.body.contains(document.activeElement) ? document.activeElement.closest('tr[data-row-id]')?.dataset.rowId : undefined;
const keepFocus = focusedId !== undefined && this.rowById.has(focusedId);
const signature = JSON.stringify(columns);
if (this.signature !== signature && !keepFocus) {
this.signature = signature;
this.renderedColumns = columns;
this.buildHead(columns);
}
if (this.sort && !columns.some(column => column.key === this.sort.key)) this.sort = null;
const sorted = rows.map((row, index) => ({row, id: rowId(row, index), index}));
if (this.sort) {
const column = columns.find(column => column.key === this.sort.key);
sorted.forEach(item => { item.value = this.sortValue(column, item.row); });
sorted.sort((a, b) => {
const difference = typeof a.value === 'number' && typeof b.value === 'number'
? a.value - b.value : collator.compare(textValue(a.value), textValue(b.value));
return difference * this.sort.direction || a.index - b.index;
});
}
this.pageCount = Math.max(1, Math.ceil(rows.length / this.pageSize));
this.page = Math.min(this.page, this.pageCount);
let visible = sorted.slice((this.page - 1) * this.pageSize, this.page * this.pageSize);
const currentIds = [...this.body.children].map(tr => tr.dataset.rowId);
const orderChanged = visible.length !== currentIds.length || visible.some((item, index) => item.id !== currentIds[index]);
this.pendingRender = keepFocus && (orderChanged || signature !== this.signature);
if (this.pendingRender) {
// Hold the current arrangement until focus leaves. Deleted rows still leave
// immediately, and the retained editors always stay within the page limit.
const retained = currentIds.filter(id => this.rowById.has(id)).slice(0, this.pageSize);
const retainedIds = new Set(retained);
visible = [...retained.map(id => ({id, row: this.rowById.get(id)})),
...visible.filter(item => !retainedIds.has(item.id)).slice(0, this.pageSize - retained.length)];
}
const visibleIds = new Set(visible.map(item => item.id));
for (const [id, node] of this.nodes) {
if (!visibleIds.has(id)) { node.tr.remove(); this.nodes.delete(id); }
}
visible.forEach(({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 (!this.selection || event.target.closest('input,select,textarea,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;
if (node.check) node.check.setAttribute('aria-label', `选择 ${row.name || row.label || id}`);
this.renderedColumns.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.isDrafting?.()) {
cell.control = createCellControl(spec, () => node.row, this.context, column.key);
cell.controlSignature = controlSignature;
cell.td.replaceChildren(cell.control.root);
cell.td.className = 'cell-edit';
}
if (cell.controlSignature !== controlSignature) this.pendingRender = true;
cell.control?.sync();
} else {
if (cell.td.contains(document.activeElement)) { this.pendingRender = true; return; }
cell.control = null;
cell.controlSignature = null;
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;
const first = rows.length ? (this.page - 1) * this.pageSize + 1 : 0;
const last = rows.length ? Math.min(rows.length, first + visible.length - 1) : 0;
const countText = `共 ${rows.length} 项,显示 ${first}–${last} 项${this.pendingRender ? ';编辑完成后更新排列' : ''}`;
if (this.count.textContent !== countText) this.count.textContent = countText;
this.firstPage.disabled = this.previousPage.disabled = this.page === 1;
this.nextPage.disabled = this.lastPage.disabled = this.page === this.pageCount;
this.pageInput.max = String(this.pageCount);
if (document.activeElement !== this.pageInput) this.pageInput.value = String(this.page);
this.pageTotal.textContent = `页 / 共 ${this.pageCount} 页`;
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();
}
sortValue(column, row) {
const edit = columnEdit(column, row);
const value = edit ? this.context.get(editPath(edit.path, row), ['target', 'priority_target', 'target_priority'].includes(edit.type) ? undefined : edit.value ?? row[column.key]) : row[column.key];
if (['target', 'priority_target', 'target_priority'].includes(edit?.type)) return Number(value !== undefined && value !== null && value !== false && value !== 0);
const type = edit?.type || column.type;
if (['boolean', 'bool', 'checkbox'].includes(type)) return Number(Boolean(value));
if (['integer', 'int', 'number', 'float', 'priority'].includes(type) && value !== '' && value != null && Number.isFinite(Number(value))) return Number(value);
return value;
}
destroy() {
this.destroyed = true;
this.table.removeEventListener('focusout', this.onFocusOut);
this.nodes.clear();
}
}
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.table?.destroy(); 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);
else if(group.table) { group.table.setRows(items); group.table.syncSelection(); }
});
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() || []); }
destroy() { this.groups.forEach(group => group.table?.destroy()); this.groups.clear(); }
}