1418 lines
60 KiB
HTML
1418 lines
60 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="zh-CN">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
<title>桌面设计稿编辑器 · 设计坐标 → 多设备等比居中</title>
|
||
<style>
|
||
:root{
|
||
--bg:#0f1115; --panel:#171a21; --panel2:#1d212a; --line:#272c36;
|
||
--txt:#e6e9ef; --dim:#8b93a3; --accent:#5b8cff; --ok:#3ecf8e; --warn:#f5a623; --bad:#ff5c5c;
|
||
}
|
||
*{box-sizing:border-box;margin:0;padding:0}
|
||
html,body{height:100%}
|
||
body{background:var(--bg);color:var(--txt);font:13px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;
|
||
overflow:hidden;display:flex}
|
||
button{font:inherit;color:inherit;background:none;border:none;cursor:pointer}
|
||
input,select,textarea{font:inherit;color:inherit}
|
||
|
||
/* ---------- 左栏 ---------- */
|
||
aside.lib{width:212px;flex:none;background:var(--panel);border-right:1px solid var(--line);
|
||
overflow-y:auto;padding:12px}
|
||
.lib h2{font-size:11px;color:var(--dim);letter-spacing:.08em;text-transform:uppercase;
|
||
margin:14px 0 8px;font-weight:600}
|
||
.lib h2:first-child{margin-top:0}
|
||
.chips{display:grid;grid-template-columns:1fr 1fr;gap:6px}
|
||
.chips button{background:var(--panel2);border:1px solid var(--line);border-radius:7px;
|
||
padding:8px 6px;font-size:12px;text-align:center;transition:.15s}
|
||
.chips button:hover{border-color:var(--accent);color:#fff;background:#222939}
|
||
.row{display:flex;align-items:center;justify-content:space-between;gap:8px;
|
||
padding:5px 0;font-size:12px;color:var(--dim)}
|
||
.row b{color:var(--txt);font-weight:600;font-variant-numeric:tabular-nums}
|
||
.row select,.row input[type=number]{background:var(--panel2);border:1px solid var(--line);
|
||
border-radius:6px;padding:4px 6px;color:var(--txt);width:106px}
|
||
.row input[type=number]{width:72px}
|
||
.row input[type=checkbox]{accent-color:var(--accent);width:15px;height:15px}
|
||
.seg{display:flex;background:var(--panel2);border:1px solid var(--line);border-radius:8px;
|
||
padding:2px;gap:2px;margin-top:4px}
|
||
.seg button{flex:1;padding:6px 0;font-size:11px;border-radius:6px;color:var(--dim);transition:.15s}
|
||
.seg button.on{background:var(--accent);color:#fff}
|
||
.seg button:hover:not(.on){color:#fff}
|
||
.formula{font:10.5px/1.7 ui-monospace,Menlo,monospace;color:#8fa6cc;
|
||
background:#12161d;border:1px solid #212836;border-radius:7px;padding:8px 9px;margin-top:6px;
|
||
white-space:pre;overflow-x:auto}
|
||
|
||
/* ---------- 中栏 ---------- */
|
||
main{flex:1;min-width:0;display:flex;flex-direction:column}
|
||
.toolbar{height:50px;flex:none;display:flex;align-items:center;gap:6px;padding:0 12px;
|
||
border-bottom:1px solid var(--line);background:var(--panel);overflow-x:auto}
|
||
.toolbar .title{font-size:13px;font-weight:600;margin-right:auto;white-space:nowrap}
|
||
.toolbar .title span{font-weight:400;color:var(--dim);margin-left:10px;font-size:11px}
|
||
.btn{background:var(--panel2);border:1px solid var(--line);border-radius:7px;
|
||
padding:6px 10px;font-size:12px;transition:.15s;white-space:nowrap}
|
||
.btn:hover:not(:disabled){border-color:#3a4252;background:#232936}
|
||
.btn:disabled{opacity:.35;cursor:not-allowed}
|
||
.btn.primary{background:var(--accent);border-color:var(--accent);color:#fff}
|
||
.btn.primary:hover{filter:brightness(1.08)}
|
||
.pagenav{display:flex;align-items:center;gap:1px;background:var(--panel2);
|
||
border:1px solid var(--line);border-radius:7px;padding:2px}
|
||
.pagenav button{padding:3px 6px;font-size:12px;color:var(--dim);border-radius:5px}
|
||
.pagenav button:hover:not(:disabled){color:#fff;background:#293040}
|
||
.pagenav button:disabled{opacity:.3}
|
||
.pagenav .num{font-size:11px;color:var(--txt);padding:0 3px;font-variant-numeric:tabular-nums}
|
||
|
||
.stage{flex:1;min-height:0;overflow:auto;display:flex;align-items:center;justify-content:center;
|
||
padding:16px;background:
|
||
radial-gradient(circle at 50% 0%,#1c2330 0%,transparent 60%),
|
||
repeating-linear-gradient(45deg,#0f1115 0 10px,#12151b 10px 20px)}
|
||
.canvas-wrap{position:relative}
|
||
.canvas-label{position:absolute;top:-20px;left:0;font-size:11px;color:var(--dim);
|
||
display:flex;gap:8px;align-items:center;white-space:nowrap}
|
||
.canvas-label b{color:var(--accent)}
|
||
|
||
.design{position:relative;background:linear-gradient(160deg,#31507e,#1a2233 60%,#0e1219);
|
||
border-radius:14px;box-shadow:0 18px 50px rgba(0,0,0,.55);
|
||
outline:1px solid #31394a;overflow:hidden;user-select:none;touch-action:none}
|
||
.design .safe{position:absolute;left:0;right:0;pointer-events:none;
|
||
border-top:1px dashed rgba(91,140,255,.35);z-index:50}
|
||
.design .safe span{position:absolute;right:4px;top:2px;font-size:9px;color:rgba(91,140,255,.6)}
|
||
.design .guides{position:absolute;inset:0;pointer-events:none;opacity:0;transition:.2s;z-index:0}
|
||
.design .guides.show{opacity:1}
|
||
.design .guides i{position:absolute;background:rgba(255,255,255,.055)}
|
||
|
||
.el{position:absolute;border-radius:10px;cursor:grab;display:flex;flex-direction:column;
|
||
align-items:center;justify-content:center;overflow:hidden}
|
||
.el:hover{box-shadow:0 0 0 1px rgba(91,140,255,.55)}
|
||
.el.sel{box-shadow:0 0 0 2px var(--accent),0 6px 18px rgba(91,140,255,.28)}
|
||
.el .ic{border-radius:24%;display:flex;align-items:center;justify-content:center;
|
||
font-weight:600;color:#fff;box-shadow:0 3px 8px rgba(0,0,0,.35);flex:none}
|
||
.el .lb{color:rgba(255,255,255,.88);white-space:nowrap;overflow:hidden;
|
||
text-overflow:ellipsis;max-width:100%;text-align:center;flex:none}
|
||
.el .handle{position:absolute;right:-1px;bottom:-1px;width:12px;height:12px;cursor:nwse-resize;
|
||
background:var(--accent);border-radius:3px 0 10px 0;opacity:0;transition:.15s}
|
||
.el.sel .handle{opacity:1}
|
||
.wg{border-radius:14px;background:linear-gradient(150deg,rgba(255,255,255,.15),rgba(255,255,255,.06));
|
||
border:1px solid rgba(255,255,255,.14);padding:10px 12px;
|
||
display:flex;flex-direction:column;justify-content:center;width:100%;height:100%;overflow:hidden}
|
||
.wg .t{color:rgba(255,255,255,.5);letter-spacing:.07em;white-space:nowrap}
|
||
.wg .v{font-weight:300;color:#fff;line-height:1.1;font-variant-numeric:tabular-nums}
|
||
.wg .s{color:rgba(255,255,255,.55);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.dockbg{width:100%;height:100%;background:rgba(255,255,255,.11);
|
||
border:1px solid rgba(255,255,255,.1)}
|
||
|
||
.pagebar{flex:none;height:38px;display:flex;align-items:center;justify-content:center;gap:7px;
|
||
border-top:1px solid var(--line);background:var(--panel)}
|
||
.pagebar i{width:7px;height:7px;border-radius:50%;background:#3a4252;cursor:pointer;transition:.18s}
|
||
.pagebar i.on{background:var(--accent);width:16px;border-radius:4px}
|
||
.pagebar .lbl{font-size:11px;color:var(--dim);margin-right:4px}
|
||
|
||
/* ---------- 右栏 ---------- */
|
||
aside.right{width:396px;flex:none;background:var(--panel);border-left:1px solid var(--line);
|
||
display:flex;flex-direction:column;min-height:0}
|
||
.tabs{display:flex;flex:none;border-bottom:1px solid var(--line)}
|
||
.tabs button{flex:1;padding:11px 4px;font-size:12px;color:var(--dim);border-bottom:2px solid transparent;
|
||
transition:.15s}
|
||
.tabs button.on{color:#fff;border-bottom-color:var(--accent)}
|
||
.tabs button:hover:not(.on){color:#c9d1e0}
|
||
.panes{flex:1;min-height:0;position:relative}
|
||
.pane{position:absolute;inset:0;overflow-y:auto;display:none;padding:12px}
|
||
.pane.on{display:block}
|
||
.pane.nopad{padding:0;display:none;flex-direction:column}
|
||
.pane.nopad.on{display:flex}
|
||
|
||
.dev-head{padding:10px 12px 8px;border-bottom:1px solid var(--line)}
|
||
.dev-head .h{font-size:12px;font-weight:600;margin-bottom:3px}
|
||
.dev-head .d{font-size:11px;color:var(--dim);line-height:1.5}
|
||
.matrix{padding:11px;display:grid;grid-template-columns:1fr 1fr;gap:10px;align-content:start}
|
||
.dcard{background:var(--panel2);border:1px solid var(--line);border-radius:9px;padding:6px;
|
||
display:flex;flex-direction:column;gap:4px}
|
||
.dcard .top{display:flex;justify-content:space-between;align-items:baseline;gap:3px}
|
||
.dcard .name{font-size:10.5px;font-weight:600;white-space:nowrap}
|
||
.dcard .ratio{font-size:9px;color:var(--dim);font-variant-numeric:tabular-nums}
|
||
.phone-mini{position:relative;border-radius:7px;overflow:hidden;margin:0 auto;
|
||
background:#000;box-shadow:0 3px 12px rgba(0,0,0,.5);outline:1px solid #2a3140}
|
||
.phone-mini .wp{position:absolute;inset:0;background:
|
||
radial-gradient(120% 80% at 20% 0%,#3b5a8f 0%,#22304a 45%,#111721 100%)}
|
||
.phone-mini .content{position:absolute;inset:0}
|
||
.phone-mini .gapzone{position:absolute;left:0;right:0;pointer-events:none;
|
||
background:repeating-linear-gradient(45deg,rgba(245,166,35,.22) 0 5px,rgba(245,166,35,.07) 5px 10px);
|
||
border-top:1px dashed rgba(245,166,35,.6);border-bottom:1px dashed rgba(245,166,35,.6)}
|
||
.phone-mini .gapzone.v{background:repeating-linear-gradient(-45deg,rgba(245,166,35,.22) 0 5px,rgba(245,166,35,.07) 5px 10px);
|
||
border:none;border-left:1px dashed rgba(245,166,35,.6);border-right:1px dashed rgba(245,166,35,.6)}
|
||
.phone-mini .contentbox{position:absolute;pointer-events:none;
|
||
outline:1px dashed rgba(91,140,255,.45)}
|
||
.phone-mini .contentbox::before,.phone-mini .contentbox::after{content:'';position:absolute;
|
||
background:rgba(91,140,255,.5)}
|
||
.phone-mini .contentbox::before{left:50%;top:0;bottom:0;width:1px}
|
||
.phone-mini .contentbox::after{top:50%;left:0;right:0;height:1px}
|
||
.dstat{display:grid;grid-template-columns:1fr 1fr;gap:1px 4px;font-size:9px;color:var(--dim)}
|
||
.dstat b{color:var(--txt);font-variant-numeric:tabular-nums}
|
||
.dstat .warn{color:var(--warn)}
|
||
.dstat .ok{color:var(--ok)}
|
||
|
||
/* 属性面板 */
|
||
.field{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:6px 0;
|
||
font-size:12px;color:var(--dim);border-bottom:1px solid rgba(255,255,255,.03)}
|
||
.field:last-child{border-bottom:none}
|
||
.field label{flex:none;width:64px}
|
||
.field input,.field select{background:#12161d;border:1px solid var(--line);border-radius:6px;
|
||
padding:5px 7px;color:var(--txt);width:100%;min-width:0}
|
||
.field input:focus,.field select:focus{outline:none;border-color:var(--accent)}
|
||
.prop-title{display:flex;align-items:center;gap:8px;margin-bottom:10px;
|
||
padding-bottom:9px;border-bottom:1px solid var(--line)}
|
||
.prop-title .pill{font-size:10px;background:#243049;color:#9fb4d8;border-radius:5px;padding:2px 7px}
|
||
.prop-title .id{font-size:10.5px;color:var(--dim);font-family:ui-monospace,Menlo,monospace}
|
||
.empty{color:var(--dim);font-size:12px;text-align:center;padding:34px 0;line-height:1.9}
|
||
.btnrow{display:flex;gap:6px;margin-top:14px}
|
||
.btnrow .btn{flex:1;text-align:center;padding:7px 0}
|
||
.sec{font-size:10.5px;color:var(--dim);letter-spacing:.06em;text-transform:uppercase;
|
||
margin:15px 0 5px;font-weight:600}
|
||
.sec:first-child{margin-top:0}
|
||
|
||
/* 校验 */
|
||
.issue{display:flex;gap:8px;padding:8px 9px;border-radius:8px;margin-bottom:6px;
|
||
font-size:11.5px;line-height:1.5;background:var(--panel2);border:1px solid var(--line)}
|
||
.issue .tag{flex:none;font-size:9px;font-weight:600;border-radius:4px;padding:2px 5px;height:15px}
|
||
.issue.err{border-left:3px solid #ff5c5c}
|
||
.issue.err .tag{background:rgba(255,92,92,.16);color:#ff8a8a}
|
||
.issue.warn{border-left:3px solid #f5a623}
|
||
.issue.warn .tag{background:rgba(245,166,35,.16);color:#ffc766}
|
||
.issue .who{color:var(--dim);font-size:10px;font-family:ui-monospace,Menlo,monospace;margin-top:2px}
|
||
.okbox{text-align:center;padding:36px 0;color:#3ecf8e;font-size:13px}
|
||
.okbox .sub{color:var(--dim);font-size:11.5px;margin-top:6px}
|
||
|
||
pre.json{font:11px/1.55 ui-monospace,Menlo,monospace;color:#9fb4d8;
|
||
white-space:pre;padding:10px 12px;margin:0;flex:1;overflow:auto}
|
||
.jsonbar{display:flex;gap:6px;padding:8px 12px;border-bottom:1px solid var(--line);flex:none}
|
||
|
||
.toast{position:fixed;left:50%;bottom:26px;transform:translate(-50%,14px);background:#232c3d;
|
||
border:1px solid #3a4459;color:#fff;padding:8px 16px;border-radius:8px;font-size:12px;
|
||
opacity:0;pointer-events:none;transition:.22s;z-index:99;max-width:70vw;text-align:center}
|
||
.toast.on{opacity:1;transform:translate(-50%,0)}
|
||
::-webkit-scrollbar{width:8px;height:8px}
|
||
::-webkit-scrollbar-thumb{background:#2c333f;border-radius:4px}
|
||
</style>
|
||
<style>
|
||
.release-dialog {width:min(620px, calc(100vw - 32px)); max-height:85vh; overflow:auto; color:var(--text,#eceff7);
|
||
background:#171d29; border:1px solid #394255; border-radius:16px; padding:24px;}
|
||
.release-dialog::backdrop {background:#080b12aa;}
|
||
.release-dialog h2 {margin:0 0 16px;font-size:20px}
|
||
.release-dialog input {display:block;width:100%;margin:6px 0 12px;padding:9px;background:#101622;color:inherit;
|
||
border:1px solid #394255;border-radius:6px;box-sizing:border-box}
|
||
.release-actions,.release-row {display:flex;gap:8px;align-items:center;flex-wrap:wrap;}
|
||
.release-row {padding:9px 0;border-top:1px solid #30394b;}
|
||
.release-row > span {flex:1;min-width:160px;}
|
||
.release-dialog output {display:block;white-space:pre-wrap;margin:12px 0;overflow-wrap:anywhere;}
|
||
[hidden] {display:none !important;}
|
||
.release-dialog ol {margin:0;padding:0;list-style:none}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
|
||
<aside class="lib">
|
||
<h2>添加内容</h2>
|
||
<div class="chips" id="lib"></div>
|
||
|
||
<h2>设计稿</h2>
|
||
<div class="row">基准尺寸
|
||
<select id="designSize">
|
||
<option value="1080x1920">1080 × 1920</option>
|
||
<option value="1080x2160">1080 × 2160</option>
|
||
<option value="1080x2340">1080 × 2340</option>
|
||
<option value="1080x2400">1080 × 2400</option>
|
||
</select>
|
||
</div>
|
||
<div class="row">safeTop <input type="number" id="safeTop" value="72" step="4"></div>
|
||
<div class="row">safeBottom <input type="number" id="safeBottom" value="72" step="4"></div>
|
||
<div class="row">吸附 12px <input type="checkbox" id="snap" checked></div>
|
||
<div class="row">参考线 <input type="checkbox" id="showGuides" checked></div>
|
||
|
||
<h2>本页背景</h2>
|
||
<div class="row">模式
|
||
<select id="backgroundType">
|
||
<option value="wallpaper">系统壁纸</option>
|
||
<option value="solid">纯色</option>
|
||
<option value="gradient">渐变</option>
|
||
</select>
|
||
</div>
|
||
<div class="row" id="backgroundStartRow" hidden>颜色 <input type="color" id="backgroundStart"></div>
|
||
<div class="row" id="backgroundEndRow" hidden>渐变终点 <input type="color" id="backgroundEnd"></div>
|
||
|
||
<h2>映射策略</h2>
|
||
<div class="seg" id="fitSeg">
|
||
<button data-fit="contain" class="on">等比居中</button>
|
||
<button data-fit="elastic">弹性行距</button>
|
||
<button data-fit="stretch">拉伸</button>
|
||
</div>
|
||
<div class="row" style="margin-top:6px">留白位置
|
||
<select id="anchor">
|
||
<option value="0.42">偏上 0.42</option>
|
||
<option value="0.5" selected>居中 0.5</option>
|
||
<option value="0">贴顶 0</option>
|
||
</select>
|
||
</div>
|
||
|
||
<h2>映射公式</h2>
|
||
<div class="formula">s = min(W/Dw, H/Dh)
|
||
ox = (W − Dw·s) / 2
|
||
oy = (H − Dh·s) · anchor</div>
|
||
<div style="font-size:11px;color:var(--dim);line-height:1.65;margin-top:6px">
|
||
取 min 保证完整装下,再减半保证居中。<br>
|
||
屏更高 → 上下留白;屏更宽 → 左右留白。
|
||
</div>
|
||
</aside>
|
||
|
||
<main>
|
||
<div class="toolbar">
|
||
<div class="title">桌面设计稿<span>坐标即设计稿像素 · 手机端只读渲染</span></div>
|
||
<div class="pagenav">
|
||
<button id="prevPage">‹</button>
|
||
<span class="num" id="pageNum">1 / 1</span>
|
||
<button id="nextPage">›</button>
|
||
<button id="addPage" title="新增页">+</button>
|
||
<button id="delPage" title="删除本页">-</button>
|
||
</div>
|
||
<button class="btn" id="undo">撤销</button>
|
||
<button class="btn" id="redo">重做</button>
|
||
<button class="btn" id="align">对齐栅格</button>
|
||
<button class="btn" id="delEl">删除</button>
|
||
<button class="btn" id="validate">校验</button>
|
||
<button class="btn" id="importBtn">导入</button>
|
||
<button class="btn" id="exportBtn">导出</button>
|
||
<button class="btn" id="openRelease" hidden>布局发布</button>
|
||
<button class="btn primary" id="copy">复制 JSON</button>
|
||
</div>
|
||
|
||
<div class="stage" id="stage">
|
||
<div class="canvas-wrap">
|
||
<div class="canvas-label">
|
||
设计稿 <b id="dSizeTxt">1080 × 1920</b>
|
||
<span style="color:#3a4252">|</span>
|
||
<span>蓝色虚线 = 安全区 · 双击空白新增图标</span>
|
||
</div>
|
||
<div class="design" id="design">
|
||
<div class="guides" id="guides"></div>
|
||
<div class="safe" id="safeT"><span>safeTop</span></div>
|
||
<div class="safe" id="safeB"><span>safeBottom</span></div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="pagebar" id="pagebar"><span class="lbl">页面</span></div>
|
||
</main>
|
||
|
||
<aside class="right">
|
||
<div class="tabs" id="tabs">
|
||
<button data-pane="preview" class="on">设备预览</button>
|
||
<button data-pane="props">属性</button>
|
||
<button data-pane="rules">校验</button>
|
||
<button data-pane="json">JSON</button>
|
||
</div>
|
||
<div class="panes">
|
||
<div class="pane on nopad" id="pane-preview">
|
||
<div class="dev-head">
|
||
<div class="h">同一份数据 · 六台设备</div>
|
||
<div class="d" id="devSummary">—</div>
|
||
</div>
|
||
<div class="matrix" id="matrix"></div>
|
||
</div>
|
||
<div class="pane" id="pane-props"><div id="propBody"></div></div>
|
||
<div class="pane" id="pane-rules"><div id="ruleBody"></div></div>
|
||
<div class="pane nopad" id="pane-json">
|
||
<div class="jsonbar">
|
||
<button class="btn" id="copy2">复制</button>
|
||
<button class="btn" id="download">下载 .json</button>
|
||
<button class="btn" id="resetDemo">重置示例</button>
|
||
</div>
|
||
<pre class="json" id="jsonOut"></pre>
|
||
</div>
|
||
</div>
|
||
</aside>
|
||
|
||
<dialog class="release-dialog" id="releaseDialog" aria-labelledby="releaseTitle">
|
||
<h2 id="releaseTitle">布局发布</h2>
|
||
<label for="adminToken">管理员令牌</label>
|
||
<input id="adminToken" type="password" autocomplete="off" spellcheck="false">
|
||
<div class="release-actions">
|
||
<button class="btn" id="loadOnline">读取线上布局</button>
|
||
<button class="btn primary" id="publishLayout" disabled>发布当前画布</button>
|
||
<button class="btn" id="closeRelease">返回编辑</button>
|
||
</div>
|
||
<output id="releaseStatus" aria-live="polite"></output>
|
||
<ol id="releaseHistory" aria-label="发布历史"></ol>
|
||
<button class="btn" id="moreHistory" hidden>更多版本</button>
|
||
</dialog>
|
||
<input type="file" id="fileInput" accept=".json,application/json" style="display:none">
|
||
<div class="toast" id="toast"></div>
|
||
|
||
<script>
|
||
/* =============================================================================
|
||
* 1. 模型:设计稿坐标,与设备完全无关
|
||
* ===========================================================================*/
|
||
const LIB = [
|
||
{ type:'app_icon', label:'图标', w:132, h:168, payload:{ package:'com.tencent.mm', label:'微信' } },
|
||
{ type:'app_icon', label:'相机', w:132, h:168, payload:{ package:'com.android.camera2', label:'相机' } },
|
||
{ type:'widget', label:'时钟组件', w:864, h:320, payload:{ provider:'com.android.deskclock/com.android.alarmclock.DigitalAppWidgetProvider', label:'时钟' } },
|
||
{ type:'widget', label:'搜索组件', w:420, h:300, payload:{ provider:'com.android.quicksearchbox/com.android.quicksearchbox.SearchWidgetProvider', label:'搜索' } },
|
||
{ type:'widget', label:'音乐组件', w:420, h:300, payload:{ provider:'com.tencent.qqmusic/com.tencent.qqmusiccommon.WidgetProviderSmall', label:'音乐' } },
|
||
{ type:'shortcut', label:'快捷方式', w:132, h:168, payload:{ label:'扫一扫', intent:'weixin://scanqrcode' } },
|
||
{ type:'dock_bg', label:'Dock 底板', w:936, h:200, payload:{ radius:56 } },
|
||
];
|
||
|
||
const DEVICES = [
|
||
{ name:'16 : 9', w:1080, h:1920 },
|
||
{ name:'18 : 9', w:1080, h:2160 },
|
||
{ name:'19.5 : 9', w:1080, h:2340 },
|
||
{ name:'2K 20:9', w:1440, h:3200 },
|
||
{ name:'16:10', w:1440, h:2304 },
|
||
{ name:'平板 4:3', w:1536, h:2048 },
|
||
];
|
||
|
||
let state = newState();
|
||
const draftKey = 'vibe-launcher-offline-draft-v3';
|
||
let savedDraft = JSON.stringify(state);
|
||
function confirmDraftReplacement() {
|
||
return JSON.stringify(state) === savedDraft || window.confirm('当前画布有改动。确定替换?');
|
||
}
|
||
let activePage = 0;
|
||
let selectedId = null;
|
||
let uidCounter = 100;
|
||
|
||
function newState() {
|
||
return {
|
||
schemaVersion: 3,
|
||
revision: 1,
|
||
canvas: { designWidth:1080, designHeight:1920, safeTop:72, safeBottom:72 },
|
||
fit: { mode:'contain', anchorY:0.5 },
|
||
pages: [{ index:0, background:{ type:'wallpaper' }, items: demoItems() }],
|
||
};
|
||
}
|
||
|
||
function demoItems() {
|
||
const pad = 108, colW = 216, icon = 132, ih = 168;
|
||
const colX = c => pad + c * colW + (colW - icon) / 2;
|
||
const out = [];
|
||
out.push({ id:'w_clock', type:'widget', x:pad, y:196, w:864, h:320, z:1,
|
||
payload:{ provider:'com.android.deskclock/com.android.alarmclock.DigitalAppWidgetProvider', label:'时钟' } });
|
||
|
||
[['微信','com.tencent.mm'],['相机','com.android.camera2'],['相册','com.android.gallery3d'],['设置','com.android.settings'],['浏览器','com.android.chrome'],['QQ音乐','com.tencent.qqmusic'],['电话','com.android.dialer'],['日历','com.android.calendar']].forEach(([label, pkg], i) => {
|
||
const c = i % 4, r = Math.floor(i / 4);
|
||
out.push({ id:'i'+i, type:'app_icon', x:colX(c), y:604 + r*224, w:icon, h:ih, z:2,
|
||
payload:{ package:pkg, label } });
|
||
});
|
||
|
||
out.push({ id:'w_weather', type:'widget', x:pad, y:1076, w:420, h:300, z:1,
|
||
payload:{ provider:'com.android.quicksearchbox/com.android.quicksearchbox.SearchWidgetProvider', label:'搜索' } });
|
||
out.push({ id:'w_music', type:'widget', x:552, y:1076, w:420, h:300, z:1,
|
||
payload:{ provider:'com.tencent.qqmusic/com.tencent.qqmusiccommon.WidgetProviderSmall', label:'音乐' } });
|
||
|
||
[['联系人','com.android.contacts'],['短信','com.android.messaging'],['文件','com.android.documentsui'],['QQ','com.tencent.mobileqq']].forEach(([label, pkg], i) => {
|
||
out.push({ id:'s'+i, type:'app_icon', x:colX(i), y:1650, w:icon, h:ih, z:2,
|
||
payload:{ package:pkg, label } });
|
||
});
|
||
return out;
|
||
}
|
||
|
||
const $ = id => document.getElementById(id);
|
||
const cur = () => state.pages[activePage];
|
||
|
||
/* =============================================================================
|
||
* 2. 映射:设计稿 → 设备像素(两套策略的唯一差异在这里)
|
||
* ===========================================================================*/
|
||
function rowBands(items) {
|
||
const spans = items.map(i => [i.y, i.y + i.h]).sort((a, b) => a[0] - b[0]);
|
||
const bands = [];
|
||
for (const [a, b] of spans) {
|
||
const last = bands[bands.length - 1];
|
||
if (last && a < last[1] - 0.5) last[1] = Math.max(last[1], b);
|
||
else bands.push([a, b]);
|
||
}
|
||
return bands;
|
||
}
|
||
|
||
function buildMapper(dev, items, fit, anchor) {
|
||
const d = state.canvas;
|
||
const sxW = dev.w / d.designWidth;
|
||
const syH = dev.h / d.designHeight;
|
||
const contain = () => {
|
||
const s = Math.min(sxW, syH);
|
||
const cw = d.designWidth * s, ch = d.designHeight * s;
|
||
return { sx:s, sy:s, ox:(dev.w - cw)/2, oy:(dev.h - ch)*anchor, elastic:null };
|
||
};
|
||
|
||
if (fit === 'stretch') return { sx:sxW, sy:syH, ox:0, oy:0, elastic:null };
|
||
if (fit === 'elastic') {
|
||
const sx = sxW;
|
||
const extra = dev.h - d.designHeight * sx;
|
||
if (extra <= 0.5) return contain();
|
||
const bands = rowBands(items);
|
||
const segs = [];
|
||
let prev = 0;
|
||
for (const [a, b] of bands) { segs.push([prev, a]); prev = b; }
|
||
segs.push([prev, d.designHeight]);
|
||
const totalBlank = segs.reduce((s, [a, b]) => s + Math.max(0, b - a), 0) || 1;
|
||
const k = (totalBlank + extra) / totalBlank;
|
||
const deltas = [];
|
||
let acc = 0;
|
||
segs.forEach(([a, b], i) => {
|
||
acc += Math.max(0, b - a) * (k - 1);
|
||
if (i < bands.length) deltas.push(acc);
|
||
});
|
||
return { sx, sy:sx, ox:0, oy:0, elastic:{ bands, deltas, k } };
|
||
}
|
||
return contain();
|
||
}
|
||
|
||
function mapY(m, y) {
|
||
if (m.elastic) {
|
||
const { bands, deltas } = m.elastic;
|
||
let d = 0;
|
||
for (let i = 0; i < bands.length; i++) if (y >= bands[i][0] - 0.5) d = deltas[i];
|
||
return y * m.sy + d;
|
||
}
|
||
return y * m.sy + m.oy;
|
||
}
|
||
|
||
/* =============================================================================
|
||
* 3. 历史(撤销 / 重做)
|
||
* ===========================================================================*/
|
||
let history = [], future = [];
|
||
|
||
function snapshot() { return JSON.stringify(state); }
|
||
function pushHistory() {
|
||
history.push(snapshot());
|
||
if (history.length > 80) history.shift();
|
||
future.length = 0;
|
||
refreshUndo();
|
||
}
|
||
function undo() {
|
||
if (!history.length) return;
|
||
future.push(snapshot());
|
||
state = JSON.parse(history.pop());
|
||
activePage = Math.min(activePage, state.pages.length - 1);
|
||
if (selectedId && !cur().items.some(i => i.id === selectedId)) selectedId = null;
|
||
syncControls(); render(); refreshUndo();
|
||
}
|
||
function redo() {
|
||
if (!future.length) return;
|
||
history.push(snapshot());
|
||
state = JSON.parse(future.pop());
|
||
activePage = Math.min(activePage, state.pages.length - 1);
|
||
if (selectedId && !cur().items.some(i => i.id === selectedId)) selectedId = null;
|
||
syncControls(); render(); refreshUndo();
|
||
}
|
||
function refreshUndo() {
|
||
$('undo').disabled = !history.length;
|
||
$('redo').disabled = !future.length;
|
||
}
|
||
|
||
/* =============================================================================
|
||
* 4. 设计稿渲染
|
||
* ===========================================================================*/
|
||
let canvasScale = 1;
|
||
|
||
function fitCanvas() {
|
||
const stage = $('stage');
|
||
const availW = Math.max(200, stage.clientWidth - 56);
|
||
const availH = Math.max(200, stage.clientHeight - 48);
|
||
const s = Math.min(availW / state.canvas.designWidth, availH / state.canvas.designHeight);
|
||
canvasScale = Math.max(0.1, s);
|
||
const el = $('design');
|
||
el.style.width = (state.canvas.designWidth * canvasScale) + 'px';
|
||
el.style.height = (state.canvas.designHeight * canvasScale) + 'px';
|
||
$('dSizeTxt').textContent = state.canvas.designWidth + ' × ' + state.canvas.designHeight;
|
||
}
|
||
|
||
function hashHue(seed) {
|
||
let h = 0;
|
||
for (let i = 0; i < seed.length; i++) h = (h * 31 + seed.charCodeAt(i)) | 0;
|
||
return Math.abs(h) % 360;
|
||
}
|
||
function iconGrad(seed) {
|
||
const h1 = hashHue(seed || 'x');
|
||
return `linear-gradient(145deg,hsl(${h1},68%,60%),hsl(${(h1 + 26) % 360},72%,46%))`;
|
||
}
|
||
|
||
function renderDesign() {
|
||
const host = $('design');
|
||
host.style.background = pageBackground();
|
||
[...host.querySelectorAll('.el')].forEach(n => n.remove());
|
||
const s = canvasScale;
|
||
const c = state.canvas;
|
||
|
||
const g = $('guides');
|
||
g.innerHTML = '';
|
||
if ($('showGuides').checked) {
|
||
g.classList.add('show');
|
||
for (let i = 1; i < 4; i++) {
|
||
const d = document.createElement('i');
|
||
d.style.cssText = `left:${i*25}%;top:0;bottom:0;width:1px`;
|
||
g.appendChild(d);
|
||
}
|
||
for (let r = 1; r < 8; r++) {
|
||
const d = document.createElement('i');
|
||
d.style.cssText = `top:${(r/8)*100}%;left:0;right:0;height:1px`;
|
||
g.appendChild(d);
|
||
}
|
||
} else g.classList.remove('show');
|
||
|
||
$('safeT').style.top = (c.safeTop * s) + 'px';
|
||
$('safeB').style.bottom = (c.safeBottom * s) + 'px';
|
||
|
||
cur().items.slice().sort((a, b) => (a.z || 0) - (b.z || 0)).forEach(it => {
|
||
const n = document.createElement('div');
|
||
n.className = 'el' + (it.id === selectedId ? ' sel' : '');
|
||
n.dataset.id = it.id;
|
||
n.style.cssText = `left:${it.x*s}px;top:${it.y*s}px;width:${it.w*s}px;height:${it.h*s}px;` +
|
||
`z-index:${(it.z || 1) + 10}`;
|
||
n.innerHTML = itemInner(it, s);
|
||
if (it.type !== 'dock_bg') {
|
||
const h = document.createElement('div');
|
||
h.className = 'handle';
|
||
n.appendChild(h);
|
||
}
|
||
host.appendChild(n);
|
||
});
|
||
}
|
||
|
||
function itemInner(it, s) {
|
||
if (it.type === 'dock_bg') {
|
||
return `<div class="dockbg" style="border-radius:${(it.payload.radius || 56) * s}px"></div>`;
|
||
}
|
||
if (it.type === 'widget') {
|
||
const p = it.payload.provider || '';
|
||
const t = (it.payload.label || 'WIDGET').toUpperCase();
|
||
if (p.includes('Clock')) {
|
||
return `<div class="wg"><div class="t" style="font-size:${Math.max(6, 24*s)}px">${esc(t)}</div>
|
||
<div class="v" style="font-size:${Math.min(it.h*s*0.30, 48)}px">09:41</div>
|
||
<div class="s" style="font-size:${Math.max(6, 21*s)}px">11月25日 周三 · 晴 12°</div></div>`;
|
||
}
|
||
if (p.includes('Weather')) {
|
||
return `<div class="wg"><div class="t" style="font-size:${Math.max(6, 24*s)}px">${esc(t)}</div>
|
||
<div class="v" style="font-size:${Math.min(it.h*s*0.26, 40)}px">12°</div>
|
||
<div class="s" style="font-size:${Math.max(6, 21*s)}px">多云 · 东南风 3 级</div></div>`;
|
||
}
|
||
return `<div class="wg"><div class="t" style="font-size:${Math.max(6, 24*s)}px">NOW PLAYING</div>
|
||
<div class="v" style="font-size:${Math.min(it.h*s*0.15, 26)}px">夜曲</div>
|
||
<div class="s" style="font-size:${Math.max(6, 21*s)}px">周杰伦 · 十一月的萧邦</div></div>`;
|
||
}
|
||
const box = it.w * s * 0.78;
|
||
const letter = (it.payload.label || '?').slice(0, 1);
|
||
const seed = it.payload.package || it.payload.label || it.id;
|
||
return `<div class="ic" style="width:${box}px;height:${box}px;font-size:${box*0.44}px;` +
|
||
`background:${iconGrad(seed)}">${esc(letter)}</div>` +
|
||
`<div class="lb" style="font-size:${Math.max(6, it.w*s*0.19)}px;margin-top:${box*0.05}px">` +
|
||
`${esc(it.payload.label || '')}</div>`;
|
||
}
|
||
|
||
/* =============================================================================
|
||
* 5. 设备矩阵
|
||
* ===========================================================================*/
|
||
function renderDevices() {
|
||
const host = $('matrix');
|
||
host.innerHTML = '';
|
||
const fit = state.fit.mode.toLowerCase(), anchor = Math.max(0, Math.min(1, state.fit.anchorY));
|
||
const items = cur().items;
|
||
|
||
DEVICES.forEach(dev => {
|
||
const m = buildMapper(dev, items, fit, anchor);
|
||
const isContain = !m.elastic;
|
||
|
||
const TARGET_H = 198, MAX_W = 146;
|
||
let W = TARGET_H * dev.w / dev.h, H = TARGET_H;
|
||
if (W > MAX_W) { W = MAX_W; H = MAX_W * dev.h / dev.w; }
|
||
|
||
const cw = state.canvas.designWidth * m.sx;
|
||
const ch = state.canvas.designHeight * m.sy;
|
||
const padX = Math.max(0, (dev.w - cw) / 2);
|
||
const padY = isContain ? Math.max(0, dev.h - ch) : 0;
|
||
const topGap = isContain ? padY * anchor : 0;
|
||
const botGap = isContain ? padY * (1 - anchor) : 0;
|
||
|
||
let inner = '';
|
||
items.slice().sort((a,b) => (a.z||0) - (b.z||0)).forEach(it => {
|
||
const px = (it.x * m.sx + m.ox) / dev.w * 100;
|
||
const py = mapY(m, it.y) / dev.h * 100;
|
||
const pw = it.w * m.sx / dev.w * 100;
|
||
const ph = it.h * m.sy / dev.h * 100;
|
||
let body;
|
||
if (it.type === 'dock_bg') {
|
||
body = `<div style="width:100%;height:100%;border-radius:5px;background:rgba(255,255,255,.13);border:1px solid rgba(255,255,255,.12)"></div>`;
|
||
} else if (it.type === 'widget') {
|
||
body = `<div style="width:100%;height:100%;border-radius:4px;background:linear-gradient(150deg,rgba(255,255,255,.22),rgba(255,255,255,.08));border:1px solid rgba(255,255,255,.16)"></div>`;
|
||
} else {
|
||
const sq = it.w * m.sx * 0.78 / dev.w * W;
|
||
const sqh = it.w * m.sy * 0.78 / dev.h * H;
|
||
body = `<div style="width:${sq}px;height:${sqh}px;border-radius:3px;background:${iconGrad(it.payload.package || it.payload.label || it.id)}"></div>`;
|
||
}
|
||
inner += `<div style="position:absolute;left:${px}%;top:${py}%;width:${pw}%;height:${ph}%;
|
||
display:flex;align-items:center;justify-content:center">${body}</div>`;
|
||
});
|
||
|
||
let gapHtml = '';
|
||
if (isContain) {
|
||
if (topGap > 0.5) gapHtml += `<div class="gapzone" style="top:0;height:${topGap/dev.h*100}%"></div>`;
|
||
if (botGap > 0.5) gapHtml += `<div class="gapzone" style="bottom:0;height:${botGap/dev.h*100}%"></div>`;
|
||
if (padX > 0.5) {
|
||
const lw = padX / dev.w * 100;
|
||
gapHtml += `<div class="gapzone v" style="left:0;width:${lw}%"></div>`;
|
||
gapHtml += `<div class="gapzone v" style="right:0;width:${lw}%"></div>`;
|
||
}
|
||
if (padX > 0.5 || padY > 0.5) {
|
||
gapHtml += `<div class="contentbox" style="left:${padX/dev.w*100}%;top:${topGap/dev.h*100}%;
|
||
width:${cw/dev.w*100}%;height:${ch/dev.h*100}%"></div>`;
|
||
}
|
||
}
|
||
|
||
const dist = (m.sy / m.sx - 1) * 100;
|
||
const vLabel = m.elastic ? '×' + m.elastic.k.toFixed(2) : Math.round(padY) + 'px';
|
||
const vHot = m.elastic ? false : padY > 0.5;
|
||
const hHot = padX > 0.5;
|
||
|
||
const card = document.createElement('div');
|
||
card.className = 'dcard';
|
||
card.innerHTML = `
|
||
<div class="top"><span class="name">${dev.name}</span><span class="ratio">${dev.w}×${dev.h}</span></div>
|
||
<div class="phone-mini" style="width:${W}px;height:${H}px">
|
||
<div class="wp"></div><div class="content">${inner}</div>${gapHtml}
|
||
</div>
|
||
<div class="dstat">
|
||
<span>缩放 <b>${m.sx.toFixed(3)}</b></span>
|
||
<span>变形 <b class="${Math.abs(dist) > 0.5 ? 'warn' : 'ok'}">${Math.abs(dist) > 0.5 ? '+' + dist.toFixed(1) + '%' : '0%'}</b></span>
|
||
<span>${m.elastic ? '纵向' : '纵留白'} <b class="${vHot ? 'warn' : 'ok'}">${vLabel}</b></span>
|
||
<span>横留白 <b class="${hHot ? 'warn' : 'ok'}">${Math.round(padX)}px</b></span>
|
||
</div>`;
|
||
card.querySelector('.wp').style.background = pageBackground();
|
||
host.appendChild(card);
|
||
});
|
||
|
||
// 汇总
|
||
if (fit === 'stretch') {
|
||
$('devSummary').textContent = '横向与纵向分别缩放,填满屏幕。';
|
||
} else if (fit === 'elastic' && buildMapper({w:1080,h:2160}, items, fit, anchor).elastic) {
|
||
const mm = buildMapper({w:1080,h:2160}, items, 'elastic', anchor);
|
||
$('devSummary').innerHTML =
|
||
`弹性行距 · 纵向余量按原空白比例放大到行间距(18:9 上 ×${mm.elastic.k.toFixed(2)}),元素尺寸不变`;
|
||
} else {
|
||
let vC = 0, hC = 0, mV = 0, mH = 0;
|
||
DEVICES.forEach(d => {
|
||
const mm = buildMapper(d, items, 'contain', anchor);
|
||
const cw2 = state.canvas.designWidth * mm.sx, ch2 = state.canvas.designHeight * mm.sy;
|
||
const dv = d.h - ch2, dh = (d.w - cw2) / 2;
|
||
if (dv > 0.5) { vC++; mV = Math.max(mV, dv); }
|
||
if (dh > 0.5) { hC++; mH = Math.max(mH, dh); }
|
||
});
|
||
$('devSummary').innerHTML = `双向等比居中 · ` +
|
||
(vC ? `${vC} 台更高 → 上下留白(最大 ${Math.round(mV)}px)` : '无上下留白') +
|
||
(hC ? `,${hC} 台更宽 → 左右留白(最大 ${Math.round(mH)}px)` : '');
|
||
}
|
||
}
|
||
|
||
/* =============================================================================
|
||
* 6. 属性 / 校验 / JSON
|
||
* ===========================================================================*/
|
||
function typeName(t) {
|
||
return { app_icon:'应用图标', widget:'小组件', shortcut:'快捷方式', dock_bg:'Dock 底板' }[t] || t;
|
||
}
|
||
|
||
function renderProps() {
|
||
const host = $('propBody');
|
||
const it = cur().items.find(i => i.id === selectedId);
|
||
if (!it) {
|
||
host.innerHTML = `<div class="empty">画布中没有选中元素<br>
|
||
<span style="color:#5c6577">点击元素编辑属性<br>双击空白新增图标</span></div>`;
|
||
return;
|
||
}
|
||
|
||
const pf = [];
|
||
if (it.type === 'app_icon') {
|
||
pf.push(`<div class="field"><label>显示名</label>
|
||
<input type="text" data-p="label" value="${esc(it.payload.label || '')}"></div>`);
|
||
pf.push(`<div class="field"><label>包名</label>
|
||
<input type="text" data-p="package" value="${esc(it.payload.package || '')}"></div>`);
|
||
} else if (it.type === 'shortcut') {
|
||
pf.push(`<div class="field"><label>显示名</label>
|
||
<input type="text" data-p="label" value="${esc(it.payload.label || '')}"></div>`);
|
||
pf.push(`<div class="field"><label>Intent</label>
|
||
<input type="text" data-p="intent" value="${esc(it.payload.intent || '')}"></div>`);
|
||
} else if (it.type === 'widget') {
|
||
pf.push(`<div class="field"><label>Provider</label>
|
||
<input type="text" data-p="provider" value="${esc(it.payload.provider || '')}"></div>`);
|
||
pf.push(`<div class="field"><label>名称</label>
|
||
<input type="text" data-p="label" value="${esc(it.payload.label || '')}"></div>`);
|
||
} else if (it.type === 'dock_bg') {
|
||
pf.push(`<div class="field"><label>圆角</label>
|
||
<input type="number" data-p="radius" value="${it.payload.radius || 56}" step="4" min="0" max="200"></div>`);
|
||
}
|
||
|
||
host.innerHTML = `
|
||
<div class="prop-title">
|
||
<span class="pill">${esc(typeName(it.type))}</span>
|
||
<span class="id">${esc(it.id)}</span>
|
||
</div>
|
||
<div class="sec">位置与尺寸(设计稿像素)</div>
|
||
<div class="field"><label>X</label><input type="number" data-k="x" value="${Math.round(it.x)}" step="2"></div>
|
||
<div class="field"><label>Y</label><input type="number" data-k="y" value="${Math.round(it.y)}" step="2"></div>
|
||
<div class="field"><label>宽</label><input type="number" data-k="w" value="${Math.round(it.w)}" step="2" min="24"></div>
|
||
<div class="field"><label>高</label><input type="number" data-k="h" value="${Math.round(it.h)}" step="2" min="24"></div>
|
||
<div class="field"><label>层级 z</label><input type="number" data-k="z" value="${it.z || 1}" step="1"></div>
|
||
<div class="sec">内容</div>
|
||
${pf.join('')}
|
||
<div class="btnrow">
|
||
<button class="btn" id="pTop">置顶</button>
|
||
<button class="btn" id="pBottom">置底</button>
|
||
<button class="btn" id="pDel" style="color:#ff8a8a">删除</button>
|
||
</div>`;
|
||
|
||
host.querySelectorAll('input[data-k]').forEach(inp => {
|
||
inp.onchange = () => {
|
||
const k = inp.dataset.k, v = parseFloat(inp.value);
|
||
if (isNaN(v)) { renderProps(); return; }
|
||
pushHistory();
|
||
if (k === 'w') it.w = Math.max(24, Math.min(state.canvas.designWidth - it.x, v));
|
||
else if (k === 'h') it.h = Math.max(24, Math.min(state.canvas.designHeight - it.y, v));
|
||
else if (k === 'x') it.x = Math.max(0, Math.min(state.canvas.designWidth - it.w, v));
|
||
else if (k === 'y') it.y = Math.max(0, Math.min(state.canvas.designHeight - it.h, v));
|
||
else if (k === 'z') it.z = v;
|
||
render();
|
||
};
|
||
});
|
||
host.querySelectorAll('input[data-p]').forEach(inp => {
|
||
inp.onchange = () => {
|
||
pushHistory();
|
||
const k = inp.dataset.p;
|
||
it.payload[k] = k === 'radius' ? Math.max(0, parseInt(inp.value, 10) || 0) : inp.value;
|
||
render();
|
||
};
|
||
});
|
||
const zMax = Math.max(...cur().items.map(i => i.z || 1));
|
||
$('pTop').onclick = () => { pushHistory(); it.z = zMax + 1; render(); };
|
||
$('pBottom').onclick = () => { pushHistory(); it.z = 0; render(); };
|
||
$('pDel').onclick = delSelected;
|
||
}
|
||
|
||
function esc(s) {
|
||
return String(s).replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<');
|
||
}
|
||
|
||
function validate() {
|
||
const issues = [];
|
||
const c = state.canvas;
|
||
const push = (lv, id, msg) => issues.push({ lv, id, msg });
|
||
|
||
state.pages.forEach((page, pi) => {
|
||
const ids = new Set();
|
||
const tag = state.pages.length > 1 ? `P${pi + 1} ` : '';
|
||
for (const it of page.items) {
|
||
const who = tag + it.id;
|
||
if (!it.id.trim()) push('err', who, 'id 为空');
|
||
if (ids.has(it.id)) push('err', who, 'id 重复');
|
||
ids.add(it.id);
|
||
if (it.w <= 0 || it.h <= 0) push('err', who, '尺寸必须为正数');
|
||
if (it.x < 0 || it.y < 0) push('err', who, '坐标不能为负');
|
||
if (it.x + it.w > c.designWidth + 0.5) push('err', who, '右侧超出画布');
|
||
if (it.y + it.h > c.designHeight + 0.5) push('err', who, '底部超出画布');
|
||
if (it.y < c.safeTop) push('warn', who, '顶部进入 safeTop 安全区');
|
||
if (it.y + it.h > c.designHeight - c.safeBottom) push('warn', who, '底部进入 safeBottom 安全区');
|
||
if (it.type === 'app_icon' && !it.payload.package) push('err', who, '应用图标缺少 package(真机会显示空白)');
|
||
if (it.type === 'widget' && !(it.payload.provider || '').includes('/')) push('err', who, 'provider 需形如 com.x/.Widget');
|
||
}
|
||
for (let i = 0; i < page.items.length; i++) {
|
||
for (let j = i + 1; j < page.items.length; j++) {
|
||
const a = page.items[i], b = page.items[j];
|
||
if (a.type === 'dock_bg' || b.type === 'dock_bg') continue;
|
||
if (a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y) {
|
||
push('warn', tag + a.id, `与 ${b.id} 重叠`);
|
||
}
|
||
}
|
||
}
|
||
});
|
||
|
||
if (c.safeTop < 0 || c.safeBottom < 0) push('err', '-', '安全区不能为负数');
|
||
if (!['contain', 'elastic', 'stretch'].includes(state.fit.mode.toLowerCase())) push('warn', '-', '未知映射模式');
|
||
if (c.safeTop < 118) push('warn', '-', `safeTop=${c.safeTop} 偏小`);
|
||
if (c.safeBottom < 40) push('warn', '-', `safeBottom=${c.safeBottom} 偏小,可能被手势条压住`);
|
||
|
||
const errors = issues.filter(i => i.lv === 'err').length;
|
||
return { issues, errors, warns: issues.length - errors };
|
||
}
|
||
|
||
function renderRules() {
|
||
const { issues, errors, warns } = validate();
|
||
const host = $('ruleBody');
|
||
if (!issues.length) {
|
||
host.innerHTML = `<div class="okbox">校验通过<div class="sub">
|
||
0 错误 · 0 提醒 · ${cur().items.length} 个元素</div></div>`;
|
||
return;
|
||
}
|
||
host.innerHTML = `<div style="font-size:11.5px;color:var(--dim);margin-bottom:10px">
|
||
共 <b style="color:#ff8a8a">${errors}</b> 个错误 ·
|
||
<b style="color:#ffc766">${warns}</b> 个提醒</div>` +
|
||
issues.map(i => `<div class="issue ${i.lv === 'err' ? 'err' : 'warn'}">
|
||
<span class="tag">${i.lv === 'err' ? 'ERROR' : 'WARN'}</span>
|
||
<div><div>${esc(i.msg)}</div><div class="who">${esc(i.id)}</div></div></div>`).join('');
|
||
}
|
||
|
||
function exportJson() {
|
||
return {
|
||
...state,
|
||
schemaVersion: 3,
|
||
revision: state.revision,
|
||
canvas: state.canvas,
|
||
fit: state.fit,
|
||
pages: state.pages.map((p, i) => ({
|
||
...p,
|
||
index: i,
|
||
background: p.background,
|
||
items: p.items.map(it => ({
|
||
...it,
|
||
z: it.z ?? 1,
|
||
payload: it.payload,
|
||
})),
|
||
})),
|
||
};
|
||
}
|
||
|
||
function renderJson() {
|
||
$('jsonOut').textContent = JSON.stringify(exportJson(), null, 2);
|
||
}
|
||
|
||
/* =============================================================================
|
||
* 7. 页面栏
|
||
* ===========================================================================*/
|
||
function renderPageBar() {
|
||
const bar = $('pagebar');
|
||
[...bar.querySelectorAll('i')].forEach(n => n.remove());
|
||
state.pages.forEach((_, i) => {
|
||
const d = document.createElement('i');
|
||
d.className = i === activePage ? 'on' : '';
|
||
d.title = '第 ' + (i + 1) + ' 页';
|
||
d.onclick = () => { activePage = i; selectedId = null; render(); };
|
||
bar.appendChild(d);
|
||
});
|
||
$('pageNum').textContent = (activePage + 1) + ' / ' + state.pages.length;
|
||
$('addPage').disabled = state.pages.length >= 20;
|
||
$('delPage').disabled = state.pages.length <= 1;
|
||
$('prevPage').disabled = activePage === 0;
|
||
$('nextPage').disabled = activePage >= state.pages.length - 1;
|
||
}
|
||
|
||
/* =============================================================================
|
||
* 8. 交互
|
||
* ===========================================================================*/
|
||
let drag = null;
|
||
|
||
$('design').addEventListener('pointerdown', e => {
|
||
const el = e.target.closest('.el');
|
||
if (!el) { selectedId = null; render(); return; }
|
||
const it = cur().items.find(i => i.id === el.dataset.id);
|
||
if (!it) return;
|
||
selectedId = it.id;
|
||
drag = {
|
||
it, resize: !!e.target.closest('.handle'),
|
||
sx: e.clientX, sy: e.clientY,
|
||
ox: it.x, oy: it.y, ow: it.w, oh: it.h, moved: false,
|
||
};
|
||
e.target.setPointerCapture?.(e.pointerId);
|
||
render();
|
||
});
|
||
|
||
window.addEventListener('pointermove', e => {
|
||
if (!drag) return;
|
||
const dx = (e.clientX - drag.sx) / canvasScale;
|
||
const dy = (e.clientY - drag.sy) / canvasScale;
|
||
if (Math.abs(dx) + Math.abs(dy) > 1.5 && !drag.moved) {
|
||
pushHistory();
|
||
drag.moved = true;
|
||
}
|
||
const snap = v => $('snap').checked ? Math.round(v / 12) * 12 : Math.round(v);
|
||
const it = drag.it, c = state.canvas;
|
||
if (drag.resize) {
|
||
it.w = Math.max(24, Math.min(c.designWidth - it.x, snap(drag.ow + dx)));
|
||
it.h = Math.max(24, Math.min(c.designHeight - it.y, snap(drag.oh + dy)));
|
||
} else {
|
||
it.x = Math.max(0, Math.min(c.designWidth - it.w, snap(drag.ox + dx)));
|
||
it.y = Math.max(0, Math.min(c.designHeight - it.h, snap(drag.oy + dy)));
|
||
}
|
||
renderDesign();
|
||
});
|
||
|
||
window.addEventListener('pointerup', () => {
|
||
if (drag && drag.moved) {
|
||
renderDevices(); renderProps(); renderJson(); renderRules();
|
||
}
|
||
drag = null;
|
||
});
|
||
|
||
$('design').addEventListener('dblclick', e => {
|
||
if (e.target.closest('.el')) return;
|
||
const r = $('design').getBoundingClientRect();
|
||
pushHistory();
|
||
addItem(LIB[0], (e.clientX - r.left) / canvasScale - 66, (e.clientY - r.top) / canvasScale - 84);
|
||
});
|
||
|
||
function addItem(tpl, x, y) {
|
||
if (cur().items.length >= 80) return toast('本页最多 80 个元素');
|
||
let id;
|
||
do { id = 'e' + (uidCounter++); } while (cur().items.some(item => item.id === id));
|
||
const it = {
|
||
id,
|
||
type: tpl.type,
|
||
x: Math.max(0, Math.min(state.canvas.designWidth - tpl.w, Math.round(x ?? 108))),
|
||
y: Math.max(0, Math.min(state.canvas.designHeight - tpl.h, Math.round(y ?? 300))),
|
||
w: Math.min(tpl.w, state.canvas.designWidth), h: Math.min(tpl.h, state.canvas.designHeight), z: 2,
|
||
payload: { ...tpl.payload },
|
||
};
|
||
cur().items.push(it);
|
||
selectedId = it.id;
|
||
render();
|
||
}
|
||
|
||
function delSelected() {
|
||
if (!selectedId) return toast('先选中一个元素');
|
||
pushHistory();
|
||
const page = cur();
|
||
page.items = page.items.filter(i => i.id !== selectedId);
|
||
selectedId = null;
|
||
render();
|
||
toast('已删除');
|
||
}
|
||
|
||
$('lib').innerHTML = LIB.map((l, i) => `<button data-i="${i}">${l.label}</button>`).join('');
|
||
$('lib').onclick = e => {
|
||
const b = e.target.closest('button');
|
||
if (!b) return;
|
||
pushHistory();
|
||
const tpl = LIB[+b.dataset.i];
|
||
const n = cur().items.length;
|
||
addItem(tpl, 108 + (n % 4) * 216, 300 + (n % 3) * 60);
|
||
};
|
||
|
||
$('designSize').onchange = e => {
|
||
const [w, h] = e.target.value.split('x').map(Number);
|
||
pushHistory();
|
||
state.canvas.designWidth = w;
|
||
state.canvas.designHeight = h;
|
||
fitCanvas(); render();
|
||
};
|
||
$('safeTop').oninput = e => { state.canvas.safeTop = +e.target.value || 0; renderDesign(); };
|
||
$('safeBottom').oninput = e => { state.canvas.safeBottom = +e.target.value || 0; renderDesign(); };
|
||
$('showGuides').onchange = () => renderDesign();
|
||
|
||
$('fitSeg').onclick = e => {
|
||
const b = e.target.closest('button');
|
||
if (!b) return;
|
||
state.fit.mode = b.dataset.fit;
|
||
[...$('fitSeg').children].forEach(n => n.classList.toggle('on', n === b));
|
||
render();
|
||
};
|
||
$('anchor').onchange = e => { state.fit.anchorY = parseFloat(e.target.value); render(); };
|
||
|
||
function showPane(name) {
|
||
[...$('tabs').children].forEach(n => n.classList.toggle('on', n.dataset.pane === name));
|
||
document.querySelectorAll('.pane').forEach(p => p.classList.remove('on'));
|
||
$('pane-' + name).classList.add('on');
|
||
if (name === 'rules') renderRules();
|
||
if (name === 'props') renderProps();
|
||
}
|
||
$('tabs').onclick = e => {
|
||
const b = e.target.closest('button');
|
||
if (b) showPane(b.dataset.pane);
|
||
};
|
||
|
||
$('undo').onclick = undo;
|
||
$('redo').onclick = redo;
|
||
$('delEl').onclick = delSelected;
|
||
$('validate').onclick = () => {
|
||
showPane('rules');
|
||
const { errors, warns } = validate();
|
||
toast(errors ? `发现 ${errors} 个错误、${warns} 个提醒`
|
||
: (warns ? `无错误,${warns} 个提醒` : '校验通过'));
|
||
};
|
||
|
||
$('align').onclick = () => {
|
||
pushHistory();
|
||
cur().items.forEach(it => {
|
||
it.x = Math.round(it.x / 12) * 12;
|
||
it.y = Math.round(it.y / 12) * 12;
|
||
it.w = Math.round(it.w / 12) * 12;
|
||
it.h = Math.round(it.h / 12) * 12;
|
||
});
|
||
render(); toast('已对齐到 12px 栅格');
|
||
};
|
||
|
||
$('addPage').onclick = () => {
|
||
pushHistory();
|
||
state.pages.splice(activePage + 1, 0, { index:0, background:{ type:'wallpaper' }, items:[] });
|
||
activePage += 1;
|
||
selectedId = null;
|
||
render();
|
||
toast('已新增第 ' + (activePage + 1) + ' 页');
|
||
};
|
||
$('delPage').onclick = () => {
|
||
if (state.pages.length <= 1) return;
|
||
pushHistory();
|
||
state.pages.splice(activePage, 1);
|
||
activePage = Math.min(activePage, state.pages.length - 1);
|
||
selectedId = null;
|
||
render();
|
||
toast('已删除本页');
|
||
};
|
||
$('prevPage').onclick = () => { if (activePage > 0) { activePage--; selectedId = null; render(); } };
|
||
$('nextPage').onclick = () => { if (activePage < state.pages.length - 1) { activePage++; selectedId = null; render(); } };
|
||
|
||
function copyJson() {
|
||
const txt = JSON.stringify(exportJson(), null, 2);
|
||
navigator.clipboard?.writeText(txt).then(
|
||
() => toast('协议已复制(' + txt.length + ' 字节)'),
|
||
() => toast('复制失败,请到 JSON 面板手动选中')
|
||
);
|
||
}
|
||
$('copy').onclick = copyJson;
|
||
$('copy2').onclick = copyJson;
|
||
|
||
$('download').onclick = $('exportBtn').onclick = () => {
|
||
const blob = new Blob([JSON.stringify(exportJson(), null, 2)], { type:'application/json' });
|
||
const a = document.createElement('a');
|
||
a.href = URL.createObjectURL(blob);
|
||
a.download = 'launcher_layout.json';
|
||
a.click();
|
||
setTimeout(() => URL.revokeObjectURL(a.href), 1500);
|
||
toast('已导出 launcher_layout.json');
|
||
};
|
||
|
||
function importLayout(d) {
|
||
if (!d || (d.schemaVersion ?? 3) !== 3) throw new Error('仅支持布局协议 v3');
|
||
const canvas = { designWidth:1080, designHeight:1920, safeTop:72, safeBottom:72, ...d.canvas };
|
||
const fit = { mode:'contain', anchorY:0.5, ...d.fit };
|
||
if (![canvas.designWidth, canvas.designHeight, canvas.safeTop, canvas.safeBottom].every(Number.isInteger) ||
|
||
canvas.designWidth < 320 || canvas.designHeight < 480 ||
|
||
canvas.designWidth > 8192 || canvas.designHeight > 8192 ||
|
||
!Number.isFinite(fit.anchorY) || typeof fit.mode !== 'string' ||
|
||
!Array.isArray(d.pages) || d.pages.length === 0 || d.pages.length > 20) {
|
||
throw new Error('画布参数或页数无效');
|
||
}
|
||
const pages = d.pages.map((p, index) => {
|
||
const items = p?.items ?? [];
|
||
if (!p || !Array.isArray(items) || items.length > 80) throw new Error('无效页面或元素超限');
|
||
return { ...p, index, background:p.background ?? { type:'wallpaper' }, items:items.map(it => {
|
||
if (!it || typeof it.id !== 'string' || typeof it.type !== 'string' ||
|
||
![it.x, it.y, it.w, it.h].every(Number.isFinite) ||
|
||
(it.z !== undefined && !Number.isInteger(it.z))) throw new Error('元素字段格式错误');
|
||
const payload = it.payload ?? {};
|
||
if (typeof payload !== 'object' || Array.isArray(payload) ||
|
||
['label','package','provider','intent'].some(k => payload[k] != null && typeof payload[k] !== 'string') ||
|
||
(payload.radius != null && !Number.isInteger(payload.radius))) throw new Error('内容字段格式错误');
|
||
return { ...it, z:it.z ?? 1, payload };
|
||
}) };
|
||
});
|
||
pushHistory();
|
||
state = { ...d, schemaVersion:3, revision:d.revision ?? 1, canvas, fit, pages };
|
||
activePage = 0;
|
||
selectedId = null;
|
||
syncControls();
|
||
fitCanvas();
|
||
render();
|
||
}
|
||
|
||
$('importBtn').onclick = () => $('fileInput').click();
|
||
$('fileInput').onchange = e => {
|
||
const f = e.target.files?.[0];
|
||
e.target.value = '';
|
||
if (!f || !confirmDraftReplacement()) return;
|
||
if (f.size > 1024 * 1024) { toast('布局超过 1 MiB'); return; }
|
||
const r = new FileReader();
|
||
r.onload = () => {
|
||
try {
|
||
importLayout(JSON.parse(r.result));
|
||
toast('已导入 ' + state.pages.length + ' 页');
|
||
} catch (err) {
|
||
toast('导入失败:' + err.message);
|
||
}
|
||
e.target.value = '';
|
||
};
|
||
r.readAsText(f);
|
||
};
|
||
|
||
$('resetDemo').onclick = () => {
|
||
if (!confirmDraftReplacement()) return;
|
||
pushHistory();
|
||
state = newState();
|
||
activePage = 0; selectedId = null;
|
||
syncControls(); fitCanvas(); render();
|
||
toast('已重置为示例布局');
|
||
};
|
||
|
||
function setSelectValue(select, value, label) {
|
||
select.querySelector('option[data-custom]')?.remove();
|
||
if (![...select.options].some(option => option.value === value)) {
|
||
const option = new Option(label, value);
|
||
option.dataset.custom = '';
|
||
select.add(option);
|
||
}
|
||
select.value = value;
|
||
}
|
||
function syncControls() {
|
||
const key = state.canvas.designWidth + 'x' + state.canvas.designHeight;
|
||
setSelectValue($('designSize'), key, key.replace('x', ' × '));
|
||
$('safeTop').value = state.canvas.safeTop;
|
||
$('safeBottom').value = state.canvas.safeBottom;
|
||
setSelectValue($('anchor'), String(state.fit.anchorY), String(state.fit.anchorY));
|
||
[...$('fitSeg').children].forEach(n => n.classList.toggle('on', n.dataset.fit === state.fit.mode));
|
||
}
|
||
|
||
window.addEventListener('keydown', e => {
|
||
const inField = ['INPUT','SELECT','TEXTAREA'].includes(e.target.tagName);
|
||
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'z') {
|
||
e.preventDefault();
|
||
e.shiftKey ? redo() : undo();
|
||
return;
|
||
}
|
||
if (inField) return;
|
||
if (e.key === 'Delete' || e.key === 'Backspace') {
|
||
if (selectedId) { e.preventDefault(); delSelected(); }
|
||
return;
|
||
}
|
||
if (e.key === 'Escape') { selectedId = null; render(); return; }
|
||
const it = cur().items.find(i => i.id === selectedId);
|
||
if (!it) return;
|
||
const step = e.shiftKey ? 10 : 1;
|
||
let handled = true;
|
||
if (e.key === 'ArrowLeft') it.x = Math.max(0, it.x - step);
|
||
else if (e.key === 'ArrowRight') it.x = Math.min(state.canvas.designWidth - it.w, it.x + step);
|
||
else if (e.key === 'ArrowUp') it.y = Math.max(0, it.y - step);
|
||
else if (e.key === 'ArrowDown') it.y = Math.min(state.canvas.designHeight - it.h, it.y + step);
|
||
else handled = false;
|
||
if (handled) { e.preventDefault(); render(); }
|
||
});
|
||
|
||
window.addEventListener('resize', () => { fitCanvas(); renderDesign(); });
|
||
|
||
function toast(msg) {
|
||
const t = $('toast');
|
||
t.textContent = msg;
|
||
t.classList.add('on');
|
||
clearTimeout(t._h);
|
||
t._h = setTimeout(() => t.classList.remove('on'), 1700);
|
||
}
|
||
|
||
/* =============================================================================
|
||
* 9. 启动
|
||
* ===========================================================================*/
|
||
const backgroundColor = (value, fallback = '#151a22') =>
|
||
typeof value === 'string' && /^#[0-9a-f]{6}$/i.test(value) ? value : fallback;
|
||
function pageBackground() {
|
||
const bg = cur().background;
|
||
if (bg.type === 'solid') return backgroundColor(bg.color);
|
||
if (bg.type === 'gradient') return 'linear-gradient(' + backgroundColor(bg.from) + ',' + backgroundColor(bg.to) + ')';
|
||
return '';
|
||
}
|
||
function renderBackgroundControls() {
|
||
const bg = cur().background;
|
||
const mode = ['solid', 'gradient'].includes(bg.type) ? bg.type : 'wallpaper';
|
||
$('backgroundType').value = mode;
|
||
$('backgroundStartRow').hidden = mode === 'wallpaper';
|
||
$('backgroundEndRow').hidden = mode !== 'gradient';
|
||
$('backgroundStart').value = backgroundColor(mode === 'solid' ? bg.color : bg.from);
|
||
$('backgroundEnd').value = backgroundColor(bg.to, '#31507e');
|
||
}
|
||
for (const id of ['backgroundType', 'backgroundStart', 'backgroundEnd']) {
|
||
$(id).onchange = () => {
|
||
pushHistory();
|
||
const type = $('backgroundType').value;
|
||
const first = $('backgroundStart').value;
|
||
cur().background = {
|
||
...cur().background, type,
|
||
...(type === 'solid' ? { color:first } : {}),
|
||
...(type === 'gradient' ? { from:first, to:$('backgroundEnd').value } : {}),
|
||
};
|
||
render();
|
||
};
|
||
}
|
||
function render() {
|
||
try {
|
||
const draft = JSON.stringify(state);
|
||
if (draft === savedDraft) localStorage.removeItem(draftKey);
|
||
else localStorage.setItem(draftKey, draft);
|
||
} catch {
|
||
// Some browsers disable storage for file URLs. JSON export remains available.
|
||
}
|
||
renderBackgroundControls();
|
||
renderDesign();
|
||
renderDevices();
|
||
renderProps();
|
||
renderJson();
|
||
renderRules();
|
||
renderPageBar();
|
||
refreshUndo();
|
||
}
|
||
|
||
try {
|
||
const draft = localStorage.getItem(draftKey);
|
||
if (draft) importLayout(JSON.parse(draft));
|
||
} catch {
|
||
// An unavailable or invalid draft leaves the built-in layout active.
|
||
}
|
||
syncControls();
|
||
render();
|
||
requestAnimationFrame(() => { fitCanvas(); renderDesign(); });
|
||
setTimeout(() => { fitCanvas(); renderDesign(); }, 260);
|
||
</script>
|
||
<script>
|
||
const releaseDialog = $('releaseDialog');
|
||
const releaseStatus = $('releaseStatus');
|
||
let onlineTag = null;
|
||
let onlineRevision = null;
|
||
let nextBefore = null;
|
||
let releaseBusy = false;
|
||
|
||
const appBase = location.pathname.replace(/\/[^/]*$/, '').replace(/\/$/, '');
|
||
const hosted = ['http:', 'https:'].includes(location.protocol);
|
||
$('openRelease').hidden = !hosted;
|
||
$('openRelease').onclick = () => releaseDialog.showModal();
|
||
$('closeRelease').onclick = () => releaseDialog.close();
|
||
releaseDialog.addEventListener('cancel', e => { if (releaseBusy) e.preventDefault(); });
|
||
|
||
function refreshReleaseButtons() {
|
||
$('loadOnline').disabled = releaseBusy;
|
||
$('closeRelease').disabled = releaseBusy;
|
||
$('adminToken').disabled = releaseBusy;
|
||
$('publishLayout').disabled = releaseBusy || !onlineTag;
|
||
$('moreHistory').disabled = releaseBusy;
|
||
$('moreHistory').hidden = nextBefore === null;
|
||
$('releaseHistory').querySelectorAll('button').forEach(button => {
|
||
button.disabled = releaseBusy || !onlineTag;
|
||
});
|
||
}
|
||
|
||
$('adminToken').oninput = () => {
|
||
onlineTag = onlineRevision = nextBefore = null;
|
||
$('releaseHistory').replaceChildren();
|
||
releaseStatus.textContent = '';
|
||
refreshReleaseButtons();
|
||
};
|
||
|
||
async function adminRequest(path, options = {}) {
|
||
const token = $('adminToken').value.trim();
|
||
if (!token) throw new Error('请输入管理员令牌');
|
||
const res = await fetch(appBase + '/api/admin/' + path, {
|
||
...options,
|
||
cache: 'no-store',
|
||
redirect: 'error',
|
||
signal: AbortSignal.timeout(10000),
|
||
headers: { Authorization: 'Bearer ' + token, ...options.headers },
|
||
});
|
||
const data = await res.json();
|
||
if (!res.ok) {
|
||
if (res.status === 401 || res.status === 412) onlineTag = null;
|
||
const issues = (data.issues || []).slice(0, 8).map(i => i.path + ' · ' + i.message);
|
||
throw new Error([data.message || 'HTTP ' + res.status, ...issues].join('\n'));
|
||
}
|
||
return { data, tag: res.headers.get('ETag') };
|
||
}
|
||
|
||
async function releaseAction(action) {
|
||
if (releaseBusy) return;
|
||
releaseBusy = true;
|
||
refreshReleaseButtons();
|
||
releaseStatus.textContent = '正在连接服务端…';
|
||
try {
|
||
releaseStatus.textContent = await action();
|
||
} catch (error) {
|
||
releaseStatus.textContent = error.message;
|
||
} finally {
|
||
releaseBusy = false;
|
||
refreshReleaseButtons();
|
||
}
|
||
}
|
||
|
||
async function loadHistory(append = false) {
|
||
const { data } = await adminRequest('history' + (append ? '?before=' + nextBefore : ''));
|
||
nextBefore = data.nextBefore;
|
||
const list = $('releaseHistory');
|
||
if (!append) list.replaceChildren();
|
||
for (const row of data.revisions) {
|
||
const li = document.createElement('li');
|
||
li.className = 'release-row';
|
||
const label = document.createElement('span');
|
||
label.textContent = 'v' + row.revision + (row.revision === onlineRevision ? '(当前)' : '') +
|
||
(row.restoredFrom ? ' · 回滚自 v' + row.restoredFrom : '') +
|
||
' · ' + new Date(row.publishedAt).toLocaleString();
|
||
li.append(label);
|
||
if (row.revision !== onlineRevision) {
|
||
const view = document.createElement('button');
|
||
view.className = 'btn';
|
||
view.textContent = '载入编辑';
|
||
view.onclick = () => {
|
||
if (!confirmDraftReplacement()) return;
|
||
releaseAction(async () => {
|
||
const { data: layout } = await adminRequest('history/' + row.revision);
|
||
importLayout({ ...layout, revision: onlineRevision });
|
||
return '已载入 v' + row.revision + ',当前线上为 v' + onlineRevision;
|
||
});
|
||
};
|
||
const rollback = document.createElement('button');
|
||
rollback.className = 'btn';
|
||
rollback.textContent = '回滚';
|
||
rollback.onclick = () => {
|
||
if (!confirmDraftReplacement() || !confirm('将 v' + row.revision + ' 的布局作为新版本发布到所有已连接设备?')) return;
|
||
releaseAction(() => commitLayout('rollback', 'POST', { revision: row.revision }));
|
||
};
|
||
li.append(view, rollback);
|
||
}
|
||
list.append(li);
|
||
}
|
||
}
|
||
|
||
async function commitLayout(path, method, layout) {
|
||
const { data, tag } = await adminRequest(path, {
|
||
method,
|
||
headers: { 'If-Match': onlineTag, 'Content-Type': 'application/json' },
|
||
body: JSON.stringify(layout),
|
||
});
|
||
onlineTag = tag;
|
||
onlineRevision = data.revision;
|
||
if (method === 'POST') importLayout(data);
|
||
state.revision = data.revision;
|
||
savedDraft = JSON.stringify(state);
|
||
render();
|
||
const message = '已发布 v' + data.revision + ',设备会在下次同步时更新。';
|
||
try {
|
||
await loadHistory();
|
||
return message;
|
||
} catch {
|
||
$('releaseHistory').replaceChildren();
|
||
nextBefore = null;
|
||
return message + ' 版本历史暂时读取失败。';
|
||
}
|
||
}
|
||
|
||
$('loadOnline').onclick = () => {
|
||
if (!confirmDraftReplacement()) return;
|
||
releaseAction(async () => {
|
||
const { data, tag } = await adminRequest('layout');
|
||
importLayout(data);
|
||
savedDraft = JSON.stringify(state);
|
||
render();
|
||
onlineTag = tag;
|
||
onlineRevision = data.revision;
|
||
await loadHistory();
|
||
return '已读取线上 v' + data.revision + ',可返回画布编辑。';
|
||
});
|
||
};
|
||
$('publishLayout').onclick = () => {
|
||
const warnings = validate().issues.filter(issue => issue.lv === 'warn');
|
||
const message = ['将当前画布发布到所有已连接设备?',
|
||
...warnings.slice(0, 5).map(issue => issue.id + ' · ' + issue.msg)];
|
||
if (warnings.length > 5) message.push('其余警告可在校验面板查看');
|
||
if (!confirm(message.join('\n'))) return;
|
||
releaseAction(() => commitLayout('layout', 'PUT', exportJson()));
|
||
};
|
||
$('moreHistory').onclick = () => releaseAction(async () => {
|
||
await loadHistory(true);
|
||
return '当前线上为 v' + onlineRevision;
|
||
});
|
||
</script>
|
||
</body>
|
||
</html>
|