Files
nixingnishang_level-editor/app.js
T

809 lines
52 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.
'use strict';
const $ = id => document.getElementById(id);
const clone = value => JSON.parse(JSON.stringify(value));
const icons = () => window.lucide.createIcons();
const state = { mode: 'mainline', level: null, revision: '', baseline: '', definitions: [], selected: null, selections: [], material: null, materialOrientation: 2,
kind: 'characters', view: 'source', history: [], future: [], result: null, sequence: 0,
zoom: 1, pan: { x: 0, y: 0 }, drag: null, hover: null, busy: false, draft: null };
const images = new Map();
const canvas = $('board'), ctx = canvas.getContext('2d');
let transform = null, validateTimer;
const layoutText = level => JSON.stringify([level.width, level.height, level.characters, level.aoes]);
const dirty = () => state.level && layoutText(state.level) !== state.baseline;
const sameSelection = (a, b) => a?.collection === b?.collection && a?.index === b?.index;
const selections = () => !state.selected ? [] : state.selections?.includes(state.selected) ? state.selections : [state.selected];
function setSelections(items) { state.selections = items; state.selected = items.at(-1) || null; }
// 非法旋转只保存在展示层,不进入保存、草稿和撤销历史。
function cancelRotationPreview() {
if (!state.rotationPreview) return;
state.rotationPreview = null; state.drag = null; render();
}
function cancelCopyPreview() {
if (!state.copyPreview) return;
const original = state.copyPreview.originalSelection;
state.copyPreview = null; state.drag = null; setSelections(original); render();
}
const selectedEntry = () => selections().length === 1 && state.level?.[state.selected.collection]?.[state.selected.index];
const definitionFor = entry => state.definitions.find(item => item.id === entry?.[0]);
const draftKey = () => 'level-editor:' + state.project + ':source:' + state.sourceLevel;
function message(text, error = false) { $('message').textContent = text; $('message').classList.toggle('error', error); }
function setBusy(value) { state.busy = value; document.body.classList.toggle('busy', value); $('save').disabled = value; $('open').disabled = value; }
async function api(url, body) {
if (state.mode === 'ghost-king') {
url = url.replace('/api/levels/', '/api/ghost-levels/');
if (url === '/api/validate') url = '/api/ghost-validate';
}
const adaptBootstrap = data => url === '/api/bootstrap' ? { ...data, mainlineCount: data.levelCount, levelCount: state.mode === 'ghost-king' ? data.ghostCount : data.levelCount } : data;
if (window.offlineEditor) return adaptBootstrap(await window.offlineEditor.api(url, body));
const response = await fetch(url, body === undefined ? {} : { method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Editor-Token': state.token }, body: JSON.stringify(body) });
const data = await response.json();
if (!response.ok) throw new Error(data.error || '请求失败');
return adaptBootstrap(data);
}
function guarded(action) { return (...args) => Promise.resolve().then(() => action(...args)).catch(error => message(error.message, true)); }
$('level-mode').onchange = guarded(async () => {
const previous = state.mode, next = $('level-mode').value;
if (state.busy || ((dirty() || pendingExtra()) && !confirm('当前关卡有未保存修改,是否切换模式?'))) { $('level-mode').value = previous; return; }
state.mode = next; state.sequence++; state.level = null; state.baseline = ''; state.selected = null;
state.levelCount = next === 'ghost-king' ? state.ghostCount : state.mainlineCount;
$('level-total').textContent = '/ ' + state.levelCount; $('level-number').max = state.levelCount;
$('mainline-manage').disabled = next === 'ghost-king';
await openLevel(1);
});
function imageFor(url) {
if (!url) return null;
if (!images.has(url)) {
const image = new Image();
image.onload = draw;
image.onerror = () => { image.failed = true; draw(); };
image.src = url;
images.set(url, image);
}
return images.get(url);
}
function makeThumbnail(definition, parent) {
parent.classList.toggle('has-overlay', Boolean(definition?.overlay));
if (definition?.image) {
const image = document.createElement('img'); image.src = definition.image; image.alt = definition.name;
parent.append(image);
if (definition.overlay) {
const overlay = document.createElement('img'); overlay.src = definition.overlay; overlay.alt = ''; overlay.className = 'entity-overlay';
parent.append(overlay);
}
} else {
const icon = document.createElement('i'); icon.dataset.lucide = 'fence'; icon.className = 'mechanism-symbol'; parent.append(icon);
}
}
function renderLibrary() {
const search = $('search').value.trim().toLowerCase();
const definitions = state.definitions.filter(item => item.collection === state.kind && (item.name.toLowerCase().includes(search) || String(item.id).includes(search)));
$('material-count').textContent = definitions.length + ' 项';
$('materials').replaceChildren();
definitions.forEach(definition => {
const button = document.createElement('button'); button.className = 'material'; button.title = definition.name;
button.classList.toggle('active', state.material?.id === definition.id);
const thumbnail = document.createElement('div'); thumbnail.className = 'thumbnail'; makeThumbnail(definition, thumbnail);
const name = document.createElement('strong'); name.textContent = definition.name;
const id = document.createElement('small'); id.textContent = definition.id;
button.append(thumbnail, name, id);
button.onclick = () => {
if (state.busy) return;
const deselect = state.material?.id === definition.id && state.material.collection === definition.collection;
state.material = deselect ? null : definition; state.materialOrientation = 2;
state.selected = null; state.view = 'source'; state.hover = null;
renderLibrary(); render(); message(deselect ? '已切换为选择模式' : '已选择:' + definition.name);
};
$('materials').append(button);
});
icons();
}
function renderInspector() {
const entry = selectedEntry(), definition = definitionFor(entry);
$('properties').hidden = !entry;
$('selection-empty').hidden = Boolean(entry);
$('selection-empty').querySelector('span').textContent = state.copyPreview ? '待放置副本:' + selections().length + ' 个对象' : selections().length > 1 ? '已选中 ' + selections().length + ' 个对象' : '未选择对象';
document.querySelectorAll('#properties input,#properties select,#properties textarea,#properties button,.board-settings input').forEach(input => { input.disabled = state.view !== 'source'; });
$('selection-kind').textContent = entry ? (state.selected.collection === 'characters' ? '军械' : '机关') : '';
if (!entry || !definition) return;
$('selected-name').textContent = definition.name;
$('selected-id').textContent = '类型 ' + entry[0] + ' · 序号 ' + (state.selected.index + 1);
$('selected-image').replaceChildren(); makeThumbnail(definition, $('selected-image'));
const options = state.definitions.filter(item => item.collection === state.selected.collection);
$('object-type').replaceChildren(...options.map(item => { const option = document.createElement('option'); option.value = item.id; option.textContent = item.name; return option; }));
$('object-type').value = entry[0]; $('col').value = entry[1]; $('row').value = entry[2]; $('orientation').value = entry[3];
const footprint = definition.footprintsByOrientation[entry[3]];
$('footprint').textContent = footprint ? footprint.width + ' × ' + footprint.height : '无效';
const behaviors = { standard: '普通军械', collisionBomb: '碰撞炸弹', automaticExit: '自动离场', countdownBomb: '倒计时炸弹', movingHazard: '移动障碍', sealedUntilCollision: '碰撞唤醒', charmLeader: '牵引', bounceBack: '碰撞折返', fenceBreaker: '破栏', limitedStep: '步数限制', burrowingBlocker: '出入地面', teamLeader: '编队领队', teamMember: '编队成员', fence: '栏杆', cage: '封印锁' };
$('behavior').textContent = behaviors[definition.boardBehavior] || definition.boardBehavior;
$('sprite-facing').textContent = ['fence', 'cage'].includes(definition.boardBehavior)
? '随横竖布局调整' : definition.visual?.spriteRotationMode === 'directional' ? '随方向旋转' : '固定直立';
$('extra').value = JSON.stringify(entry[4] || {}, null, 2);
renderExtraFields(entry, definition);
icons();
}
function render() {
if (!state.level) return;
const level = state.level;
$('title').textContent = '第 ' + level.displayLevel + ' 关';
$('subtitle').textContent = level.width + ' × ' + level.height + ' · ' + level.sourceId;
$('level-number').value = level.displayLevel;
$('dirty').textContent = dirty() ? '未保存' : '已保存'; $('dirty').classList.toggle('modified', dirty());
$('counts').textContent = level.characters.length + ' 军械 / ' + level.aoes.length + ' 机关';
$('source-id').textContent = level.sourceId; $('scene').textContent = state.result?.scene || '-';
$('columns').value = level.width; $('rows').value = level.height;
$('undo').disabled = !state.history.length; $('redo').disabled = !state.future.length;
for (const id of ['rotate', 'duplicate', 'delete']) $(id).disabled = !selectedEntry() || state.view !== 'source';
$('delete').disabled = !selections().length || state.view !== 'source';
$('duplicate').disabled = !selections().length || state.view !== 'source';
$('rotate').disabled = (!selections().length && !state.material) || state.view !== 'source';
$('selection-help').hidden = state.view !== 'source' || (!state.material && selections().length < 2);
$('selection-help').textContent = state.material
? '单击空位放置 · R 顺时针旋转 · E 逆时针旋转\n可连续放置 · 红色表示位置不合法\n右键退出创建(也可按 Esc 或再次点击同一对象图标)'
: state.copyPreview
? (state.copyPreview.valid ? '副本位置合法:单击放置' : '副本位置不合法:请移动到空位') + ' · R / E 旋转 · 右键取消'
: state.rotationPreview
? '位置不合法:可继续 R / E 旋转或拖动红色选区按格吸附;合法后应用,其他操作取消临时调整。'
: 'R 顺时针旋转 · E 逆时针旋转 · 拖动整体移动\nCtrl+C 复制 · Ctrl 单击增减选择 / 拖动框选 · Delete 删除(需确认) · Esc 取消选择';
if (state.rotationPreview || state.copyPreview) $('selection-help').hidden = false;
$('select-tool').classList.toggle('active', !state.material);
document.querySelectorAll('[data-view]').forEach(button => button.classList.toggle('active', button.dataset.view === state.view));
$('view-state').textContent = state.view === 'source' ? (state.material ? '放置 · ' + state.material.name : '源布局') : '局内预览 · 只读';
$('zoom-label').textContent = Math.round(state.zoom * 100) + '%';
$('draft-actions').hidden = !state.draft;
renderInspector(); draw();
}
function draftSave() {
try {
if (dirty()) localStorage.setItem(draftKey(), JSON.stringify({ level: state.level, revision: state.revision, updated: Date.now() }));
else localStorage.removeItem(draftKey());
} catch { message('本地草稿存储失败,请及时保存或导出', true); }
}
function changed(before) {
if (JSON.stringify(before) === JSON.stringify(state.level)) return;
state.history.push(before); if (state.history.length > 80) state.history.shift(); state.future.length = 0;
state.sequence++; state.result = null; draftSave(); render(); scheduleValidation();
}
function mutate(action) {
if (!state.level || state.busy || state.view !== 'source') return;
const before = clone(state.level);
if (pendingExtra()) {
const value = readExtraInput(), problems = window.LevelExtraFields.validate(value);
if (problems.length) throw new Error(problems[0]);
selectedEntry()[4] = value;
}
action(); changed(before);
}
function localIssues(level) {
const occupied = new Set(), issues = [];
for (const collection of ['characters', 'aoes']) for (const [index, entry] of level[collection].entries()) {
const definition = definitionFor(entry), footprint = definition?.footprintsByOrientation[entry[3]];
if (!footprint || !entry.slice(0, 4).every(Number.isSafeInteger)) { issues.push('对象数据无效'); continue; }
for (const [dx, dy] of footprint.cells) {
const col = entry[1] + dx, row = entry[2] + dy, key = col + ',' + row;
if (col < 0 || row < 0 || col >= level.width || row >= level.height) issues.push('对象超出棋盘');
if (collection === 'characters') { if (occupied.has(key)) issues.push('军械占格重叠'); occupied.add(key); }
}
}
return issues;
}
function updateSelected(index, value) {
const entry = selectedEntry(); if (!entry) return;
if (!Number.isSafeInteger(value)) { renderInspector(); throw new Error('请输入整数'); }
mutate(() => { entry[index] = value; });
}
function applyExtra() {
const entry = selectedEntry(); if (!entry) return;
const value = readExtraInput();
const problems = window.LevelExtraFields.validate(value);
if (problems.length) throw new Error(problems[0]);
if (JSON.stringify(value) === JSON.stringify(entry[4] || {})) { if ($('extra-path')) $('extra-path').dataset.dirty = 'false'; return; }
mutate(() => { entry[4] = value; });
}
function pendingExtra() {
const entry = selectedEntry();
return entry && ($('extra').value !== JSON.stringify(entry[4] || {}, null, 2) || $('extra-path')?.dataset.dirty === 'true');
}
async function openLevel(number) {
if (state.busy) return;
if (!Number.isInteger(number) || number < 1 || number > state.levelCount) throw new Error('关卡编号超出范围');
if ((dirty() || pendingExtra()) && !confirm('当前关卡有未保存修改,是否切换?')) { render(); return; }
state.sequence++; clearTimeout(validateTimer); setBusy(true);
try {
const result = await api('/api/levels/' + number);
state.level = result.level; state.sourceLevel = result.sourceLevel; state.revision = result.revision; state.baseline = layoutText(result.level); state.result = result;
state.history = []; state.future = []; state.selected = null; state.material = null; state.drag = null;
state.view = 'source'; state.zoom = 1; state.pan = { x: 0, y: 0 }; state.draft = null;
try { const draft = JSON.parse(localStorage.getItem(draftKey())); if (draft?.level && layoutText(draft.level) !== state.baseline) { draft.level.displayLevel = number; state.draft = draft; } }
catch { message('本地草稿读取失败', true); }
renderLibrary(); render(); showValidation(result); message('已打开第 ' + number + ' 关');
} finally { setBusy(false); }
}
function showValidation(result) {
$('validation-status').textContent = result.issues.length ? result.issues.length + ' 个问题' : '通过';
$('validation-status').className = result.issues.length ? 'error' : 'ok';
$('issues').replaceChildren();
if (!result.issues.length) { $('issues').textContent = '源占格与游戏布局适配通过'; return; }
result.issues.forEach(issue => {
const button = document.createElement('button'); button.className = 'issue'; button.textContent = issue.message;
button.onclick = () => { if (issue.collection && Number.isInteger(issue.entryIndex)) { state.selected = { collection: issue.collection, index: issue.entryIndex }; state.material = null; state.view = 'source'; render(); } };
$('issues').append(button);
});
}
async function validate() {
if (!state.level) return;
const sequence = ++state.sequence, level = clone(state.level);
$('validation-status').textContent = '正在校验';
const result = await api('/api/validate', { level });
if (sequence !== state.sequence) return;
state.result = result; showValidation(result); $('scene').textContent = result.scene || '-'; refreshExtraEffective(); draw();
return result;
}
function scheduleValidation() { clearTimeout(validateTimer); $('validation-status').textContent = '待校验'; validateTimer = setTimeout(guarded(validate), 300); }
async function save() {
if (!state.level || state.busy) return;
if (pendingExtra()) applyExtra();
clearTimeout(validateTimer); state.sequence++; setBusy(true);
try {
const result = await api('/api/levels/' + state.level.displayLevel, { level: state.level, revision: state.revision });
state.revision = result.revision; state.baseline = layoutText(state.level); state.result = result; state.draft = null;
draftSave(); render(); showValidation(result); message('已保存;备份:' + result.backup);
} finally { setBusy(false); }
}
function displayedEntities() {
if (!state.level) return [];
if (state.view === 'preview') {
if (!state.result?.board) return [];
return [...state.result.board.units.map((unit, index) => ({ collection: 'characters', index,
entry: [unit.artifactId, unit.col, unit.row, unit.sourceOrientation, unit.sourceExtra], unit })),
...state.result.board.aoes.map((unit, index) => ({ collection: 'aoes', index,
entry: [unit.mechanismId, unit.col, unit.row, unit.sourceOrientation] }))];
}
const units = new Map((state.result?.board?.units || []).map(unit => [unit.id, unit]));
const layout = state.copyPreview?.candidate || state.rotationPreview?.candidate || state.level;
return ['characters', 'aoes'].flatMap(collection => layout[collection].map((entry, index) => ({ collection, index, entry,
unit: collection === 'characters' ? units.get('u-' + String(index + 1).padStart(6, '0')) : null })));
}
// 绘制和命中共用层级:选中对象置顶,不改变源数据的对象顺序。
function orderedEntities() {
const selected = new Set(selections().map(item => item.collection + ':' + item.index));
return displayedEntities().sort((a, b) => Number(selected.has(a.collection + ':' + a.index)) - Number(selected.has(b.collection + ':' + b.index)));
}
function bombLabel(definition, unit) {
if (definition.boardBehavior === 'collisionBomb') {
const count = unit?.collisionHp ?? definition.behaviorParams?.collisionHp;
return Number.isFinite(count) ? count + '次' : '待校验';
}
if (definition.boardBehavior === 'countdownBomb') {
const duration = unit?.timer?.duration;
return Number.isFinite(duration) ? duration + '秒' : '待校验';
}
return '';
}
function drawBombLabel(definition, unit, col, row, footprint) {
const text = bombLabel(definition, unit);
if (!text) return;
ctx.save();
ctx.translate(col + footprint.width / 2, row + footprint.height / 2 + .23);
// 局内预览会旋转棋盘,数字反向旋转以保持正向可读。
ctx.rotate(-transform.angle);
ctx.font = 'bold 0.24px "Microsoft YaHei",sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
const width = Math.min(.92, Math.max(.56, ctx.measureText(text).width + .12));
ctx.fillStyle = definition.boardBehavior === 'collisionBomb' ? '#8f3027' : '#075f68';
ctx.fillRect(-width / 2, -.17, width, .34);
ctx.fillStyle = '#ffffff'; ctx.fillText(text, 0, 0, width - .1);
ctx.restore();
}
function spriteAngle(definition, direction) {
const footprint = definition.footprintsByOrientation[direction];
// 舞女图像保持直立,横竖占格仍由方向决定;机关的 Canvas 旋转正方向与 Cocos 相反。
if (definition.boardBehavior === 'movingHazard') return 0;
if (definition.collection === 'aoes') return (definition.boardBehavior === 'cage' && footprint.height > footprint.width)
|| (definition.boardBehavior === 'fence' && [2, 4].includes(Number(direction))) ? -90 : 0;
return definition.visual?.spriteRotationMode === 'directional' ? ({ 1: 180, 2: 90, 3: 0, 4: -90 }[direction] + Number(definition.visual?.spriteForwardOffsetDeg || 0)) : 0;
}
function drawEntity(entry, selected = false, ghost = false, invalid = false, unit = null) {
const definition = definitionFor(entry), footprint = definition?.footprintsByOrientation[entry[3]];
if (!footprint) return;
const [id, col, row, direction] = entry;
ctx.save();
if (ghost) ctx.globalAlpha = 0.65;
const mechanism = definition.collection === 'aoes';
ctx.lineWidth = selected ? 0.045 : 0.018;
for (const [dx, dy] of footprint.cells) {
ctx.fillStyle = invalid ? '#fce0de' : selected ? '#cfebea' : mechanism ? '#f2e8d0' : '#e2ede6';
ctx.strokeStyle = invalid ? '#d5544b' : selected ? '#07858c' : mechanism ? '#c4a16c' : '#b8cfc0';
ctx.fillRect(col + dx + .035, row + dy + .035, .93, .93);
ctx.strokeRect(col + dx + .035, row + dy + .035, .93, .93);
}
const lowered = definition.boardBehavior === 'burrowingBlocker' && window.LevelExtraFields.down(entry[4]);
const stateImage = definition.stateImages?.underground || (definition.statePrefabIds?.underground ? '/assets/resources/Ynyk/Props/' + definition.statePrefabIds.underground + '.png' : null);
const image = imageFor(lowered && stateImage ? stateImage : definition.image);
if (image?.complete && image.naturalWidth && !image.failed) {
ctx.save(); ctx.translate(col + footprint.width / 2, row + footprint.height / 2);
if (lowered) ctx.globalAlpha *= 135 / 255;
// 项目图片朝上,和占格配置的朝右基准不同;沿用局内展示层的朝向约定。
const angle = spriteAngle(definition, direction);
ctx.rotate(angle * Math.PI / 180);
const sideways = Math.abs(Math.sin(angle * Math.PI / 180)) > .5;
const width = (sideways ? footprint.height : footprint.width) - .12;
const height = (sideways ? footprint.width : footprint.height) - .12;
const fit = Math.min(width / image.naturalWidth, height / image.naturalHeight);
ctx.drawImage(image, -image.naturalWidth * fit / 2, -image.naturalHeight * fit / 2, image.naturalWidth * fit, image.naturalHeight * fit);
ctx.restore();
} else {
ctx.fillStyle = mechanism ? '#8a6b39' : '#456b5b'; ctx.font = '0.22px "Microsoft YaHei"'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillText(definition.name, col + footprint.width / 2, row + footprint.height / 2, footprint.width - .12);
}
const overlay = imageFor(definition.overlay);
if (overlay?.complete && overlay.naturalWidth && !overlay.failed) {
ctx.save(); ctx.translate(col + footprint.width / 2, row + footprint.height / 2);
ctx.rotate(spriteAngle(definition, direction) * Math.PI / 180);
// 按对象库 52 × 44 缩略图中标记的占比绘制,保持相对箭身的大小一致。
const angle = spriteAngle(definition, direction);
const sideways = Math.abs(Math.sin(angle * Math.PI / 180)) > .5;
const availableWidth = (sideways ? footprint.height : footprint.width) - .12;
const availableHeight = (sideways ? footprint.width : footprint.height) - .12;
const arrowHeight = image?.naturalWidth && image.naturalHeight
? Math.min(availableWidth / image.naturalWidth, availableHeight / image.naturalHeight) * image.naturalHeight
: availableHeight;
const fit = Math.min(arrowHeight * 52 / 44 * .48 / overlay.naturalWidth, arrowHeight * .60 / overlay.naturalHeight);
ctx.drawImage(overlay, -overlay.naturalWidth * fit / 2, -overlay.naturalHeight * fit / 2, overlay.naturalWidth * fit, overlay.naturalHeight * fit);
ctx.restore();
}
ctx.fillStyle = invalid ? '#b84138' : selected ? '#007780' : '#5a7970';
ctx.font = 'bold 0.23px sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
if (definition.boardBehavior !== 'burrowingBlocker') ctx.fillText({ 1: '↓', 2: '→', 3: '↑', 4: '←' }[direction], col + footprint.width - .19, row + .2);
drawBombLabel(definition, unit, col, row, footprint);
if (selected) {
ctx.lineWidth = .045; ctx.strokeStyle = invalid ? '#d5544b' : '#07858c'; ctx.strokeRect(col + .018, row + .018, footprint.width - .036, footprint.height - .036);
}
ctx.restore();
}
function draw() {
const rect = $('viewport').getBoundingClientRect(), dpr = window.devicePixelRatio || 1;
const width = Math.max(1, rect.width), height = Math.max(1, rect.height);
if (canvas.width !== Math.round(width * dpr) || canvas.height !== Math.round(height * dpr)) {
canvas.width = Math.round(width * dpr); canvas.height = Math.round(height * dpr);
}
ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, width, height);
if (!state.level) return;
const preview = state.view === 'preview', board = state.result?.board;
$('canvas-empty').hidden = !preview || Boolean(board);
if (preview && !board) { transform = null; return; }
const columns = preview ? board.geometry.columns : state.level.width;
const rows = preview ? board.geometry.rows : state.level.height;
const angle = preview ? board.geometry.rotationDeg * Math.PI / 180 : 0;
const cosine = Math.cos(angle), sine = Math.sin(angle);
const boundsW = Math.abs(columns * cosine) + Math.abs(rows * sine);
const boundsH = Math.abs(columns * sine) + Math.abs(rows * cosine);
const scale = Math.min((width - 80) / (boundsW + 1), (height - 55) / (boundsH + 1), 65) * state.zoom;
const x = width / 2 + state.pan.x, y = height / 2 + state.pan.y;
transform = { columns, rows, angle, scale, x, y };
ctx.save(); ctx.translate(x, y); ctx.scale(scale, scale); ctx.rotate(angle); ctx.translate(-columns / 2, -rows / 2);
if (preview && state.result.boundary) {
ctx.beginPath();
state.result.boundary.forEach((point, index) => {
const dx = (point.x - board.geometry.center.x) / board.geometry.cellSize;
const dy = (point.y - board.geometry.center.y) / board.geometry.cellSize;
const px = dx * cosine + dy * sine + columns / 2, py = -dx * sine + dy * cosine + rows / 2;
if (index) ctx.lineTo(px, py); else ctx.moveTo(px, py);
});
ctx.closePath(); ctx.strokeStyle = '#9badb7'; ctx.lineWidth = .035; ctx.setLineDash([.1,.1]); ctx.stroke(); ctx.setLineDash([]);
}
const valid = preview ? new Set(board.validCells) : null;
for (let row = 0; row < rows; row++) for (let col = 0; col < columns; col++) {
if (valid && !valid.has(col + ',' + row)) continue;
ctx.fillStyle = (row + col) % 2 ? '#f9fbfa' : '#ffffff'; ctx.fillRect(col, row, 1, 1);
ctx.strokeStyle = '#dce5e4'; ctx.lineWidth = .012; ctx.strokeRect(col, row, 1, 1);
}
ctx.fillStyle = '#8d9ba4'; ctx.font = '0.21px Consolas,monospace'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
for (let col = 0; col < columns; col++) ctx.fillText(col, col + .5, -.38);
for (let row = 0; row < rows; row++) ctx.fillText(row, -.38, row + .5);
const entities = orderedEntities();
const invalidEntries = new Set((state.result?.issues || []).filter(issue => issue.collection).map(issue => issue.collection + ':' + issue.entryIndex));
for (const entity of entities) {
const selected = selections().some(item => sameSelection(item, entity));
if (state.drag?.type === 'object' && selected && !preview && state.drag.moved) continue;
drawEntity(entity.entry, selected, false, Boolean(selected && (state.rotationPreview || state.copyPreview && !state.copyPreview.valid)) || invalidEntries.has(entity.collection + ':' + entity.index), entity.unit);
}
if (!preview && state.drag?.type === 'object' && state.drag.moved) for (const item of state.drag.items) drawEntity(state.drag.candidate[item.collection][item.index], true, true, !state.drag.valid);
if (!preview && state.material && state.hover) {
const entry = [state.material.id, state.hover.col, state.hover.row, state.materialOrientation];
const candidate = clone(state.level); candidate[state.material.collection].push(entry);
drawEntity(entry, false, true, Boolean(localIssues(candidate).length));
}
ctx.restore();
if (state.drag?.type === 'marquee' && state.drag.moved) {
const drag = state.drag, bounds = canvas.getBoundingClientRect();
const left = Math.min(drag.startX, drag.endX) - bounds.left, top = Math.min(drag.startY, drag.endY) - bounds.top;
const w = Math.abs(drag.endX - drag.startX), h = Math.abs(drag.endY - drag.startY);
ctx.save(); ctx.fillStyle = 'rgba(7,133,140,.12)'; ctx.strokeStyle = '#07858c'; ctx.lineWidth = 1;
ctx.setLineDash([5, 3]); ctx.fillRect(left, top, w, h); ctx.strokeRect(left, top, w, h); ctx.restore();
}
}
// 框选在屏幕坐标下求交,保证缩放、平移及旋转预览中的命中与可见框一致。
function marqueeItems(drag) {
const left = Math.min(drag.startX, drag.endX), right = Math.max(drag.startX, drag.endX);
const top = Math.min(drag.startY, drag.endY), bottom = Math.max(drag.startY, drag.endY);
const box = [[left, top], [right, top], [right, bottom], [left, bottom]];
const t = transform, rect = canvas.getBoundingClientRect(), cosine = Math.cos(t.angle), sine = Math.sin(t.angle);
const axes = [[1, 0], [0, 1], [cosine, sine], [-sine, cosine]];
return displayedEntities().filter(({ entry }) => {
const footprint = definitionFor(entry)?.footprintsByOrientation[entry[3]];
return footprint?.cells.some(([dx, dy]) => {
const col = entry[1] + dx, row = entry[2] + dy;
const cell = [[col, row], [col + 1, row], [col + 1, row + 1], [col, row + 1]].map(([x, y]) => {
const gx = x - t.columns / 2, gy = y - t.rows / 2;
return [rect.left + t.x + (gx * cosine - gy * sine) * t.scale,
rect.top + t.y + (gx * sine + gy * cosine) * t.scale];
});
return axes.every(([ax, ay]) => {
const a = cell.map(([x, y]) => x * ax + y * ay), b = box.map(([x, y]) => x * ax + y * ay);
return Math.min(...a) < Math.max(...b) - 1e-7 && Math.min(...b) < Math.max(...a) - 1e-7;
});
});
}).map(({ collection, index }) => ({ collection, index }));
}
function updateMarquee(event) {
const drag = state.drag;
drag.endX = event.clientX; drag.endY = event.clientY;
drag.moved ||= Math.hypot(drag.endX - drag.startX, drag.endY - drag.startY) >= 4;
if (drag.moved) { setSelections(marqueeItems(drag)); render(); }
}
function gridPoint(event) {
if (!transform) return null;
const rect = canvas.getBoundingClientRect(), t = transform;
const dx = (event.clientX - rect.left - t.x) / t.scale, dy = (event.clientY - rect.top - t.y) / t.scale;
return { col: Math.floor(dx * Math.cos(t.angle) + dy * Math.sin(t.angle) + t.columns / 2),
row: Math.floor(-dx * Math.sin(t.angle) + dy * Math.cos(t.angle) + t.rows / 2) };
}
function hit(point) {
const entities = orderedEntities().reverse();
return entities.find(entity => {
const entry = entity.entry, footprint = definitionFor(entry)?.footprintsByOrientation[entry[3]];
return footprint?.cells.some(([dx, dy]) => point.col >= entry[1] + dx && point.col < entry[1] + dx + 1 && point.row >= entry[2] + dy && point.row < entry[2] + dy + 1);
});
}
canvas.addEventListener('pointerdown', guarded(event => {
if (state.busy || !state.level) return;
if (state.material && event.button === 2) {
event.preventDefault();
state.material = null; state.hover = null; state.drag = null;
renderLibrary(); render(); message('已退出创建,切换为选择模式'); return;
}
if (pendingExtra()) applyExtra();
const point = gridPoint(event); if (!point) return;
canvas.focus();
if (state.copyPreview && event.button === 0) {
updateCopyPreview(point);
if (!state.copyPreview.valid) { message('副本无法放置:对象越界或军械重叠,请继续移动', true); return; }
const before = clone(state.level), candidate = state.copyPreview.candidate;
state.copyPreview = null; state.level = candidate; changed(before); render(); message('已放置复制对象,尚未保存'); return;
}
if (state.material && state.view === 'source' && event.button === 0) {
const entry = [state.material.id, point.col, point.row, state.materialOrientation], candidate = clone(state.level);
candidate[state.material.collection].push(entry);
if (localIssues(candidate).length) { message('无法放置:对象越界或军械重叠', true); return; }
mutate(() => { state.level[state.material.collection].push(entry); }); return;
}
const entity = event.button === 0 ? hit(point) : null;
if (!state.material && event.button === 0 && (event.ctrlKey || event.metaKey)) {
state.drag = { type: 'marquee', startX: event.clientX, startY: event.clientY,
endX: event.clientX, endY: event.clientY, moved: false, beforeSelection: selections().slice(),
clicked: entity ? { collection: entity.collection, index: entity.index } : null };
canvas.setPointerCapture(event.pointerId); event.preventDefault(); return;
}
if (entity) {
const item = { collection: entity.collection, index: entity.index }, previous = selections();
const alreadySelected = previous.some(selected => sameSelection(selected, item));
state.material = null;
if (!alreadySelected) setSelections([item]);
// 反选延迟到抬起,保留拖动已选对象及整组移动的能力。
state.drag = { type: 'object', start: point, before: clone(state.rotationPreview?.candidate || state.level), items: selections().slice(),
moved: false, didMove: false, deselectOnClick: alreadySelected && !state.rotationPreview, readOnly: state.view !== 'source' };
render();
} else {
if (!event.ctrlKey && !event.metaKey) setSelections([]);
state.drag = { type: 'pan', x: event.clientX, y: event.clientY, original: { ...state.pan } }; render();
}
canvas.setPointerCapture(event.pointerId);
}));
canvas.addEventListener('pointermove', event => {
const point = gridPoint(event); if (!point) return;
state.hover = point; $('coordinates').textContent = '列 ' + point.col + ' / 行 ' + point.row;
if (state.copyPreview) { updateCopyPreview(point); render(); return; }
const drag = state.drag;
if (drag?.type === 'marquee') {
updateMarquee(event); return;
} else if (drag?.type === 'object') {
if (drag.readOnly) return;
let dx = point.col - drag.start.col, dy = point.row - drag.start.row;
if (state.rotationPreview) {
const anchor = drag.before[drag.items[0].collection][drag.items[0].index];
dx = Math.round(anchor[1] + dx) - anchor[1]; dy = Math.round(anchor[2] + dy) - anchor[2];
}
drag.candidate = clone(drag.before); drag.moved = dx !== 0 || dy !== 0; drag.didMove ||= drag.moved;
for (const item of drag.items) shiftEntry(drag.candidate[item.collection][item.index], dx, dy);
drag.valid = !localIssues(drag.candidate).length;
} else if (drag?.type === 'pan') state.pan = { x: drag.original.x + event.clientX - drag.x, y: drag.original.y + event.clientY - drag.y };
draw();
});
canvas.addEventListener('pointerup', event => {
if (state.drag?.type === 'marquee' && Number.isFinite(event.clientX) && Number.isFinite(event.clientY)) updateMarquee(event);
const drag = state.drag; state.drag = null;
if (canvas.hasPointerCapture(event.pointerId)) canvas.releasePointerCapture(event.pointerId);
if (drag?.type === 'marquee') {
if (!drag.moved && drag.clicked) {
const existed = drag.beforeSelection.some(item => sameSelection(item, drag.clicked));
setSelections(existed ? drag.beforeSelection.filter(item => !sameSelection(item, drag.clicked)) : [...drag.beforeSelection, drag.clicked]);
}
render(); return;
}
if (drag?.type === 'object' && drag.moved) {
if (drag.valid) {
const before = state.rotationPreview ? clone(state.level) : drag.before;
state.rotationPreview = null; state.level = drag.candidate; changed(before);
} else if (state.rotationPreview) {
state.rotationPreview.candidate = drag.candidate; render(); message('位置仍不合法,请继续拖动红色选区', true);
} else message('移动已取消:对象越界或军械重叠', true);
}
if (drag?.type === 'object' && !drag.didMove && drag.deselectOnClick) { setSelections([]); render(); }
draw();
});
function cancelPointerDrag() {
if (state.drag?.type === 'marquee') setSelections(state.drag.beforeSelection);
state.drag = null; render();
}
canvas.addEventListener('pointercancel', cancelPointerDrag);
canvas.addEventListener('lostpointercapture', () => { if (state.drag) cancelPointerDrag(); });
canvas.addEventListener('pointerleave', () => { state.hover = null; draw(); });
canvas.addEventListener('contextmenu', event => event.preventDefault());
canvas.addEventListener('wheel', event => { event.preventDefault(); setZoom(state.zoom * (event.deltaY < 0 ? 1.1 : 1 / 1.1)); }, { passive: false });
// 移动巡逻对象时同步平移其源路径,不改变其他扩展参数。
function shiftEntry(entry, dx, dy) {
entry[1] += dx; entry[2] += dy;
const clips = Array.isArray(entry[4]?.aiClips) ? entry[4].aiClips : [];
for (const clip of clips) for (const action of (Array.isArray(clip?.actions) ? clip.actions : [])) {
if (action.method === 'movePath' && Array.isArray(action.params)) action.params = action.params.map(point => {
const match = /^(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)$/.exec(String(point));
return match ? (Number(match[1]) + dx) + ',' + (Number(match[2]) + dy) : point;
});
}
}
function setZoom(value) { state.zoom = Math.max(.4, Math.min(3, value)); $('zoom-label').textContent = Math.round(state.zoom * 100) + '%'; draw(); }
function rotate(clockwise = true) {
const items = selections();
if (state.busy || state.view !== 'source') return;
const turns = clockwise ? { 1: 4, 4: 3, 3: 2, 2: 1 } : { 1: 2, 2: 3, 3: 4, 4: 1 };
if (state.material) {
state.materialOrientation = turns[state.materialOrientation]; render(); return;
}
if (!items.length) return;
if (pendingExtra()) applyExtra();
const dragged = state.drag?.type === 'object' ? state.drag : null;
const candidate = clone(state.copyPreview?.candidate || (dragged ? (dragged.moved ? dragged.candidate : dragged.before) : state.rotationPreview?.candidate || state.level));
const footprints = items.map(item => {
const entry = candidate[item.collection][item.index], footprint = definitionFor(entry)?.footprintsByOrientation[entry[3]];
if (!footprint?.cells?.length) throw new Error('旋转已取消:对象占格无效');
return { item, entry, footprint };
});
// 多选以全部占格的包围盒中心旋转,格子按中心坐标变换,不取整或移动旋转中心。
const cells = footprints.flatMap(({ entry, footprint }) => footprint.cells.map(([x, y]) => [entry[1] + x, entry[2] + y]));
const cx = (Math.min(...cells.map(cell => cell[0])) + Math.max(...cells.map(cell => cell[0])) + 1) / 2;
const cy = (Math.min(...cells.map(cell => cell[1])) + Math.max(...cells.map(cell => cell[1])) + 1) / 2;
const rotateCell = (x, y) => {
const dx = x + .5 - cx, dy = y + .5 - cy;
const point = clockwise ? [cx - dy - .5, cy + dx - .5] : [cx + dy - .5, cy - dx - .5];
if (!point.every(Number.isFinite)) throw new Error('旋转已取消:旋转坐标无效');
return point;
};
for (const { entry, footprint } of footprints) {
const nextOrientation = turns[entry[3]], nextFootprint = definitionFor(entry)?.footprintsByOrientation[nextOrientation];
if (!nextFootprint?.cells?.length) throw new Error('旋转已取消:目标朝向占格无效');
if (items.length > 1) {
const rotated = footprint.cells.map(([x, y]) => rotateCell(entry[1] + x, entry[2] + y));
entry[1] = Math.min(...rotated.map(cell => cell[0])) - Math.min(...nextFootprint.cells.map(cell => cell[0]));
entry[2] = Math.min(...rotated.map(cell => cell[1])) - Math.min(...nextFootprint.cells.map(cell => cell[1]));
const occupied = new Set(rotated.map(cell => cell.join(',')));
if (occupied.size !== nextFootprint.cells.length || nextFootprint.cells.some(([x, y]) => !occupied.has((entry[1] + x) + ',' + (entry[2] + y)))) throw new Error('旋转已取消:目标朝向占格与旋转结果不一致');
for (const clip of (Array.isArray(entry[4]?.aiClips) ? entry[4].aiClips : [])) for (const action of (Array.isArray(clip?.actions) ? clip.actions : [])) {
if (action.method === 'movePath' && Array.isArray(action.params)) action.params = action.params.map(point => {
const match = /^(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)$/.exec(String(point));
if (!match) throw new Error('旋转已取消:移动路径坐标无效');
return rotateCell(Number(match[1]), Number(match[2])).join(',');
});
}
}
entry[3] = nextOrientation;
}
const problems = localIssues(candidate);
state.drag = null;
if (state.copyPreview) {
Object.assign(state.copyPreview, { base: clone(candidate), candidate, valid: !problems.length,
start: state.copyPreview.point || state.copyPreview.start });
render(); return;
}
if (problems.length) {
state.rotationPreview = { candidate }; render();
message('位置不合法,可继续旋转或拖动红色选区;其他操作将取消临时调整', true); return;
}
state.rotationPreview = null;
mutate(() => { state.level = candidate; });
render(); message('旋转位置合法,已应用;尚未保存的修改请保存');
}
function remove() {
const items = selections();
if (!items.length || state.busy || state.drag || state.view !== 'source') return;
if (items.length > 1 && !confirm('将删除选中的 ' + items.length + ' 个对象,是否继续?')) return;
if (items.length) mutate(() => {
for (const collection of ['characters', 'aoes']) for (const item of items.filter(item => item.collection === collection).sort((a, b) => b.index - a.index)) state.level[collection].splice(item.index, 1);
setSelections([]);
});
}
function duplicate() {
if (state.busy || state.view !== 'source' || state.copyPreview || !selections().length) return;
if (pendingExtra()) applyExtra();
cancelRotationPreview();
const originalSelection = selections().slice(), candidate = clone(state.level), items = [];
for (const item of originalSelection) {
const entry = clone(candidate[item.collection][item.index]);
items.push({ collection: item.collection, index: candidate[item.collection].length });
candidate[item.collection].push(entry);
}
const entries = items.map(item => candidate[item.collection][item.index]);
const start = state.hover ? { ...state.hover } : { col: Math.min(...entries.map(entry => entry[1])), row: Math.min(...entries.map(entry => entry[2])) };
state.copyPreview = { base: clone(candidate), candidate, items, start, originalSelection, valid: !localIssues(candidate).length };
state.drag = null; state.material = null; setSelections(items); render();
message('已复制 ' + items.length + ' 个对象,移动鼠标后单击合法位置放置;右键取消');
}
// 副本仅存在于临时布局,单击合法位置后才一次性写入并生成撤销记录。
function updateCopyPreview(point) {
const preview = state.copyPreview;
if (!preview) return;
const candidate = clone(preview.base), dx = point.col - preview.start.col, dy = point.row - preview.start.row;
for (const item of preview.items) shiftEntry(candidate[item.collection][item.index], dx, dy);
Object.assign(preview, { candidate, point: { ...point }, valid: !localIssues(candidate).length });
}
function history(direction) {
if (state.busy || state.view !== 'source') return;
const source = direction === 'undo' ? state.history : state.future;
const target = direction === 'undo' ? state.future : state.history;
if (!source.length) return;
target.push(clone(state.level)); state.level = source.pop(); state.selected = null; state.drag = null;
state.sequence++; state.result = null; draftSave(); render(); scheduleValidation();
}
$('previous').onclick = guarded(() => openLevel(state.level.displayLevel - 1));
$('next').onclick = guarded(() => openLevel(state.level.displayLevel + 1));
$('open').onclick = guarded(() => openLevel(Number($('level-number').value)));
$('level-number').onkeydown = guarded(event => { if (event.key === 'Enter') return openLevel(Number($('level-number').value)); });
$('save').onclick = guarded(save);
$('validate').onclick = guarded(async () => { if (pendingExtra()) applyExtra(); const result = await validate(); if (result) message(result.issues.length ? '校验发现问题' : '布局校验通过', Boolean(result.issues.length)); });
$('undo').onclick = () => history('undo'); $('redo').onclick = () => history('redo');
$('rotate').onclick = guarded(() => rotate(true)); $('delete').onclick = guarded(remove); $('duplicate').onclick = guarded(duplicate);
$('zoom-in').onclick = () => setZoom(state.zoom * 1.15); $('zoom-out').onclick = () => setZoom(state.zoom / 1.15);
$('fit').onclick = () => { state.pan = { x: 0, y: 0 }; setZoom(1); };
$('select-tool').onclick = () => { state.material = null; renderLibrary(); render(); };
$('search').oninput = renderLibrary;
$('library-tabs').onclick = event => {
const button = event.target.closest('[data-kind]'); if (!button) return;
state.kind = button.dataset.kind;
document.querySelectorAll('[data-kind]').forEach(item => item.classList.toggle('active', item === button)); renderLibrary();
};
$('view-tabs').onclick = guarded(async event => {
const button = event.target.closest('[data-view]'); if (!button || state.busy) return;
if (pendingExtra()) applyExtra();
state.view = button.dataset.view; state.material = null; state.drag = null; state.pan = { x: 0, y: 0 };
renderLibrary(); render();
if (state.view === 'preview' && !state.result) await validate();
});
for (const [id, position] of [['object-type', 0], ['col', 1], ['row', 2], ['orientation', 3]]) {
$(id).onchange = guarded(() => {
const entry = selectedEntry(); if (!entry) return;
const value = Number($(id).value);
if (position === 1 || position === 2) {
if (!Number.isSafeInteger(value)) throw new Error('请输入整数坐标');
mutate(() => shiftEntry(entry, position === 1 ? value - entry[1] : 0, position === 2 ? value - entry[2] : 0));
} else updateSelected(position, value);
});
}
$('properties').onsubmit = event => event.preventDefault();
$('apply-extra').onclick = guarded(applyExtra);
for (const [id, property] of [['columns', 'width'], ['rows', 'height']]) $(id).onchange = guarded(() => {
const value = Number($(id).value);
if (!Number.isInteger(value) || value < 1 || value > 64) { render(); throw new Error('棋盘行列数必须是 1 到 64 的整数'); }
mutate(() => { state.level[property] = value; });
});
$('restore-draft').onclick = guarded(() => {
if (!state.draft || state.busy) return;
const draft = state.draft;
if (draft.level.displayLevel !== state.level.displayLevel || !Array.isArray(draft.level.characters) || !Array.isArray(draft.level.aoes)) throw new Error('草稿格式无效');
const before = clone(state.level);
// 草稿保留原始版本号,磁盘已变化时仍由保存接口拦截覆盖。
state.level = { ...state.level, width: draft.level.width, height: draft.level.height,
characters: draft.level.characters, aoes: draft.level.aoes };
state.revision = draft.revision; state.draft = null; state.view = 'source'; changed(before); message('已恢复本地草稿');
});
$('discard-draft').onclick = () => { if (confirm('删除此关卡的本地草稿?')) { localStorage.removeItem(draftKey()); state.draft = null; render(); } };
$('export').onclick = guarded(() => {
if (!state.level) return;
if (pendingExtra()) applyExtra();
const url = URL.createObjectURL(new Blob([JSON.stringify(state.level, null, 2) + '\n'], { type: 'application/json' }));
const link = document.createElement('a'); link.href = url; link.download = (state.mode === 'ghost-king' ? '逐鹿关卡-' : '主线关卡-') + state.level.displayLevel + '.json'; link.click();
setTimeout(() => URL.revokeObjectURL(url), 1000); message('已导出第 ' + state.level.displayLevel + ' 关');
});
$('import').onclick = () => { if (!state.busy) $('import-file').click(); };
$('import-file').onchange = guarded(async event => {
const file = event.target.files[0]; event.target.value = ''; if (!file || !state.level || state.busy) return;
if (file.size > 2 * 1024 * 1024) throw new Error('导入文件不能超过 2MB');
const number = state.level.displayLevel, revision = state.revision, initialLayout = layoutText(state.level), mode = state.mode;
let imported;
try { imported = JSON.parse(await file.text()); } catch { throw new Error('导入文件不是有效的 JSON'); }
if (state.mode !== mode || state.level.displayLevel !== number || state.revision !== revision || layoutText(state.level) !== initialLayout) throw new Error('关卡已切换或修改,请重新导入');
const candidate = { ...state.level, ...MainlineWorkspace.importLayout(imported) };
const result = await api('/api/validate', { level: candidate });
if (state.mode !== mode || state.level.displayLevel !== number || state.revision !== revision || layoutText(state.level) !== initialLayout) throw new Error('关卡已切换或修改,请重新导入');
if (result.issues.length) throw new Error('导入校验失败:' + result.issues[0].message);
if (!confirm('将导入布局应用到当前第 ' + number + ' 关?')) return;
state.view = 'source'; state.selected = null;
mutate(() => { state.level = candidate; }); message('布局已导入,尚未保存');
});
document.addEventListener('keydown', guarded(event => {
if (state.busy) return;
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') { event.preventDefault(); return save(); }
if (event.target.matches('input,textarea,select')) return;
if ((event.ctrlKey || event.metaKey) && !event.altKey && event.key.toLowerCase() === 'c' && selections().length && state.view === 'source') {
event.preventDefault(); if (!event.repeat) duplicate(); return;
}
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'z') { event.preventDefault(); history(event.shiftKey ? 'redo' : 'undo'); }
if (event.key === 'Delete' || event.key === 'Backspace') { event.preventDefault(); remove(); }
if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.repeat && ['r', 'e'].includes(event.key.toLowerCase())) { event.preventDefault(); rotate(event.key.toLowerCase() === 'r'); }
if (event.key === 'Escape') { state.material = null; state.drag = null; state.selected = null; renderLibrary(); render(); }
}));
// 切换选择或执行工具前提交参数;非法 JSON 留在原处,不静默丢弃。
function commitPendingExtra(event) {
if (event.target === $('extra') || event.target.closest('#extra-fields') || !pendingExtra()) return;
try { applyExtra(); }
catch (error) { event.preventDefault(); event.stopImmediatePropagation(); message(error.message, true); }
}
document.addEventListener('pointerdown', commitPendingExtra, true);
document.addEventListener('click', commitPendingExtra, true);
function discardRotationForOtherAction(event) {
if (!state.rotationPreview) return;
if (event.type === 'keydown' && ['Control', 'Meta', 'Shift', 'Alt'].includes(event.key)) return;
if (event.type === 'keydown' && !event.ctrlKey && !event.metaKey && !event.altKey
&& ['r', 'e'].includes(event.key.toLowerCase()) && !event.target.matches('input,textarea,select')) return;
if (['pointerdown', 'click'].includes(event.type) && event.target.closest?.('#rotate')) return;
if (event.target === canvas) {
if (event.type === 'click') return;
const point = gridPoint(event), entity = point && hit(point);
if (event.type === 'pointerdown' && event.button === 0 && !event.ctrlKey && !event.metaKey && entity && selections().some(item => sameSelection(item, entity))) return;
}
cancelRotationPreview();
}
for (const type of ['pointerdown', 'click', 'change', 'input', 'wheel', 'contextmenu', 'keydown']) document.addEventListener(type, discardRotationForOtherAction, true);
function discardCopyForOtherAction(event) {
if (!state.copyPreview) return;
if (event.type === 'keydown') {
if (['Control', 'Meta', 'Shift', 'Alt'].includes(event.key)) return;
if (!event.target.matches('input,textarea,select') && ((!event.ctrlKey && !event.metaKey && !event.altKey && ['r', 'e'].includes(event.key.toLowerCase()))
|| ((event.ctrlKey || event.metaKey) && !event.altKey && event.key.toLowerCase() === 'c'))) return;
}
if (['pointerdown', 'click'].includes(event.type) && event.target.closest?.('#rotate,#duplicate')) return;
if (event.target === canvas && (event.type === 'click' || event.type === 'pointerdown' && event.button === 0)) return;
cancelCopyPreview();
}
for (const type of ['pointerdown', 'click', 'change', 'input', 'wheel', 'contextmenu', 'keydown']) document.addEventListener(type, discardCopyForOtherAction, true);
window.addEventListener('beforeunload', event => { if (dirty() || pendingExtra()) { event.preventDefault(); event.returnValue = ''; } });
new ResizeObserver(draw).observe($('viewport'));
guarded(async () => {
icons();
const bootstrap = await api('/api/bootstrap'); Object.assign(state, bootstrap);
$('project-path').textContent = bootstrap.project; $('project-path').title = bootstrap.project;
$('level-total').textContent = '/ ' + bootstrap.levelCount; $('level-number').max = bootstrap.levelCount;
await openLevel(Number(new URLSearchParams(location.search).get('level') || 1));
})();