feat: redesign the web console with Vue and isolated account workspaces

This commit is contained in:
AttilaNet
2026-11-11 09:35:54 +08:00
parent 99aff423d8
commit ff6a828f58
46 changed files with 4549 additions and 748 deletions
+172 -43
View File
@@ -11,17 +11,24 @@ export function editPath(template, row) {
});
}
function columnEdit(column, row) {
return row.edits?.[column.key] ? {...column.edit, ...row.edits[column.key]} : column.edit;
}
function editableSpec(column, row) {
const edit = column.edit || row.edits?.[column.key] ? {...column.edit, ...row.edits?.[column.key]} : null;
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, row, context, key) {
const get = (path, fallback) => context.get(path, fallback ?? row[key]);
const set = (path, value, field) => context.set(path, value, field, row);
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});
@@ -30,7 +37,7 @@ function createCellControl(spec, row, context, key) {
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;
if (document.activeElement !== checkbox) checkbox.checked = current !== undefined && current !== null && current !== false && current !== 0;
checkbox.disabled = Boolean(spec.disabled);
};
sync();
@@ -38,7 +45,7 @@ function createCellControl(spec, row, context, key) {
}
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 || []);
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) => {
@@ -69,13 +76,16 @@ function createCellControl(spec, row, context, key) {
selects.forEach((select, index) => { if (document.activeElement !== select) select.value = String(selected[index] ?? ''); });
};
sync();
return {root, sync, field: spec};
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 = '当前筛选下没有条目。'} = {}) {
constructor(host, context, {selection = true, emptyMessage = '当前筛选下没有条目。', pageSize = 50} = {}) {
this.host = host;
this.context = context;
this.selection = selection;
@@ -84,43 +94,107 @@ export class DataTable {
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('div', {class: 'table-footer'});
this.count = el('span');
this.selectionCount = el('span');
this.footer.append(this.count, this.selectionCount);
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.selected.has(id)) {
if (this.selection && !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));
context.onContext?.(event, this.selectedRows(), this.rowById.get(id));
});
}
selectedRows() { return this.rows.filter(row => this.selected.has(String(row.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);
}
this.selectionCount.textContent = this.selected.size ? `已选择 ${this.selected.size} 项` : '';
const selectionText = this.selected.size ? `已选择 ${this.selected.size} 项(含其他分页)` : '';
if (this.selectionCount.textContent !== selectionText) this.selectionCount.textContent = selectionText;
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;
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());
}
@@ -131,10 +205,9 @@ export class DataTable {
this.body.replaceChildren();
const row = el('tr');
if (this.selection) {
this.allCheck = el('input', {type: 'checkbox', 'aria-label': '选择当前表格全部条目'});
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.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));
@@ -147,6 +220,7 @@ export class DataTable {
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);
@@ -154,30 +228,54 @@ export class DataTable {
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) {
if (this.host.contains(document.activeElement) && this.signature) return;
this.columns = columns;
if (this.signature !== signature && !keepFocus) {
this.signature = signature;
this.renderedColumns = columns;
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 && !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 {key, direction} = 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 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;
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;
});
}
sorted.forEach((row, index) => {
const id = String(row.id ?? 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});
@@ -187,7 +285,7 @@ export class DataTable {
tr.append(el('td', {class: 'selection-cell'}, check));
}
tr.addEventListener('click', event => {
if (event.target.closest('input,select,button,a,label')) return;
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();
@@ -199,7 +297,8 @@ export class DataTable {
this.nodes.set(id, node);
}
node.row = row;
columns.forEach(column => {
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});
@@ -210,14 +309,18 @@ export class DataTable {
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);
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;
@@ -231,7 +334,15 @@ export class DataTable {
});
this.empty.hidden = Boolean(rows.length);
this.table.hidden = !columns.length;
this.count.textContent = `共 ${rows.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');
@@ -239,6 +350,22 @@ export class DataTable {
}
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 {
@@ -257,7 +384,7 @@ export class GroupedTables {
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); }
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) {
@@ -275,6 +402,7 @@ export class GroupedTables {
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); }
@@ -289,4 +417,5 @@ export class GroupedTables {
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(); }
}