Files
nixingnishang_level-editor/mainline.js
T

174 lines
14 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(() => {
'use strict';
const actions = document.querySelector('.file-actions');
function button(id, title, icon, text = '') {
const element = document.createElement('button'); element.id = id; element.title = element.ariaLabel = title;
element.innerHTML = '<i data-lucide="' + icon + '"></i>' + text; return element;
}
const manage = button('mainline-manage', '主线编排', 'list-ordered', '主线编排');
const importButton = button('package-import', '导入关卡数据包', 'folder-input');
const exportButton = button('package-export', '导出全部关卡数据包', 'package-open');
const projectExport = button('project-export', '导出项目文件包 ZIP', 'folder-down');
actions.insertBefore(manage, $('dirty')); actions.insertBefore(importButton, $('import')); actions.insertBefore(exportButton, $('export'));
actions.insertBefore(projectExport, exportButton);
const helpButton = button('editor-help', '使用说明', 'circle-help'); actions.append(helpButton);
helpButton.onclick = () => { const help = $('help-dialog'); if (!help.open) help.showModal(); };
const exportDialog = document.createElement('dialog'); exportDialog.id = 'project-export-dialog'; exportDialog.setAttribute('aria-labelledby', 'project-export-title');
exportDialog.innerHTML = '<form method="dialog"><div class="mainline-heading"><h2 id="project-export-title">导出项目 JSON</h2><button value="cancel" title="关闭" aria-label="关闭"><i data-lucide="x"></i></button></div>' +
'<div class="mainline-row"><button id="project-export-changes" value="changes"><i data-lucide="file-diff"></i>导出变更 JSON</button><button id="project-export-all" class="primary" value="all"><i data-lucide="files"></i>导出全部 JSON</button></div></form>';
document.body.append(exportDialog);
const input = document.createElement('input'); input.type = 'file'; input.accept = '.json'; input.hidden = true; document.body.append(input);
const dialog = document.createElement('dialog'); dialog.id = 'mainline-dialog'; dialog.setAttribute('aria-labelledby', 'mainline-title');
dialog.innerHTML = '<div class="mainline-heading"><h2 id="mainline-title">主线编排</h2><button id="mainline-close" aria-label="关闭" title="关闭"><i data-lucide="x"></i></button></div>' +
'<div class="mainline-summary"><strong id="mainline-count"></strong><span id="mainline-pending"></span></div>' +
'<input id="mainline-search" type="search" placeholder="搜索关卡号或来源 ID" aria-label="搜索主线关卡">' +
'<select id="mainline-list" size="12" aria-label="主线关卡列表"></select>' +
'<div class="mainline-row"><label>新增方式 <select id="mainline-kind"><option value="copy">复制选中关卡</option><option value="empty">空白布局</option></select></label>' +
'<button id="mainline-add"><i data-lucide="plus"></i>新增至末尾</button><button id="mainline-insert"><i data-lucide="list-plus"></i>插入选中关卡之后</button></div>' +
'<div class="mainline-row"><button id="mainline-up" title="上移一关" aria-label="上移一关"><i data-lucide="arrow-up"></i></button><button id="mainline-down" title="下移一关" aria-label="下移一关"><i data-lucide="arrow-down"></i></button>' +
'<label>移动到第 <input id="mainline-target" type="number" min="1" value="1" aria-label="目标关卡号"> 关</label><button id="mainline-move"><i data-lucide="arrow-right-to-line"></i>移动</button>' +
'<button id="mainline-undo" title="撤销编排" aria-label="撤销编排"><i data-lucide="undo-2"></i></button><button id="mainline-remove"><i data-lucide="trash-2"></i>从主线移除</button></div>' +
'<p id="mainline-error" role="alert"></p><div class="mainline-footer"><button id="mainline-cancel">取消</button><button id="mainline-apply" class="primary"><i data-lucide="check"></i>应用编排</button></div>';
document.body.append(dialog); icons();
let draft, revision, selected, history = [], modified = false, initialModified = false, submitting = false;
function redraw() {
draft.levels.forEach((level, index) => { level.displayLevel = index + 1; });
const search = $('mainline-search').value.trim().toLowerCase(), list = $('mainline-list'); list.replaceChildren();
draft.order.forEach((id, index) => {
const text = '第 ' + (index + 1) + ' 关 来源 ' + id + ' ' + draft.levels[index].characters.length + ' 军械 / ' + draft.levels[index].aoes.length + ' 机关';
if (search && !text.toLowerCase().includes(search)) return;
const option = document.createElement('option'); option.value = id; option.textContent = text; list.append(option);
});
list.value = selected; $('mainline-count').textContent = '共 ' + draft.order.length + ' 关';
requestAnimationFrame(() => { if (dialog.open) list.selectedOptions[0]?.scrollIntoView({ block: 'nearest' }); });
$('mainline-pending').textContent = modified ? '待应用' : '已同步'; $('mainline-target').max = draft.order.length;
const index = draft.order.indexOf(selected);
$('mainline-up').disabled = index <= 0; $('mainline-down').disabled = index < 0 || index === draft.order.length - 1;
$('mainline-remove').disabled = index < 0 || draft.order.length <= 1;
$('mainline-undo').disabled = !history.length; $('mainline-apply').disabled = !modified;
}
function remember() {
history.push({ draft: clone(draft), selected }); if (history.length > 20) history.shift(); modified = true; $('mainline-error').textContent = '';
}
function create(append) {
if (MainlineWorkspace.sourceOrder(draft).length >= 20000) throw new Error('来源库存最多支持 20000 关');
const index = draft.order.indexOf(selected); if (index < 0) throw new Error('请先选择模板关卡');
remember(); const id = Math.max(...MainlineWorkspace.sourceOrder(draft)) + 1, level = clone(draft.levels[index]);
if ($('mainline-kind').value === 'empty') { level.characters = []; level.aoes = []; }
const position = append ? draft.order.length : index + 1;
draft.templates[id] = draft.templates[selected]; draft.order.splice(position, 0, id); draft.levels.splice(position, 0, level);
selected = id; $('mainline-search').value = ''; $('mainline-target').value = position + 1; redraw();
}
function move(target) {
const index = draft.order.indexOf(selected);
if (!Number.isInteger(target) || target < 0 || target >= draft.order.length) throw new Error('目标关卡号超出范围');
if (index < 0 || index === target) return;
remember(); draft.order.splice(target, 0, draft.order.splice(index, 1)[0]); draft.levels.splice(target, 0, draft.levels.splice(index, 1)[0]); redraw();
}
const localGuard = action => () => { if (submitting) return; try { action(); } catch (error) { $('mainline-error').textContent = error.message; } };
function close() { if (!submitting && (!modified || confirm('编排尚未应用,确定放弃?'))) dialog.close(); }
$('mainline-close').onclick = close; $('mainline-cancel').onclick = close;
dialog.addEventListener('cancel', event => { event.preventDefault(); close(); });
dialog.addEventListener('keydown', event => event.stopPropagation());
$('mainline-list').onchange = () => { selected = Number($('mainline-list').value); $('mainline-target').value = draft.order.indexOf(selected) + 1; redraw(); };
$('mainline-search').oninput = redraw;
$('mainline-add').onclick = localGuard(() => create(true)); $('mainline-insert').onclick = localGuard(() => create(false));
$('mainline-up').onclick = localGuard(() => move(draft.order.indexOf(selected) - 1));
$('mainline-down').onclick = localGuard(() => move(draft.order.indexOf(selected) + 1));
$('mainline-move').onclick = localGuard(() => move(Number($('mainline-target').value) - 1));
$('mainline-remove').onclick = localGuard(() => {
const index = draft.order.indexOf(selected);
if (index < 0) throw new Error('请先选择要移除的关卡');
if (draft.order.length <= 1) throw new Error('主线至少保留一关');
if (!confirm('从主线移除第 ' + (index + 1) + ' 关(来源 ' + selected + ')?后续关卡前移,底层来源布局与逐鹿引用会保留。应用前可撤销。')) return;
remember(); draft.archivedLevels ||= {}; draft.archivedLevels[selected] = clone(draft.levels[index]);
draft.order.splice(index, 1); draft.levels.splice(index, 1);
selected = draft.order[Math.min(index, draft.order.length - 1)];
$('mainline-search').value = ''; $('mainline-target').value = draft.order.indexOf(selected) + 1; redraw();
});
$('mainline-undo').onclick = localGuard(() => { const previous = history.pop(); if (previous) { draft = previous.draft; selected = previous.selected; modified = initialModified || history.length > 0; redraw(); } });
async function refresh(number, text) {
try { localStorage.removeItem(draftKey()); } catch { /* 工作区已经保存,清理旧草稿失败不阻断打开。 */ }
state.baseline = layoutText(state.level); state.selected = null;
const bootstrap = await api('/api/bootstrap'); Object.assign(state, bootstrap);
$('level-total').textContent = '/ ' + state.levelCount; $('level-number').max = state.levelCount;
setBusy(false); await openLevel(Math.min(number, state.levelCount)); message(text);
}
async function snapshot() {
if (pendingExtra()) applyExtra();
const validation = await api(state.mode === 'ghost-king' ? '/api/ghost-validate' : '/api/validate', { level: state.level });
if (validation.issues.length) throw new Error('当前关卡校验失败:' + validation.issues[0].message);
const result = await api('/api/mainline');
const position = result.package.order.indexOf(state.sourceLevel);
if (state.mode === 'ghost-king') {
result.package.ghostLayouts[state.level.displayLevel] = Object.fromEntries(['width', 'height', 'characters', 'aoes'].map(field => [field, clone(state.level[field])]));
} else if (position >= 0) result.package.levels[position] = clone(state.level);
return result;
}
manage.onclick = guarded(async () => {
if (state.busy || !state.level || state.mode === 'ghost-king') return;
if (pendingExtra()) applyExtra();
setBusy(true);
try {
const result = await snapshot(); draft = result.package; revision = result.revision; selected = state.sourceLevel;
history = []; modified = initialModified = dirty(); $('mainline-search').value = ''; $('mainline-error').textContent = '';
$('mainline-target').value = state.level.displayLevel; redraw(); dialog.showModal();
} finally { setBusy(false); }
});
$('mainline-apply').onclick = async () => {
if (submitting) return;
if (!window.offlineEditor && !confirm('将写入项目主线顺序、布局和新增关卡配置,并创建备份。现有玩家存档不会自动迁移,请确认发布安排。继续?')) return;
submitting = true; setBusy(true); dialog.querySelectorAll('button,input,select').forEach(element => { element.disabled = true; });
try {
const number = draft.order.indexOf(selected) + 1;
const result = await api('/api/mainline', { package: draft, revision });
modified = false; dialog.close();
await refresh(number, '主线编排已应用,共 ' + draft.order.length + ' 关' + (result.backup ? ';备份:' + result.backup : ',请导出完整数据包交付'));
} catch (error) { $('mainline-error').textContent = error.message; }
finally { submitting = false; setBusy(false); dialog.querySelectorAll('button,input,select').forEach(element => { element.disabled = false; }); if (dialog.open) redraw(); }
};
function download(bundle) {
const url = URL.createObjectURL(new Blob([JSON.stringify(bundle, null, 2)], { type: 'application/json' }));
const link = document.createElement('a'); link.href = url; link.download = '主线关卡数据包.json'; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000);
}
exportButton.onclick = guarded(async () => {
if (state.busy || !state.level) return;
setBusy(true);
try { const result = await snapshot(); download(result.package); message('已导出完整数据包,包含主线顺序、新增关卡和当前布局'); }
finally { setBusy(false); }
});
projectExport.onclick = () => { if (!state.busy && state.level) { exportDialog.returnValue = 'cancel'; exportDialog.showModal(); } };
exportDialog.addEventListener('close', guarded(async () => {
const mode = exportDialog.returnValue;
if (!['changes', 'all'].includes(mode)) return;
if (state.busy || !state.level) return;
setBusy(true); projectExport.disabled = true;
try {
message('正在校验并生成项目文件包…');
const snapshotResult = await snapshot();
const prepared = await api('/api/project-export', snapshotResult);
const result = await ProjectExport.create(prepared, mode);
const url = URL.createObjectURL(new Blob([result.bytes], { type: 'application/zip' }));
const link = document.createElement('a'); link.href = url;
link.download = '关卡项目文件包-' + (mode === 'all' ? '全部-' : '变更-') + new Date().toISOString().replace(/[:.]/g, '-') + '.zip'; link.click();
setTimeout(() => URL.revokeObjectURL(url), 60000);
message('已下载' + (mode === 'all' ? '全部' : '变更') + '项目 JSON 包,共 ' + result.manifest.files.length + ' 个文件;请在浏览器下载记录中查看,覆盖前先备份');
} finally { projectExport.disabled = false; setBusy(false); }
}));
importButton.onclick = () => { if (!state.busy) input.click(); };
input.onchange = guarded(async () => {
const file = input.files[0]; input.value = ''; if (!file || state.busy) return;
if (file.size > 32 * 1024 * 1024) throw new Error('数据包不能超过 32MB');
setBusy(true);
try {
let bundle;
try { bundle = JSON.parse(await file.text()); } catch { throw new Error('数据包不是有效的 JSON'); }
const current = await api('/api/mainline');
if (![1, 2].includes(bundle?.formatVersion) || bundle.rulesVersion !== current.package.rulesVersion || bundle.dataVersion !== current.package.dataVersion) throw new Error('数据包版本不匹配,请使用对应版本的编辑器');
if (!confirm('导入将替换全部关卡工作区和主线顺序,并丢弃当前未保存编辑。' + (window.offlineEditor ? '' : '项目文件会先备份;玩家存档不自动迁移。') + '继续?')) return;
const result = await api('/api/mainline', { package: bundle, revision: current.revision });
await refresh(state.level.displayLevel, '完整关卡数据包已导入' + (result.backup ? ';备份:' + result.backup : '并保存到本机'));
} finally { setBusy(false); }
});
})();