(() => {
'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 = '' + text; return element;
}
const manage = button('mainline-manage', '主线编排', 'list-ordered', '主线编排');
const importButton = button('package-import', '导入完整数据包 JSON', 'folder-input');
const exportButton = button('package-export', '导出完整数据包 JSON(可直接重新导入)', 'folder-output');
const projectExport = button('project-export', '导出项目文件包 ZIP', 'folder-down');
actions.insertBefore(manage, $('dirty'));
actions.insertBefore(importButton, $('import')); actions.insertBefore(exportButton, $('import'));
actions.insertBefore(projectExport, $('validate'));
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 = '
';
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 = '主线编排
' +
'
' +
'' +
'' +
'' +
'
' +
'' +
'
' +
'' +
'' +
'' +
'
' +
'';
document.body.append(dialog); icons();
let draft, revision, selected, history = [], modified = false, initialModified = false, submitting = false;
let importedLayout = null, importedName = '', readingFile = false, generation = 0, validationOrder = [];
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);
if (index >= 0) {
const settings = draft.levels[index].levelSettings || state.settingsCatalog.records[draft.templates[selected]];
$('mainline-config-summary').textContent = '配置模板:第 ' + (index + 1) + ' 关 · 来源 ' + selected + '\n' + levelSettingsSummary(settings);
}
$('mainline-up').disabled = index <= 0; $('mainline-down').disabled = index < 0 || index === draft.order.length - 1;
$('mainline-remove').disabled = index < 0 || draft.order.length <= 1;
const importing = $('mainline-kind').value === 'json';
$('mainline-json-row').hidden = !importing;
$('mainline-json-name').textContent = readingFile ? '正在读取…' : importedName || '未选择文件';
$('mainline-json-template').textContent = index >= 0 ? '配置模板:第 ' + (index + 1) + ' 关 · 来源 ' + selected : '';
$('mainline-json-choose').disabled = readingFile;
$('mainline-add').disabled = $('mainline-insert').disabled = readingFile || (importing && !importedLayout);
$('mainline-undo').disabled = !history.length; $('mainline-apply').disabled = !modified || readingFile;
}
function setSubmitting(value) {
submitting = value;
dialog.querySelectorAll('button,input,select').forEach(element => { element.disabled = value; });
if (!value && dialog.open) redraw();
}
function remember() {
history.push({ draft: clone(draft), selected }); if (history.length > 20) history.shift(); modified = true; $('mainline-error').textContent = '';
}
async 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('请先选择模板关卡');
const id = Math.max(...MainlineWorkspace.sourceOrder(draft)) + 1;
let level = clone(draft.levels[index]);
if (!confirm('新关卡将继承以下配置:\n' + $('mainline-config-summary').textContent + '\n\n是否继续新增?')) return;
if ($('mainline-kind').value === 'json') {
if (readingFile || !importedLayout) throw new Error('请先选择单关 JSON 文件');
level = { ...level, ...clone(importedLayout) };
setSubmitting(true);
try {
// 尚未应用的新增关卡不在校验器中,使用它继承的已保存模板定位场景和规则。
const result = await api('/api/validate', { level: { ...level, displayLevel: validationOrder.indexOf(draft.templates[selected]) + 1 } });
if (result.issues.length) throw new Error('导入布局与所选模板不兼容:' + result.issues[0].message);
} finally { setSubmitting(false); }
}
if ($('mainline-kind').value === 'empty') { level.characters = []; level.aoes = []; }
remember();
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 => async () => { if (submitting) return; try { await 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());
dialog.addEventListener('close', () => { generation++; importedLayout = null; importedName = ''; readingFile = false; });
$('mainline-kind').onchange = redraw;
$('mainline-json-choose').onclick = () => { if (!submitting && !readingFile) $('mainline-json-file').click(); };
$('mainline-json-file').onchange = async event => {
const file = event.target.files[0]; event.target.value = '';
if (!file || submitting || readingFile || !dialog.open) return;
const currentGeneration = generation;
importedLayout = null; importedName = ''; readingFile = true; $('mainline-error').textContent = ''; redraw();
try {
if (file.size > 2 * 1024 * 1024) throw new Error('单关 JSON 文件不能超过 2MB');
let parsed;
try { parsed = JSON.parse(await file.text()); } catch { throw new Error('单关文件不是有效的 JSON'); }
if (currentGeneration !== generation || !dialog.open) return;
importedLayout = MainlineWorkspace.importLayout(parsed); importedName = file.name;
} catch (error) {
if (currentGeneration === generation && dialog.open) $('mainline-error').textContent = error.message;
} finally {
if (currentGeneration === generation && dialog.open) { readingFile = false; redraw(); }
}
};
$('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;
validationOrder = MainlineWorkspace.sourceOrder(draft); generation++; importedLayout = null; importedName = ''; readingFile = false;
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 || readingFile || !modified) return;
if (!window.offlineEditor && !confirm('将写入项目主线顺序、布局和新增关卡配置,并创建备份。现有玩家存档不会自动迁移,请确认发布安排。继续?')) return;
setSubmitting(true); setBusy(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 { setSubmitting(false); setBusy(false); }
};
exportButton.onclick = async () => {
if (state.busy || !state.level) return;
setBusy(true);
const name = '主线关卡数据包.json';
try {
let handle;
// 保存窗口必须在点击事件内打开,不能等异步校验结束后再请求权限。
if (typeof window.showSaveFilePicker === 'function') {
try {
handle = await window.showSaveFilePicker({ id: 'mainline-package', suggestedName: name,
types: [{ description: '关卡数据包 JSON', accept: { 'application/json': ['.json'] } }] });
} catch (error) {
if (error.name === 'AbortError') return;
if (error.name !== 'SecurityError') throw error;
}
}
if (!handle && !window.confirm('当前环境无法打开保存窗口。是否改用浏览器下载?同名文件可能会另存为副本。')) return;
const result = await snapshot();
const blob = new Blob([JSON.stringify(result.package, null, 2)], { type: 'application/json' });
if (handle) {
const stream = await handle.createWritable();
try { await stream.write(blob); await stream.close(); }
catch (error) { await stream.abort().catch(() => {}); throw error; }
message('已保存完整数据包:' + handle.name);
} else {
const url = URL.createObjectURL(blob);
const link = document.createElement('a'); link.href = url; link.download = name; link.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
message('已下载完整数据包 JSON');
}
} catch (error) {
message('导出数据包失败:' + (error.name === 'NotAllowedError' ? '没有文件写入权限' : error.message), true);
} 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); }
});
})();