Files
VibeCoding_ComposeRemote/ComposeRemoteServer/src/main/resources/static/editor.html
T

1817 lines
56 KiB
HTML
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.
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Remote UI 布局编辑器</title>
<style>
:root {
--bg: #0f172a;
--bg-soft: #1e293b;
--line: #334155;
--text: #e2e8f0;
--muted: #94a3b8;
--primary: #3b82f6;
--primary-hover: #2563eb;
--danger: #ef4444;
--card-bg: #e3f2fd;
--title-color: #0d47a1;
--body-color: #212121;
--accent-color: #1565c0;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
height: 100%;
background: var(--bg);
color: var(--text);
font-family: "Segoe UI", "PingFang SC", "Microsoft YaHei", system-ui, sans-serif;
font-size: 13px;
}
body { display: flex; flex-direction: column; overflow: hidden; }
header {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 14px;
background: var(--bg-soft);
border-bottom: 1px solid var(--line);
flex-wrap: nowrap;
overflow: hidden;
}
.brand {
font-size: 14px;
font-weight: 600;
letter-spacing: .3px;
margin-right: 2px;
white-space: nowrap;
}
.toolbar { display: flex; align-items: center; gap: 6px; flex: none; flex-wrap: nowrap; }
.toolbar.right { margin-left: auto; }
.divider { width: 1px; height: 20px; background: var(--line); margin: 0 2px; }
button {
font: inherit;
color: var(--text);
background: #273449;
border: 1px solid var(--line);
border-radius: 8px;
padding: 6px 10px;
cursor: pointer;
transition: background .15s ease, border-color .15s ease, opacity .15s ease;
white-space: nowrap;
}
button:hover { background: #31415c; }
button:disabled { opacity: .35; cursor: not-allowed; }
button.primary { background: var(--primary); border-color: var(--primary); }
button.primary:hover { background: var(--primary-hover); border-color: var(--primary-hover); }
button.danger { color: #fecaca; border-color: #7f1d1d; background: #3f1d1d; }
button.danger:hover { background: #552020; }
button.ghost { background: transparent; }
.page-select {
font: inherit;
color: var(--text);
background: #0b1220;
border: 1px solid var(--line);
border-radius: 8px;
padding: 6px 8px;
max-width: 170px;
outline: none;
}
.page-select:focus { border-color: var(--primary); }
main { flex: 1; display: flex; min-height: 0; }
.stage {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
padding: 18px;
overflow: auto;
}
.stage-head { color: var(--muted); font-size: 12px; text-align: center; line-height: 1.7; }
.canvas-wrap {
border-radius: 26px;
padding: 8px;
background: #020617;
border: 1px solid var(--line);
box-shadow: 0 24px 60px rgba(0, 0, 0, .45);
}
.canvas {
position: relative;
width: 320px;
height: 693px;
overflow: hidden;
border-radius: 20px;
background: #ffffff;
touch-action: none;
user-select: none;
}
.guides {
position: absolute;
inset: 0;
pointer-events: none;
z-index: 0;
background-image:
linear-gradient(to right, rgba(21, 101, 192, .10) 1px, transparent 1px),
linear-gradient(to bottom, rgba(21, 101, 192, .06) 1px, transparent 1px);
background-size: calc(100% / 12) 100%, 100% 5%;
background-position: 0 0;
}
.align-line {
position: absolute;
background: #f59e0b;
z-index: 5;
pointer-events: none;
}
.align-line.v { top: 0; bottom: 0; width: 1px; }
.align-line.h { left: 0; right: 0; height: 1px; }
.item {
position: absolute;
z-index: 1;
overflow: hidden;
border-radius: 6px;
cursor: grab;
outline: 1px dashed rgba(21, 101, 192, .28);
}
.item:hover { outline: 1px dashed rgba(21, 101, 192, .7); }
.item.selected {
outline: 2px solid #1976d2;
box-shadow: 0 0 0 3px rgba(25, 118, 210, .18);
cursor: grabbing;
z-index: 3;
}
.item .handle {
position: absolute;
right: 0;
bottom: 0;
width: 16px;
height: 16px;
cursor: nwse-resize;
background: linear-gradient(135deg, transparent 46%, #1976d2 47%, #1976d2 100%);
border-bottom-right-radius: 5px;
opacity: 0;
z-index: 4;
}
.item.selected .handle { opacity: 1; }
.item .chip {
position: absolute;
top: 2px;
right: 2px;
padding: 1px 5px;
border-radius: 999px;
background: rgba(25, 118, 210, .92);
color: #fff;
font-size: 9px;
line-height: 1.4;
pointer-events: none;
}
.pv-text {
width: 100%;
height: 100%;
overflow: hidden;
color: var(--title-color);
line-height: 1.25;
white-space: pre-wrap;
word-break: break-word;
}
.pv-card {
width: 100%;
height: 100%;
overflow: hidden;
background: var(--card-bg);
color: var(--body-color);
}
.pv-card .pv-title { color: var(--title-color); font-weight: 600; }
.pv-card .pv-hint { color: var(--accent-color); }
.pv-image {
width: 100%;
height: 100%;
background: #cbd5e1 center/cover no-repeat;
display: flex;
align-items: center;
justify-content: center;
color: #475569;
font-size: 11px;
}
aside {
width: 300px;
flex: none;
background: var(--bg-soft);
border-left: 1px solid var(--line);
overflow-y: auto;
padding: 16px;
}
aside h2 {
font-size: 12px;
text-transform: uppercase;
letter-spacing: .12em;
color: var(--muted);
margin: 0 0 10px;
}
.section { margin-bottom: 22px; }
.field { margin-bottom: 10px; }
.field label {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 11px;
}
input, select, textarea {
width: 100%;
font: inherit;
color: var(--text);
background: #0b1220;
border: 1px solid var(--line);
border-radius: 7px;
padding: 6px 8px;
outline: none;
}
input:focus, select:focus, textarea:focus { border-color: var(--primary); }
input[type="color"] { padding: 2px; height: 30px; cursor: pointer; }
textarea { resize: vertical; min-height: 54px; }
.grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
.grid2 .field { margin-bottom: 0; }
.static {
padding: 6px 8px;
border-radius: 7px;
background: #0b1220;
border: 1px dashed var(--line);
color: var(--text);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.layer-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-top: 8px; }
.layer-grid button { padding: 6px 8px; font-size: 12px; }
.empty {
color: var(--muted);
line-height: 1.8;
border: 1px dashed var(--line);
border-radius: 10px;
padding: 16px;
text-align: center;
}
.hint { color: var(--muted); font-size: 11px; line-height: 1.6; margin-top: 4px; }
.dirty-dot {
display: inline-block;
width: 7px;
height: 7px;
border-radius: 50%;
background: #f59e0b;
visibility: hidden;
}
body.dirty .dirty-dot { visibility: visible; }
#toast {
position: fixed;
left: 50%;
bottom: 26px;
transform: translate(-50%, 16px);
background: #0f766e;
color: #f0fdfa;
padding: 10px 18px;
border-radius: 10px;
box-shadow: 0 12px 30px rgba(0, 0, 0, .4);
opacity: 0;
pointer-events: none;
transition: opacity .2s ease, transform .2s ease;
max-width: 80vw;
z-index: 99;
}
#toast.show { opacity: 1; transform: translate(-50%, 0); }
#toast.error { background: #7f1d1d; color: #fee2e2; }
.modal-mask {
position: fixed;
inset: 0;
background: rgba(2, 6, 23, .72);
display: none;
align-items: center;
justify-content: center;
z-index: 90;
}
.modal-mask.show { display: flex; }
.modal {
width: 360px;
max-width: calc(100vw - 32px);
background: var(--bg-soft);
border: 1px solid var(--line);
border-radius: 14px;
padding: 18px;
box-shadow: 0 30px 80px rgba(0, 0, 0, .5);
}
.modal h3 { margin: 0 0 14px; font-size: 15px; }
.modal .actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 16px; }
.modal.wide { width: 460px; }
.state-badge {
display: inline-block;
padding: 3px 8px;
border-radius: 999px;
font-size: 11px;
border: 1px solid var(--line);
color: var(--muted);
background: #0b1220;
white-space: nowrap;
}
.state-badge[data-state="published"] { color: #6ee7b7; border-color: #065f46; background: #052e2b; }
.state-badge[data-state="draft"] { color: #fcd34d; border-color: #854d0e; background: #3b2a08; }
.state-badge[data-state="dirty"] { color: #fca5a5; border-color: #7f1d1d; background: #3f1d1d; }
.history-list { max-height: 56vh; overflow: auto; display: flex; flex-direction: column; gap: 8px; }
.history-row {
display: flex;
align-items: center;
gap: 10px;
padding: 10px;
border: 1px solid var(--line);
border-radius: 10px;
background: #0b1220;
}
.history-row .meta { flex: 1; min-width: 0; }
.history-row .meta strong { display: block; font-size: 13px; font-weight: 600; }
.history-row .meta span { color: var(--muted); font-size: 11px; }
.history-row button { padding: 5px 10px; font-size: 12px; }
.asset-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
max-height: 56vh;
overflow: auto;
}
.asset-card {
border: 1px solid var(--line);
border-radius: 10px;
overflow: hidden;
background: #0b1220;
cursor: pointer;
transition: border-color .15s ease;
}
.asset-card:hover { border-color: var(--primary); }
.asset-card img { width: 100%; height: 76px; object-fit: cover; display: block; background: #111827; }
.asset-card .meta { padding: 6px 8px; }
.asset-card .meta strong { display: block; font-size: 11px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.asset-card .meta span { color: var(--muted); font-size: 10px; }
.asset-card .ops { display: flex; justify-content: flex-end; padding: 0 8px 8px; }
.asset-card .ops button { padding: 3px 8px; font-size: 11px; }
@media (max-width: 1050px) {
.brand { display: none; }
}
@media (max-width: 900px) {
main { flex-direction: column; }
aside { width: auto; border-left: 0; border-top: 1px solid var(--line); max-height: 42vh; }
}
</style>
</head>
<body>
<header>
<div class="brand">Remote UI 布局编辑器</div>
<div class="toolbar">
<select id="page-select" class="page-select" title="切换布局页面"></select>
<span class="dirty-dot" title="有未保存修改"></span>
<span id="publish-state" class="state-badge" data-state="published">已发布</span>
<button id="btn-new-page" title="新建页面">+ 页面</button>
<button id="btn-del-page" class="ghost">删除页面</button>
</div>
<div class="toolbar">
<button id="btn-add-text">+ 文字</button>
<button id="btn-add-card">+ 卡片</button>
<button id="btn-add-image">+ 图片</button>
</div>
<div class="toolbar right">
<button id="btn-undo" title="撤销 (Ctrl+Z)">撤销</button>
<button id="btn-redo" title="重做 (Ctrl+Y)">重做</button>
<span class="divider"></span>
<button id="btn-history" class="ghost" title="版本历史">历史</button>
<button id="btn-reload" class="ghost" title="重新加载">重载</button>
<button id="btn-save" title="保存草稿 (Ctrl+S)">保存草稿</button>
<button id="btn-publish" class="primary" title="发布到线上">发布</button>
</div>
</header>
<main>
<section class="stage" id="stage">
<div class="stage-head">
拖动移动 · 右下角缩放 · 自动吸附网格 / 相邻组件边缘<br>
Ctrl+C 复制、Ctrl+V 粘贴、Ctrl+D 再制、Ctrl+Z 撤销、Delete 删除
</div>
<div class="canvas-wrap" id="canvas-wrap">
<div class="canvas" id="canvas">
<div class="guides" id="guides"></div>
</div>
</div>
<div class="stage-head" id="canvas-meta"></div>
</section>
<aside>
<div class="section">
<h2>画布</h2>
<div class="field">
<label>页面标题</label>
<input id="page-title" maxlength="100">
</div>
<div class="field">
<label>背景颜色</label>
<input id="bg-color" type="color">
</div>
<div class="grid2">
<div class="field"><label>宽高比</label><div class="static" id="aspect">9 : 19.5</div></div>
<div class="field"><label>网格列数</label><div class="static" id="columns">12</div></div>
</div>
<div class="hint">画布比例由布局文档决定,新建页面时选择预设。</div>
</div>
<div class="section">
<h2>组件</h2>
<div id="inspector"></div>
</div>
</aside>
</main>
<div class="modal-mask" id="page-modal">
<div class="modal">
<h3>新建页面</h3>
<div class="field">
<label>页面 id(字母、数字、下划线、短横线)</label>
<input id="new-page-id" placeholder="例如 detail-v2" maxlength="64">
</div>
<div class="field">
<label>页面标题</label>
<input id="new-page-title" placeholder="例如 详情页" maxlength="100">
</div>
<div class="field">
<label>画布预设</label>
<select id="new-page-preset">
<option value="9,19.5">手机 9 : 19.5</option>
<option value="3,4">平板 3 : 4</option>
<option value="16,9">横屏 16 : 9</option>
<option value="1,1">方形 1 : 1</option>
</select>
</div>
<div class="actions">
<button id="btn-modal-cancel" class="ghost">取消</button>
<button id="btn-modal-create" class="primary">创建</button>
</div>
</div>
</div>
<div class="modal-mask" id="history-modal">
<div class="modal wide">
<h3>版本历史</h3>
<div class="history-list" id="history-list"></div>
<div class="actions">
<button id="btn-history-close" class="ghost">关闭</button>
</div>
</div>
</div>
<div class="modal-mask" id="assets-modal">
<div class="modal wide">
<h3>图片资源库</h3>
<div class="asset-grid" id="assets-list"></div>
<div class="actions">
<button id="btn-assets-close" class="ghost">关闭</button>
</div>
</div>
</div>
<input type="file" id="image-file" accept="image/png,image/jpeg,image/gif" hidden>
<div id="toast"></div>
<script>
(() => {
'use strict';
const PM = 1000; // 坐标总长(千分比)
const SNAP_Y = 5; // 纵向吸附步长(千分比)
const ALIGN_THRESHOLD = 6; // 与其它组件对齐的吸附阈值(千分比)
const MIN_ITEM = 10; // 组件最小尺寸(千分比)
const CANVAS_DP = 400; // 编译器里的文档逻辑宽度,用于预估预览字号
const HISTORY_LIMIT = 50;
const PROP_FIELDS = {
TEXT: [
{ key: 'text', label: '文字', type: 'textarea' },
{ key: 'fontSize', label: '字号 (sp)', type: 'number' }
],
CARD: [
{ key: 'title', label: '标题' },
{ key: 'body', label: '正文', type: 'textarea' },
{ key: 'hint', label: '提示(可选)' }
],
IMAGE: [
{ key: 'url', label: '图片 URL' },
{ key: 'pixelWidth', label: '像素宽', type: 'number' },
{ key: 'pixelHeight', label: '像素高', type: 'number' }
]
};
const state = {
pageId: 'desktop',
doc: null,
pages: [],
selectedId: null,
dirty: false,
hasDraft: false,
savedJson: '',
clipboard: null
};
const undoStack = [];
const redoStack = [];
const $ = (id) => document.getElementById(id);
const canvas = $('canvas');
const guides = $('guides');
const inspector = $('inspector');
const stage = $('stage');
init();
async function init() {
state.pageId = new URLSearchParams(location.search).get('id') || 'desktop';
bindToolbar();
bindPageModal();
bindKeys();
bindBeforeUnload();
new ResizeObserver(() => {
fitCanvas();
renderItems();
}).observe(stage);
await refreshPages();
await loadPage(state.pageId);
}
/* ---------------- 页面加载 / 保存 ---------------- */
async function refreshPages() {
try {
const res = await fetch('/api/layouts');
if (!res.ok) throw new Error(await readError(res));
state.pages = await res.json();
renderPageSelect();
} catch (e) {
toast('页面列表加载失败:' + e.message, true);
}
}
function renderPageSelect() {
const select = $('page-select');
select.innerHTML = '';
state.pages.forEach((page) => {
const option = document.createElement('option');
option.value = page.id;
option.textContent = `${page.title}(${page.id}${page.draft ? ' · 草稿' : ''})`;
select.appendChild(option);
});
if (!state.pages.some((page) => page.id === state.pageId)) {
const option = document.createElement('option');
option.value = state.pageId;
option.textContent = state.pageId;
select.appendChild(option);
}
select.value = state.pageId;
$('btn-del-page').disabled = state.pageId === 'desktop';
}
async function loadPage(id) {
try {
const res = await fetch(`/api/layouts/${encodeURIComponent(id)}`);
if (!res.ok) throw new Error(await readError(res));
const data = await res.json();
state.pageId = id;
state.hasDraft = !!data.draft;
delete data.draft;
state.doc = data;
state.doc.canvas = state.doc.canvas || {};
state.selectedId = null;
state.savedJson = snapshot();
state.dirty = false;
undoStack.length = 0;
redoStack.length = 0;
history.replaceState(null, '', `?id=${encodeURIComponent(id)}`);
renderAll();
toast('已加载「' + (state.doc.title || id) + '」');
normalizeImageSizes();
} catch (e) {
toast(e.message, true);
}
}
/** 保存草稿;返回是否成功。silent 用于发布前自动保存,不弹提示。 */
async function save(options) {
if (!state.doc) return false;
const silent = !!(options && options.silent);
try {
const res = await fetch(`/api/layouts/${encodeURIComponent(state.pageId)}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(state.doc)
});
if (!res.ok) throw new Error(await readError(res));
state.doc = await res.json();
state.savedJson = snapshot();
state.hasDraft = true;
state.dirty = false;
updateDirty();
renderAll();
await refreshPages();
if (!silent) toast('已保存草稿,点「发布」后 Android 端生效');
return true;
} catch (e) {
toast('保存失败:' + e.message, true);
return false;
}
}
/** 发布草稿;有未保存改动时先自动保存。 */
async function publish() {
if (!state.doc) return;
if (state.dirty && !(await save({ silent: true }))) return;
if (!confirm('发布后会用当前草稿覆盖线上布局,确定发布吗?')) return;
try {
const res = await fetch(`/api/layouts/${encodeURIComponent(state.pageId)}/publish`, {
method: 'POST'
});
if (!res.ok) throw new Error(await readError(res));
const data = await res.json();
data.canvas = data.canvas || {};
state.doc = data;
state.savedJson = snapshot();
state.hasDraft = false;
state.dirty = false;
renderAll();
await refreshPages();
toast('已发布:Android 端重新进入该页面后生效');
} catch (e) {
toast('发布失败:' + e.message, true);
}
}
/* ---------------- 版本历史 ---------------- */
function closeHistory() {
$('history-modal').classList.remove('show');
}
async function openHistory() {
if (!state.doc) return;
$('history-modal').classList.add('show');
$('history-list').innerHTML = '<div class="empty">加载中…</div>';
try {
const res = await fetch(`/api/layouts/${encodeURIComponent(state.pageId)}/versions`);
if (!res.ok) throw new Error(await readError(res));
renderHistory(await res.json());
} catch (e) {
$('history-list').innerHTML = `<div class="empty">${escapeHtml(e.message)}</div>`;
}
}
function renderHistory(versions) {
const list = $('history-list');
if (!versions.length) {
list.innerHTML = '<div class="empty">还没有历史版本。<br>每次点「发布」都会自动保存一份快照。</div>';
return;
}
list.innerHTML = '';
versions.forEach((version) => {
const row = document.createElement('div');
row.className = 'history-row';
const meta = document.createElement('div');
meta.className = 'meta';
const title = document.createElement('strong');
title.textContent = version.title || '(无标题)';
const detail = document.createElement('span');
detail.textContent = `${version.savedAt} · ${version.items} 个组件 · ${version.version}`;
meta.append(title, detail);
const button = document.createElement('button');
button.textContent = '恢复';
button.onclick = () => restoreVersion(version.version);
row.append(meta, button);
list.appendChild(row);
});
}
async function restoreVersion(version) {
if (!confirm('把该版本恢复成草稿?恢复后需要点「发布」才会影响线上。')) return;
try {
const res = await fetch(
`/api/layouts/${encodeURIComponent(state.pageId)}/versions/${encodeURIComponent(version)}/restore`,
{ method: 'POST' }
);
if (!res.ok) throw new Error(await readError(res));
const data = await res.json();
data.canvas = data.canvas || {};
state.doc = data;
state.selectedId = null;
state.hasDraft = true;
state.savedJson = snapshot();
state.dirty = false;
undoStack.length = 0;
redoStack.length = 0;
closeHistory();
renderAll();
toast('已恢复到草稿,确认无误后点「发布」');
} catch (e) {
toast('恢复失败:' + e.message, true);
}
}
/* ---------------- 图片资源库 ---------------- */
function closeAssets() {
$('assets-modal').classList.remove('show');
}
async function openAssets() {
const item = currentItem();
if (!item || item.type !== 'IMAGE') {
toast('先选中一个图片组件,再从资源库选择图片', true);
return;
}
$('assets-modal').classList.add('show');
await loadAssets();
}
async function loadAssets() {
const grid = $('assets-list');
grid.innerHTML = '<div class="empty" style="grid-column:1/-1">加载中…</div>';
try {
const res = await fetch('/api/remote-ui/assets');
if (!res.ok) throw new Error(await readError(res));
renderAssets(await res.json());
} catch (e) {
grid.innerHTML = `<div class="empty" style="grid-column:1/-1">${escapeHtml(e.message)}</div>`;
}
}
function renderAssets(assets) {
const grid = $('assets-list');
if (!assets.length) {
grid.innerHTML = '<div class="empty" style="grid-column:1/-1">资源库还没有图片,先在图片组件里上传。</div>';
return;
}
grid.innerHTML = '';
assets.forEach((asset) => {
const card = document.createElement('div');
card.className = 'asset-card';
card.title = '点击使用这张图片';
const image = document.createElement('img');
image.src = location.origin + asset.path;
image.alt = asset.name;
image.loading = 'lazy';
const meta = document.createElement('div');
meta.className = 'meta';
const name = document.createElement('strong');
name.textContent = asset.name;
const info = document.createElement('span');
info.textContent = `${asset.pixelWidth}×${asset.pixelHeight} · ${formatSize(asset.size)}`;
meta.append(name, info);
const ops = document.createElement('div');
ops.className = 'ops';
const remove = document.createElement('button');
remove.className = 'danger';
remove.textContent = '删除';
remove.onclick = (event) => {
event.stopPropagation();
deleteAsset(asset);
};
ops.appendChild(remove);
card.append(image, meta, ops);
card.onclick = () => applyAsset(asset);
grid.appendChild(card);
});
}
function applyAsset(asset) {
const item = currentItem();
if (!item || item.type !== 'IMAGE') return;
pushHistory();
item.props = item.props || {};
item.props.url = location.origin + asset.path;
item.props.pixelWidth = String(asset.pixelWidth);
item.props.pixelHeight = String(asset.pixelHeight);
closeAssets();
renderAll();
refreshDirty();
toast(`已使用 ${asset.name}(${asset.pixelWidth}×${asset.pixelHeight})`);
}
async function deleteAsset(asset) {
if (!confirm(`确定删除图片「${asset.name}」吗?`)) return;
try {
const res = await fetch(`/api/remote-ui/assets/${encodeURIComponent(asset.name)}`, { method: 'DELETE' });
if (!res.ok) throw new Error(await readError(res));
toast('图片已删除');
await loadAssets();
} catch (e) {
toast(e.message, true);
}
}
/* ---------------- 图片尺寸校正 ---------------- */
/** 浏览器加载图片拿真实像素尺寸;失败返回 null(保留原值,避免写成 0)。 */
function probeImageSize(url) {
return new Promise((resolve) => {
const image = new Image();
image.onload = () => resolve({ w: image.naturalWidth, h: image.naturalHeight });
image.onerror = () => resolve(null);
image.src = url;
});
}
/** 把组件像素宽高写成真实尺寸,返回是否有变化。 */
function applyImageSize(item, size) {
if (!size || !size.w || !size.h) return false;
const width = String(size.w);
const height = String(size.h);
if (item.props.pixelWidth === width && item.props.pixelHeight === height) return false;
item.props.pixelWidth = width;
item.props.pixelHeight = height;
return true;
}
/** 修改 URL 后自动探测尺寸,避免登记的宽高与图片实际尺寸不一致导致播放端报错。 */
async function syncImageSize(item) {
const doc = state.doc;
const url = ((item.props && item.props.url) || '').trim();
if (!url) return;
const size = await probeImageSize(url);
if (state.doc !== doc || !applyImageSize(item, size)) return;
renderAll();
refreshDirty();
toast(`已校正图片尺寸为 ${size.w}×${size.h}`);
}
/** 载入页面后批量校正图片尺寸:站内资源取资源库数据,外部 URL 用浏览器探测。 */
async function normalizeImageSizes() {
const doc = state.doc;
if (!doc) return;
const images = doc.items.filter((item) => item.type === 'IMAGE' && item.props && item.props.url);
if (!images.length) return;
let assets = [];
try {
const res = await fetch('/api/remote-ui/assets');
if (res.ok) assets = await res.json();
} catch (ignored) {
// 资源库不可用时仍然尝试逐个探测外部图片。
}
let changed = 0;
for (const item of images) {
if (state.doc !== doc) return;
const url = item.props.url.split('?')[0];
const asset = assets.find((candidate) => url.endsWith(candidate.path));
const size = asset
? { w: asset.pixelWidth, h: asset.pixelHeight }
: await probeImageSize(item.props.url);
if (applyImageSize(item, size)) changed += 1;
}
if (state.doc !== doc || !changed) return;
renderAll();
refreshDirty();
toast(`已自动校正 ${changed} 张图片尺寸,请保存并发布`);
}
async function readError(res) {
try {
const body = await res.json();
if (body && body.error) return body.error;
} catch (ignored) { /* 非 JSON 响应 */ }
return `请求失败(HTTP ${res.status})`;
}
function bindToolbar() {
$('btn-add-text').onclick = () => addItem('TEXT');
$('btn-add-card').onclick = () => addItem('CARD');
$('btn-add-image').onclick = () => addItem('IMAGE');
$('btn-save').onclick = () => save();
$('btn-publish').onclick = publish;
$('btn-history').onclick = openHistory;
$('btn-history-close').onclick = closeHistory;
$('history-modal').addEventListener('click', (event) => {
if (event.target === $('history-modal')) closeHistory();
});
$('btn-assets-close').onclick = closeAssets;
$('assets-modal').addEventListener('click', (event) => {
if (event.target === $('assets-modal')) closeAssets();
});
$('btn-undo').onclick = undo;
$('btn-redo').onclick = redo;
$('btn-reload').onclick = () => {
if (!confirmDiscard()) return;
loadPage(state.pageId);
};
$('page-select').onchange = (e) => {
if (!confirmDiscard()) {
e.target.value = state.pageId;
return;
}
loadPage(e.target.value);
};
$('btn-new-page').onclick = openPageModal;
$('btn-del-page').onclick = deletePage;
$('image-file').onchange = (event) => {
uploadImage(event.target.files && event.target.files[0]);
};
$('page-title').onfocus = pushHistory;
$('page-title').oninput = (e) => {
if (!state.doc) return;
state.doc.title = e.target.value;
refreshDirty();
};
$('bg-color').onfocus = pushHistory;
$('bg-color').oninput = (e) => {
if (!state.doc) return;
state.doc.backgroundColor = hexToInt(e.target.value);
canvas.style.backgroundColor = e.target.value;
refreshDirty();
};
}
function confirmDiscard() {
return !state.dirty || confirm('当前页面有未保存的修改,确定放弃吗?');
}
function bindBeforeUnload() {
window.addEventListener('beforeunload', (event) => {
if (!state.dirty) return;
event.preventDefault();
event.returnValue = '';
});
}
/* ---------------- 页面增删 ---------------- */
function openPageModal() {
$('new-page-id').value = '';
$('new-page-title').value = '';
$('new-page-preset').value = '9,19.5';
$('page-modal').classList.add('show');
setTimeout(() => $('new-page-id').focus(), 30);
}
function closePageModal() {
$('page-modal').classList.remove('show');
}
function bindPageModal() {
$('btn-modal-cancel').onclick = closePageModal;
$('btn-modal-create').onclick = createPage;
$('page-modal').addEventListener('click', (event) => {
if (event.target === $('page-modal')) closePageModal();
});
$('new-page-id').addEventListener('keydown', (event) => {
if (event.key === 'Enter') createPage();
});
}
async function createPage() {
if (!confirmDiscard()) return;
const id = $('new-page-id').value.trim();
const title = $('new-page-title').value.trim() || id;
const preset = $('new-page-preset').value.split(',').map(Number);
if (!/^[A-Za-z0-9_-]{1,64}$/.test(id)) {
toast('页面 id 只能包含字母、数字、下划线、短横线', true);
return;
}
if (state.pages.some((page) => page.id === id)) {
toast('页面 id 已存在', true);
return;
}
const document = {
id,
title,
canvas: { aspectWidth: preset[0], aspectHeight: preset[1], columns: 12 },
backgroundColor: -1,
items: [{
id: 'title',
type: 'TEXT',
x: 0, y: 0, w: 1000, h: 80,
props: { text: title, fontSize: '28' },
action: null
}]
};
try {
const res = await fetch(`/api/layouts/${encodeURIComponent(id)}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(document)
});
if (!res.ok) throw new Error(await readError(res));
closePageModal();
await refreshPages();
await loadPage(id);
} catch (e) {
toast(e.message, true);
}
}
async function deletePage() {
if (state.pageId === 'desktop') return;
if (!confirm(`确定删除页面「${state.doc.title || state.pageId}」吗?`)) return;
try {
const res = await fetch(`/api/layouts/${encodeURIComponent(state.pageId)}`, { method: 'DELETE' });
if (!res.ok) throw new Error(await readError(res));
state.dirty = false;
await refreshPages();
await loadPage('desktop');
toast('页面已删除');
} catch (e) {
toast(e.message, true);
}
}
/* ---------------- 渲染 ---------------- */
function renderAll() {
if (!state.doc) return;
renderPageSelect();
$('page-title').value = state.doc.title || '';
$('bg-color').value = intToHex(state.doc.backgroundColor);
canvas.style.backgroundColor = intToHex(state.doc.backgroundColor);
const canvasSpec = state.doc.canvas || {};
$('aspect').textContent = `${canvasSpec.aspectWidth ?? 9} : ${canvasSpec.aspectHeight ?? 19.5}`;
$('columns').textContent = `${canvasSpec.columns ?? 12} 列`;
$('canvas-meta').textContent =
`${state.doc.items.length} 个组件 · 坐标范围 0–${PM}‰ · 预览按画布比例缩放`;
const columns = canvasSpec.columns || 12;
guides.style.backgroundSize = `${100 / columns}% 100%, 100% 5%`;
fitCanvas();
renderItems();
renderInspector();
updateDirty();
updateHistoryButtons();
}
/** 按画布宽高比与可用空间计算显示尺寸,兼容手机 / 平板 / 横屏。 */
function fitCanvas() {
if (!state.doc) return;
const canvasSpec = state.doc.canvas || {};
const aspect = (canvasSpec.aspectWidth || 9) / (canvasSpec.aspectHeight || 19.5);
const availableWidth = Math.max(180, stage.clientWidth - 60);
const availableHeight = Math.max(220, stage.clientHeight - 128);
let width = Math.min(availableWidth, availableHeight * aspect);
let height = width / aspect;
if (height > availableHeight) {
height = availableHeight;
width = height * aspect;
}
canvas.style.width = `${Math.round(width)}px`;
canvas.style.height = `${Math.round(height)}px`;
}
function renderItems() {
if (!state.doc) return;
canvas.querySelectorAll('.item').forEach((node) => node.remove());
state.doc.items.forEach((item) => canvas.appendChild(buildItemNode(item)));
}
function buildItemNode(item) {
const node = document.createElement('div');
node.className = 'item' + (item.id === state.selectedId ? ' selected' : '');
node.dataset.id = item.id;
applyBox(node, item);
node.appendChild(buildPreview(item));
if (item.action) {
const chip = document.createElement('span');
chip.className = 'chip';
chip.textContent = item.action.type === 'OPEN_ACTIVITY' ? '新窗' : '跳转';
node.appendChild(chip);
}
const handle = document.createElement('div');
handle.className = 'handle';
handle.title = '拖动缩放';
handle.addEventListener('pointerdown', (e) => startDrag(e, item, 'resize'));
node.appendChild(handle);
node.addEventListener('pointerdown', (e) => startDrag(e, item, 'move'));
return node;
}
function buildPreview(item) {
const scale = Math.max(canvas.clientWidth, 1) / CANVAS_DP;
const props = item.props || {};
if (item.type === 'TEXT') {
const div = document.createElement('div');
div.className = 'pv-text';
div.style.fontSize = `${num(props.fontSize, 15) * scale}px`;
div.textContent = props.text || '';
return div;
}
if (item.type === 'CARD') {
const box = document.createElement('div');
box.className = 'pv-card';
box.style.padding = `${10 * scale}px`;
const title = document.createElement('div');
title.className = 'pv-title';
title.style.fontSize = `${16 * scale}px`;
title.textContent = props.title || '';
const body = document.createElement('div');
body.style.fontSize = `${13 * scale}px`;
body.style.marginTop = `${4 * scale}px`;
body.textContent = props.body || '';
box.append(title, body);
if (props.hint) {
const hint = document.createElement('div');
hint.className = 'pv-hint';
hint.style.fontSize = `${12 * scale}px`;
hint.style.marginTop = `${4 * scale}px`;
hint.textContent = props.hint;
box.appendChild(hint);
}
return box;
}
const div = document.createElement('div');
div.className = 'pv-image';
if (props.url) {
div.style.backgroundImage = `url("${props.url.replace(/"/g, '%22')}")`;
div.style.color = 'transparent';
} else {
div.textContent = '图片(未设置 URL)';
}
return div;
}
function applyBox(node, item) {
if (!node) return;
node.style.left = pct(item.x);
node.style.top = pct(item.y);
node.style.width = pct(item.w);
node.style.height = pct(item.h);
}
/* ---------------- 选中与属性面板 ---------------- */
function select(id) {
state.selectedId = id;
canvas.querySelectorAll('.item').forEach((node) => {
node.classList.toggle('selected', node.dataset.id === id);
});
renderInspector();
}
function renderInspector() {
const item = currentItem();
if (!item) {
inspector.innerHTML = '<div class="empty">点击画布中的组件进行编辑<br>或从上方新增文字 / 卡片 / 图片</div>';
return;
}
const props = item.props || {};
const propFields = (PROP_FIELDS[item.type] || []).map((field) => {
const long = field.type === 'textarea';
const input = long
? `<textarea data-prop="${field.key}"></textarea>`
: `<input data-prop="${field.key}" ${field.type === 'number' ? 'type="number" step="1"' : ''}>`;
return `<div class="field"><label>${field.label}</label>${input}</div>`;
}).join('');
const uploadBlock = item.type === 'IMAGE'
? `<button data-act="upload-image" style="width:100%;margin-bottom:6px">上传图片</button>
<button data-act="pick-asset" style="width:100%;margin-bottom:6px">从资源库选择</button>
<div class="hint" style="margin-bottom:10px">上传或选择后自动回填 URL 与像素尺寸,文件保存到服务端 assets 目录。</div>`
: '';
inspector.innerHTML = `
<div class="field"><label>类型</label><div class="static">${item.type}</div></div>
<div class="field"><label>组件 id</label><div class="static">${item.id}</div></div>
<div class="grid2" style="margin-bottom:10px">
<div class="field"><label>x</label><input data-box="x" type="number" min="0" max="${PM - 1}"></div>
<div class="field"><label>y</label><input data-box="y" type="number" min="0" max="${PM - 1}"></div>
<div class="field"><label>w</label><input data-box="w" type="number" min="1" max="${PM}"></div>
<div class="field"><label>h</label><input data-box="h" type="number" min="1" max="${PM}"></div>
</div>
<h2>内容</h2>
${uploadBlock}
${propFields}
<h2>点击行为</h2>
<div class="field">
<label>动作</label>
<select data-action="type">
<option value="">无</option>
<option value="NAVIGATE">页面内跳转</option>
<option value="OPEN_ACTIVITY">新 Activity 打开</option>
</select>
</div>
<div class="field">
<label>目标页面</label>
<input data-action="target" placeholder="例如 detail / list">
</div>
<h2>层级</h2>
<div class="layer-grid">
<button data-layer="front">置顶</button>
<button data-layer="up">上移</button>
<button data-layer="down">下移</button>
<button data-layer="back">置底</button>
</div>
<div class="layer-grid">
<button data-act="copy">复制组件</button>
<button data-act="duplicate">再制一份</button>
</div>
<button class="danger" data-act="delete" style="width:100%;margin-top:8px">删除该组件</button>
<div class="hint">提示:图片组件的像素宽高需与真实图片一致,用「上传图片」时会自动填写。</div>
`;
inspector.querySelectorAll('[data-box]').forEach((input) => {
input.value = item[input.dataset.box];
input.onfocus = pushHistory;
input.oninput = () => {
const value = clampInt(input.value, 0, PM);
if (value === null) return;
if (input.dataset.box === 'x') item.x = Math.min(value, PM - item.w);
if (input.dataset.box === 'y') item.y = Math.min(value, PM - item.h);
if (input.dataset.box === 'w') item.w = Math.max(1, Math.min(value, PM - item.x));
if (input.dataset.box === 'h') item.h = Math.max(1, Math.min(value, PM - item.y));
applyBox(itemNode(item.id), item);
refreshDirty();
};
});
inspector.querySelectorAll('[data-prop]').forEach((input) => {
input.value = props[input.dataset.prop] ?? '';
input.onfocus = pushHistory;
input.oninput = () => {
item.props = item.props || {};
item.props[input.dataset.prop] = input.value;
const node = itemNode(item.id);
if (node) {
node.replaceChild(buildPreview(item), node.firstElementChild);
}
refreshDirty();
};
});
const imageUrlInput = inspector.querySelector('[data-prop="url"]');
if (imageUrlInput && item.type === 'IMAGE') {
imageUrlInput.addEventListener('change', () => syncImageSize(item));
}
const actionSelect = inspector.querySelector('[data-action="type"]');
const actionTarget = inspector.querySelector('[data-action="target"]');
actionSelect.value = item.action ? item.action.type : '';
actionTarget.value = item.action ? item.action.target : '';
actionTarget.disabled = !item.action;
actionTarget.onfocus = pushHistory;
actionSelect.onchange = () => {
pushHistory();
if (!actionSelect.value) {
item.action = null;
actionTarget.value = '';
actionTarget.disabled = true;
} else {
item.action = { type: actionSelect.value, target: actionTarget.value.trim() };
actionTarget.disabled = false;
actionTarget.focus();
}
renderItems();
refreshDirty();
};
actionTarget.oninput = () => {
if (!item.action) return;
item.action.target = actionTarget.value.trim();
refreshDirty();
};
inspector.querySelectorAll('[data-layer]').forEach((button) => {
button.onclick = () => moveLayer(item, button.dataset.layer);
});
inspector.querySelector('[data-act="copy"]').onclick = copyItem;
inspector.querySelector('[data-act="duplicate"]').onclick = duplicateItem;
inspector.querySelector('[data-act="delete"]').onclick = deleteSelected;
const uploadButton = inspector.querySelector('[data-act="upload-image"]');
if (uploadButton) {
uploadButton.onclick = () => {
$('image-file').value = '';
$('image-file').click();
};
}
const pickButton = inspector.querySelector('[data-act="pick-asset"]');
if (pickButton) pickButton.onclick = openAssets;
}
function moveLayer(item, direction) {
const items = state.doc.items;
const index = items.findIndex((it) => it.id === item.id);
if (index < 0) return;
let target = index;
if (direction === 'front') target = items.length - 1;
if (direction === 'back') target = 0;
if (direction === 'up') target = Math.min(items.length - 1, index + 1);
if (direction === 'down') target = Math.max(0, index - 1);
if (target === index) return;
pushHistory();
items.splice(index, 1);
items.splice(target, 0, item);
renderItems();
refreshDirty();
}
/* ---------------- 拖拽 / 缩放 / 对齐 ---------------- */
function startDrag(event, item, mode) {
if (event.button !== 0) return;
event.preventDefault();
event.stopPropagation();
select(item.id);
const before = snapshot();
pushHistory();
const historyPushed = undoStack[undoStack.length - 1] === before;
const rect = canvas.getBoundingClientRect();
const start = { x: item.x, y: item.y, w: item.w, h: item.h, px: event.clientX, py: event.clientY };
const columns = (state.doc.canvas && state.doc.canvas.columns) || 12;
const colWidth = PM / columns;
const node = itemNode(item.id);
let moved = false;
const onMove = (ev) => {
const dxPm = ((ev.clientX - start.px) / rect.width) * PM;
const dyPm = ((ev.clientY - start.py) / rect.height) * PM;
if (Math.abs(ev.clientX - start.px) + Math.abs(ev.clientY - start.py) > 2) moved = true;
if (mode === 'move') {
const rawX = start.x + dxPm;
const rawY = start.y + dyPm;
const alignedX = alignSnap(rawX, item.w, 'x', item);
const alignedY = alignSnap(rawY, item.h, 'y', item);
item.x = clamp(alignedX.value === null ? snap(rawX, colWidth) : alignedX.value, 0, PM - item.w);
item.y = clamp(alignedY.value === null ? snap(rawY, SNAP_Y) : alignedY.value, 0, PM - item.h);
drawAlignLines(alignedX.line, alignedY.line);
} else {
const minW = Math.max(MIN_ITEM, colWidth / 2);
item.w = clamp(snap(start.w + dxPm, colWidth), minW, PM - item.x);
item.h = clamp(snap(start.h + dyPm, SNAP_Y), Math.max(MIN_ITEM, SNAP_Y), PM - item.y);
}
applyBox(node, item);
};
const onUp = () => {
window.removeEventListener('pointermove', onMove);
window.removeEventListener('pointerup', onUp);
clearAlignLines();
if (moved) {
refreshDirty();
} else if (historyPushed) {
undoStack.pop();
}
updateHistoryButtons();
renderAll();
};
window.addEventListener('pointermove', onMove);
window.addEventListener('pointerup', onUp);
}
/**
* 拖动时与其它组件 / 画布边缘对齐:返回吸附后的值和对齐线位置。
* 未命中时 value 为 null,调用方退回网格吸附。
*/
function alignSnap(raw, size, axis, moving) {
const candidates = axis === 'x' ? [0, PM / 2, PM] : [0, PM / 2, PM];
state.doc.items.forEach((it) => {
if (it.id === moving.id) return;
if (axis === 'x') {
candidates.push(it.x, it.x + it.w / 2, it.x + it.w);
} else {
candidates.push(it.y, it.y + it.h / 2, it.y + it.h);
}
});
const offsets = [0, size / 2, size];
let best = null;
offsets.forEach((offset) => {
const position = raw + offset;
candidates.forEach((candidate) => {
const diff = candidate - position;
if (Math.abs(diff) <= ALIGN_THRESHOLD && (!best || Math.abs(diff) < Math.abs(best.diff))) {
best = { diff, line: candidate };
}
});
});
return best
? { value: raw + best.diff, line: best.line }
: { value: null, line: null };
}
function drawAlignLines(xLine, yLine) {
clearAlignLines();
if (xLine !== null && xLine !== undefined) {
const line = document.createElement('div');
line.className = 'align-line v';
line.style.left = pct(xLine);
canvas.appendChild(line);
}
if (yLine !== null && yLine !== undefined) {
const line = document.createElement('div');
line.className = 'align-line h';
line.style.top = pct(yLine);
canvas.appendChild(line);
}
}
function clearAlignLines() {
canvas.querySelectorAll('.align-line').forEach((node) => node.remove());
}
/* ---------------- 撤销 / 重做 / 复制 ---------------- */
function snapshot() {
return JSON.stringify(state.doc);
}
function pushHistory() {
if (!state.doc) return;
const current = snapshot();
if (undoStack[undoStack.length - 1] === current) return;
undoStack.push(current);
if (undoStack.length > HISTORY_LIMIT) undoStack.shift();
redoStack.length = 0;
updateHistoryButtons();
}
function undo() {
if (!undoStack.length || !state.doc) return;
redoStack.push(snapshot());
state.doc = JSON.parse(undoStack.pop());
afterHistoryRestore();
}
function redo() {
if (!redoStack.length || !state.doc) return;
undoStack.push(snapshot());
state.doc = JSON.parse(redoStack.pop());
afterHistoryRestore();
}
function afterHistoryRestore() {
if (!state.doc.items.some((item) => item.id === state.selectedId)) {
state.selectedId = null;
}
renderAll();
refreshDirty();
}
function updateHistoryButtons() {
$('btn-undo').disabled = undoStack.length === 0;
$('btn-redo').disabled = redoStack.length === 0;
}
function copyItem() {
const item = currentItem();
if (!item) return;
state.clipboard = JSON.parse(JSON.stringify(item));
toast('已复制组件');
}
function duplicateItem() {
const item = currentItem();
if (!item) return;
pastePayload(JSON.parse(JSON.stringify(item)));
}
function pasteItem() {
if (!state.clipboard) {
toast('剪贴板为空,先按 Ctrl+C 复制组件', true);
return;
}
pastePayload(JSON.parse(JSON.stringify(state.clipboard)));
}
function pastePayload(item) {
if (!state.doc) return;
pushHistory();
item.id = uniqueId(item.type.toLowerCase());
item.x = clamp(item.x + 10, 0, PM - item.w);
item.y = clamp(item.y + 10, 0, PM - item.h);
state.doc.items.push(item);
renderAll();
select(item.id);
refreshDirty();
}
/* ---------------- 新增 / 删除组件 ---------------- */
let sequence = 0;
function addItem(type) {
if (!state.doc) return;
const preset = {
TEXT: { w: 1000, h: 70, props: { text: '新文字', fontSize: '20' } },
CARD: { w: 480, h: 160, props: { title: '新卡片', body: '描述文字' } },
IMAGE: {
w: 1000, h: 240,
props: {
url: 'https://ttstd.com/api/remote-ui/assets/spike-image.png',
pixelWidth: '800', pixelHeight: '450'
}
}
}[type];
if (!preset) return;
pushHistory();
const id = uniqueId(type.toLowerCase());
const y = Math.min(PM - preset.h, maxBottom() + 20);
state.doc.items.push({
id,
type,
x: 0,
y: Math.max(0, y),
w: preset.w,
h: preset.h,
props: { ...preset.props },
action: null
});
renderAll();
select(id);
refreshDirty();
}
function deleteSelected() {
const item = currentItem();
if (!item) return;
pushHistory();
state.doc.items = state.doc.items.filter((it) => it.id !== item.id);
state.selectedId = null;
renderAll();
refreshDirty();
}
/** 上传图片并回填组件的 URL 与像素尺寸;URL 用当前站点地址,播放端可直接下载。 */
async function uploadImage(file) {
if (!file) return;
const item = currentItem();
if (!item || item.type !== 'IMAGE') return;
try {
toast('图片上传中…');
const form = new FormData();
form.append('file', file);
const res = await fetch('/api/remote-ui/assets', { method: 'POST', body: form });
if (!res.ok) throw new Error(await readError(res));
const data = await res.json();
pushHistory();
item.props = item.props || {};
item.props.url = location.origin + data.path;
item.props.pixelWidth = String(data.pixelWidth);
item.props.pixelHeight = String(data.pixelHeight);
renderAll();
refreshDirty();
toast(`已上传 ${data.name}(${data.pixelWidth}×${data.pixelHeight})`);
} catch (e) {
toast('图片上传失败:' + e.message, true);
} finally {
$('image-file').value = '';
}
}
function uniqueId(prefix) {
let id;
do {
sequence += 1;
id = `${prefix}-${Date.now().toString(36).slice(-4)}${sequence}`;
} while (state.doc.items.some((item) => item.id === id));
return id;
}
function maxBottom() {
return state.doc.items.reduce((max, item) => Math.max(max, item.y + item.h), 0);
}
/* ---------------- 快捷键 ---------------- */
function bindKeys() {
window.addEventListener('keydown', (event) => {
const tag = (event.target.tagName || '').toLowerCase();
const inField = tag === 'input' || tag === 'textarea' || tag === 'select';
const mod = event.ctrlKey || event.metaKey;
const key = event.key.toLowerCase();
if (mod && key === 's') {
event.preventDefault();
save();
return;
}
if (inField) return;
if (mod && key === 'z') {
event.preventDefault();
if (event.shiftKey) redo(); else undo();
return;
}
if (mod && key === 'y') {
event.preventDefault();
redo();
return;
}
if (mod && key === 'c') {
event.preventDefault();
copyItem();
return;
}
if (mod && key === 'v') {
event.preventDefault();
pasteItem();
return;
}
if (mod && key === 'd') {
event.preventDefault();
duplicateItem();
return;
}
const item = currentItem();
if (!item) return;
if (event.key === 'Delete' || event.key === 'Backspace') {
event.preventDefault();
deleteSelected();
return;
}
const step = event.shiftKey ? 25 : SNAP_Y;
const delta = {
ArrowLeft: [-step, 0], ArrowRight: [step, 0],
ArrowUp: [0, -step], ArrowDown: [0, step]
}[event.key];
if (!delta) return;
event.preventDefault();
pushHistory();
item.x = clamp(item.x + delta[0], 0, PM - item.w);
item.y = clamp(item.y + delta[1], 0, PM - item.h);
applyBox(itemNode(item.id), item);
renderInspectorNumbers(item);
refreshDirty();
});
}
function renderInspectorNumbers(item) {
inspector.querySelectorAll('[data-box]').forEach((input) => {
input.value = item[input.dataset.box];
});
}
/* ---------------- 工具函数 ---------------- */
function currentItem() {
if (!state.doc || !state.selectedId) return null;
return state.doc.items.find((item) => item.id === state.selectedId) || null;
}
function itemNode(id) {
return canvas.querySelector(`.item[data-id="${cssEscape(id)}"]`);
}
function refreshDirty() {
state.dirty = state.doc ? snapshot() !== state.savedJson : false;
updateDirty();
}
function updateDirty() {
document.body.classList.toggle('dirty', state.dirty);
updatePublishState();
}
/** 顶栏状态徽标:未保存 / 草稿未发布 / 已发布。 */
function updatePublishState() {
const node = $('publish-state');
if (!node) return;
let text = '已发布';
let kind = 'published';
if (state.dirty) {
text = '未保存';
kind = 'dirty';
} else if (state.hasDraft) {
text = '草稿未发布';
kind = 'draft';
}
node.textContent = text;
node.dataset.state = kind;
}
function pct(value) {
return `${value / 10}%`;
}
function clamp(value, min, max) {
return Math.round(Math.min(Math.max(value, min), max));
}
function clampInt(raw, min, max) {
const value = Number.parseInt(raw, 10);
if (Number.isNaN(value)) return null;
return Math.round(Math.min(Math.max(value, min), max));
}
function snap(value, step) {
return Math.round(value / step) * step;
}
function num(raw, fallback) {
const value = Number.parseFloat(raw);
return Number.isFinite(value) ? value : fallback;
}
function intToHex(value) {
const n = (Number(value) >>> 0).toString(16).padStart(8, '0');
return `#${n.slice(-6)}`;
}
function hexToInt(hex) {
const rgb = Number.parseInt(hex.replace('#', ''), 16) || 0;
return (0xff000000 | rgb) | 0;
}
function cssEscape(value) {
return (window.CSS && CSS.escape) ? CSS.escape(value) : value.replace(/["\\]/g, '\\$&');
}
function escapeHtml(value) {
return String(value).replace(/[&<>"']/g, (ch) => ({
'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
}[ch]));
}
function formatSize(bytes) {
if (!Number.isFinite(bytes)) return '';
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
}
let toastTimer = null;
function toast(message, isError = false) {
const node = $('toast');
node.textContent = message;
node.classList.toggle('error', !!isError);
node.classList.add('show');
clearTimeout(toastTimer);
toastTimer = setTimeout(() => node.classList.remove('show'), isError ? 4000 : 2400);
}
})();
</script>
</body>
</html>