feat(web-ui): 新增首页启动器与地图遮挡感知交互

- 添加首页卡片式应用启动器界面,包含实时视图、登记、
  设置三个入口及对应 SVG 图标资源
- 地图组件新增 ResizeObserver 自动适配容器尺寸变化
- 地图组件引入遮挡区域(occlusion)管理,聚焦时自动
  计算可见填充偏移,避免目标被面板遮挡
- 将地图加载事件从 load 改为 style.load,提升初始化
  可靠性
- 扩展 metrics 接口,返回选中目标像素坐标、遮挡状态、
  画布尺寸等运行时诊断信息
- 补充 web-sys features(HtmlImageElement, Storage,
  PointerEvent, DomRect 等)以支持新 UI 交互
- index.html 新增 workspace/home/registry 样式及资源引用
- .gitignore 忽略 previews 目录与本地编译产物
```
This commit is contained in:
2026-10-22 13:43:58 +08:00
parent 1dfcdb619c
commit 91059cf395
44 changed files with 2787 additions and 3390 deletions
+1 -1
View File
@@ -7,7 +7,7 @@ edition = "2024"
rid-shared = { path = "../rid-shared" }
leptos = { version = "=0.8.22", features = ["csr"] }
wasm-bindgen = "=0.2.129"
web-sys = { version = "0.3", features = ["Window", "Location", "Document", "HtmlElement", "Element", "NodeList", "HtmlInputElement", "HtmlButtonElement", "HtmlAnchorElement", "HtmlDialogElement", "HtmlCanvasElement", "CanvasRenderingContext2d", "File", "FileList", "Blob", "Url", "Navigator", "Clipboard", "Worker", "WorkerOptions", "WorkerType", "MessageEvent", "CustomEvent", "console"] }
web-sys = { version = "0.3", features = ["Window", "Location", "Document", "HtmlElement", "Element", "NodeList", "HtmlInputElement", "HtmlButtonElement", "HtmlAnchorElement", "HtmlDialogElement", "HtmlCanvasElement", "HtmlImageElement", "HtmlSelectElement", "CssStyleDeclaration", "Storage", "KeyboardEvent", "BeforeUnloadEvent", "CanvasRenderingContext2d", "File", "FileList", "Blob", "Url", "Navigator", "Clipboard", "Worker", "WorkerOptions", "WorkerType", "MessageEvent", "CustomEvent", "PointerEvent", "KeyboardEvent", "DomRect", "console"] }
js-sys = "0.3"
wasm-bindgen-futures = "0.4"
gloo-net = "0.6"
+1 -1
View File
@@ -1,2 +1,2 @@
<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><title>FPV-RID · 本地登记与核验</title><link data-trunk rel="rust" data-wasm-opt="0"><link data-trunk rel="copy-file" href="public/app.css"><link data-trunk rel="copy-file" href="public/fpv-rid-icon.png"><link data-trunk rel="copy-dir" href="public/vendor"><link data-trunk rel="copy-file" href="public/map-adapter.js"><link data-trunk rel="copy-file" href="public/map-loader.js"><link data-trunk rel="copy-file" href="public/realtime.css"><link rel="stylesheet" href="/app.css"><link rel="stylesheet" href="/realtime.css"><link rel="stylesheet" href="/vendor/maplibre-gl.css"><script type="module" src="/map-loader.js"></script><link rel="icon" href="/fpv-rid-icon.png"></head><body></body></html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><title>FPV-RID · 本地登记与核验</title><link data-trunk rel="rust" data-wasm-opt="0"><link data-trunk rel="copy-file" href="public/app.css"><link data-trunk rel="copy-file" href="public/fpv-rid-icon.png"><link data-trunk rel="copy-dir" href="public/vendor"><link data-trunk rel="copy-file" href="public/map-adapter.js"><link data-trunk rel="copy-file" href="public/map-loader.js"><link data-trunk rel="copy-file" href="public/realtime.css"><link rel="stylesheet" href="/app.css"><link rel="stylesheet" href="/realtime.css"><link rel="stylesheet" href="/vendor/maplibre-gl.css"><script type="module" src="/map-loader.js"></script><link data-trunk rel="copy-file" href="public/workspace.css"><link data-trunk rel="copy-file" href="public/workspace-native.css"><link data-trunk rel="copy-dir" href="public/wallpapers"><link rel="stylesheet" href="/workspace.css"><link rel="stylesheet" href="/workspace-native.css"><link data-trunk rel="copy-dir" href="public/home"><link data-trunk rel="copy-file" href="public/home.css"><link rel="stylesheet" href="/home.css"><link data-trunk rel="copy-file" href="public/registry.css"><link rel="stylesheet" href="/registry.css"><link rel="icon" href="/fpv-rid-icon.png"></head><body></body></html>
+64
View File
@@ -0,0 +1,64 @@
/* Approved B1 launch screen. All rules are scoped to the home or wallpaper chooser. */
body[data-screen="home"] .reference-top,
body[data-screen="home"] .reference-rail{display:none!important}
.home-top{position:absolute;z-index:15;inset:0 0 auto;height:48px;display:flex;align-items:center;justify-content:space-between;padding:0 32px;background:#0e172570;border-bottom:1px solid #d7e9ff14;backdrop-filter:blur(18px);color:var(--work-text)}
.home-brand{display:flex;align-items:center;gap:10px;font-size:14px;font-weight:600}
.home-brand-mark{width:24px;height:24px;background:#a9c9e516;border:1px solid #bad6f430;border-radius:6px;display:grid;place-items:center;color:var(--work-muted);font-size:12px}
.home-top-note{font-size:12px;color:var(--work-muted)}
.workspace-home-link{display:inline-flex;align-items:center;gap:6px;border:0;background:none;box-shadow:none;padding:5px 2px;color:var(--work-muted);font-size:13px}
.workspace-home-link:hover{color:var(--work-text);background:#809ab516}.workspace-crumb-separator{color:var(--work-muted);opacity:.5;font-size:12px}
.home-launcher.homescreen{position:absolute;inset:48px 0 0!important;display:flex;align-items:center;justify-content:center;height:auto;min-height:0;max-width:none;margin:0!important;padding:36px 40px 60px;background:none!important;border:0;border-radius:0;box-shadow:none;backdrop-filter:none;overflow:auto;color:var(--work-text);text-align:left}
.home-space{width:1070px;max-width:100%;margin:auto 0}
.home-heading{margin:0 0 28px}
.home-heading h1{font-size:27px;font-weight:600;line-height:1.4;letter-spacing:0;text-shadow:none;color:var(--work-text)}
.home-heading p{font-size:14px;line-height:1.8;color:var(--work-muted);margin-top:8px}
.home-cards{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:19px}
.home-card{display:flex;flex-direction:column;align-items:flex-start;min-width:0;min-height:0;padding:24px;border:1px solid #b0cbea2c;border-radius:17px;background:linear-gradient(145deg,#4d657b4d,#1a2a3b73),#0c182494;box-shadow:0 1px 0 #ffffff08 inset,0 14px 40px #00000012;backdrop-filter:blur(22px);text-align:left;white-space:normal;color:var(--work-text);font:inherit;cursor:pointer;transition:transform .18s,background .18s,border-color .18s}
.home-card:hover{background:linear-gradient(145deg,#667f9852,#24384b85),#0c1824a0;border-color:#bfdafa62;transform:translateY(-3px)}
.home-card:focus-visible{outline:2px solid #91bde8;outline-offset:5px}
.home-app-icon{display:block;width:75px;height:75px;flex-shrink:0;filter:drop-shadow(0 5px 8px #0002)}
.home-card-title{display:block;font-size:18px;font-weight:600;line-height:1.5;margin-top:22px}
.home-card-desc{display:block;min-height:50px;font-size:14px;line-height:1.85;color:var(--work-muted);margin-top:8px}
.home-card-preview{display:block;width:100%;margin-top:23px;pointer-events:none}
.home-card .mini{display:block;height:109px;width:100%;border-radius:10px;border:1px solid #b7d1ef1c;background:#08132166;overflow:hidden;position:relative;opacity:.85}
.home-card .registry{display:flex;padding:12px;gap:10px}
.home-card .mini-side{display:block;width:24%;border-right:1px solid #809dbe1f;padding-right:9px;padding-top:3px}
.home-card .mini-side i{display:block;height:6px;width:100%;background:#6b89ac26;margin-bottom:9px;border-radius:2px}
.home-card .mini-side i:first-child{background:#6a9ac54a}
.home-card .mini-body{display:block;width:49%}
.home-card .mini-body b{display:block;width:45%;height:5px;border-radius:2px;background:#a4bcd040;margin:2px 0 9px}
.home-card .mini-body>span{display:block;height:12px;border:1px solid #7e9ab526;border-radius:3px;margin:5px 0}
.home-card .mini-body em{display:block;height:10px;width:39%;margin-top:8px;background:#5784b14a;border-radius:3px;float:right}
.home-card .mini-qr{display:grid;width:22%;place-items:center}
.home-card .mini-qr i{display:block;width:34px;height:34px;border:5px solid #93abc038;border-radius:3px;box-shadow:inset 0 0 0 3px #0e1c2b;position:relative}
.home-card .mini-qr i:before{content:'';position:absolute;top:4px;left:4px;width:6px;height:6px;background:#b7d0e155}
.home-card .radar{background:#122b3459}
.home-card .radar-grid{position:absolute;inset:0;background-image:linear-gradient(#91b1c111 1px,transparent 1px),linear-gradient(90deg,#91b1c111 1px,transparent 1px);background-size:29px 27px}
.home-card .radar-line{position:absolute;left:45px;top:29px;width:140px;height:48px;border-bottom:1px dashed #a1d3d47d;transform:rotate(-17deg)}
.home-card .radar i{width:6px;height:6px;position:absolute;background:#b3ddd6;clip-path:polygon(50% 0,100% 100%,50% 80%,0 100%)}
.home-card .radar i:nth-of-type(1){left:22%;top:65%}.home-card .radar i:nth-of-type(2){left:65%;top:28%}.home-card .radar i:nth-of-type(3){left:79%;top:60%}
.home-card .map-label{position:absolute;top:12px;left:12px;width:42px;height:8px;background:#8caab822;border-radius:3px}
.home-card .appearance{padding:14px 13px;display:grid;grid-template-columns:repeat(3,1fr);gap:8px;align-content:start}
.home-card .wall{display:block;height:44px;border:1px solid #a9bdce26;border-radius:5px}
.home-card .wall-one{background:linear-gradient(135deg,#3b4a5b,#101b29)}.home-card .wall-two{background:linear-gradient(135deg,#41728f,#193a54)}.home-card .wall-three{background:linear-gradient(135deg,#dae4ec,#8c9eaf)}
.home-card .setting-line{display:flex;grid-column:1/4;justify-content:space-between;border-top:1px solid #a7c3e11c;margin-top:4px;padding-top:10px}
.home-card .setting-line i{width:45px;height:4px;background:#8dacc32d;border-radius:3px}.home-card .setting-line i:last-child{width:65px}
.home-card-open{display:flex;align-items:center;justify-content:space-between;width:100%;border-top:1px solid #b1cbe429;padding-top:18px;margin-top:23px;color:var(--work-text);font-size:14px}
.theme-blue .home-top{background:#0d274775}.theme-blue .home-card{background:linear-gradient(145deg,#4a78a84d,#173c6673),#081a30a0;border-color:#b0d6ff36}
.theme-white .home-top{background:#eff6ffd1;border-color:#56718c29}
.theme-white .home-card{background:linear-gradient(145deg,#ffffff70,#e1edf96e),#eff6ffd0;border-color:#ffffffb0;box-shadow:0 1px 0 #fff9 inset,0 14px 35px #263e5b12}
.theme-white .home-card:hover{background:linear-gradient(145deg,#ffffff90,#e1edf98e),#eff6ffd9;border-color:#8eb4dc80}
.theme-white .home-card .mini{background:#c4d4e344;border-color:#6f8eac29}
.theme-white .home-card .mini-side i,.theme-white .home-card .mini-body b,.theme-white .home-card .setting-line i{background:#698baa4d}
.theme-white .home-card .mini-body>span{border-color:#6b8baa3d}.theme-white .home-card .mini-qr i{border-color:#698dad66;box-shadow:none}
.theme-white .home-card .radar-line{border-color:#4b7a947d}.theme-white .home-card .radar i{background:#3d788b}
.theme-white .home-card .radar-grid{background-image:linear-gradient(#587c9d19 1px,transparent 1px),linear-gradient(90deg,#587c9d19 1px,transparent 1px)}
.theme-white .home-card-open{border-color:#6c8da834}
.theme-white .home-launcher.homescreen{background:linear-gradient(130deg,#f1f7ffd9,#d9e7f5bf)!important;backdrop-filter:blur(6px)}
body[data-custom-wallpaper="true"]:not(.theme-white) .home-launcher.homescreen{background:#050f1aad!important}
body[data-custom-wallpaper="true"]:not(.theme-white) .home-heading p{color:#b6c8dc}
.settings-layout .wall-grid{grid-template-columns:repeat(4,minmax(0,1fr))}
@media(max-width:1100px){.home-launcher.homescreen{padding:35px 30px 55px}.home-cards{gap:15px}.home-card{padding:21px}.home-card-desc{font-size:14px}.home-card .mini{height:100px}}
@media(max-width:760px){.home-top{padding:0 20px}.home-launcher.homescreen{align-items:flex-start;padding:34px 22px 40px}.home-space{margin:0}.home-heading{margin-bottom:24px}.home-heading h1{font-size:25px}.home-cards{grid-template-columns:1fr;gap:15px}.home-card{display:grid;grid-template-columns:65px minmax(0,1fr) 19px;gap:4px 17px;padding:19px;min-height:134px}.home-app-icon{width:65px;height:65px;grid-row:1/3}.home-card-title{grid-column:2;grid-row:1;margin:0;align-self:end;font-size:17px}.home-card-desc{grid-column:2;grid-row:2;margin:0;min-height:0;align-self:start;font-size:13px}.home-card-preview{display:none}.home-card-open{grid-column:3;grid-row:1/3;display:block;overflow:hidden;width:19px;height:22px;font-size:0;padding:0;margin:0;border:0}.home-card-open svg{display:block;position:absolute}.settings-layout .wall-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}
@media(prefers-reduced-motion:reduce){.home-card{transition:none}.home-card:hover{transform:none}}
@media(max-width:760px){.workspace-home-link{min-width:24px;padding:4px}.workspace-home-link>span,.workspace-crumb-separator{display:none}}
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" class="app-icon" width="80" height="80" viewBox="0 0 92 92" aria-hidden="true"><defs><linearGradient id="base-realtime" x2="0" y2="1"><stop stop-color="#398b87"></stop><stop offset="1" stop-color="#205c63"></stop></linearGradient></defs><rect x="4" y="5" width="84" height="84" rx="21" fill="#000" opacity=".16"></rect><rect x="4" y="3" width="84" height="84" rx="21" fill="url(#base-realtime)" stroke="#d8edff" stroke-opacity=".3"></rect><path d="M25 5h42c11 0 19 8 19 19" fill="none" stroke="#e3f4ff" stroke-opacity=".22"></path><circle cx="46" cy="45" r="25" fill="none" stroke="#dcfbf6" stroke-width="3"></circle><circle cx="46" cy="45" r="15" fill="none" stroke="#a4d4ce" stroke-width="1.5"></circle><path d="M46 20v25l18-18" fill="#e2fff3" fill-opacity=".19" stroke="#e4fff8" stroke-width="2"></path><path d="M46 16v7m0 45v7M16 45h7m45 0h7" stroke="#bce8df" stroke-width="2"></path><circle cx="34" cy="53" r="3.5" fill="#e5fff8"></circle><circle cx="59" cy="55" r="2.5" fill="#b8e5df"></circle></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" class="app-icon" width="80" height="80" viewBox="0 0 92 92" aria-hidden="true"><defs><linearGradient id="base-register" x2="0" y2="1"><stop stop-color="#3f83c7"></stop><stop offset="1" stop-color="#24588d"></stop></linearGradient></defs><rect x="4" y="5" width="84" height="84" rx="21" fill="#000" opacity=".16"></rect><rect x="4" y="3" width="84" height="84" rx="21" fill="url(#base-register)" stroke="#d8edff" stroke-opacity=".3"></rect><path d="M25 5h42c11 0 19 8 19 19" fill="none" stroke="#e3f4ff" stroke-opacity=".22"></path><path d="M30 20h22l12 12v36H30Z" fill="#edf6ff"></path><path d="M52 20v13h12" fill="#a8c9ed"></path><rect x="23" y="30" width="6" height="35" rx="3" fill="#90b5df"></rect><path d="M38 43h17m-17 8h17m-17 8h10" stroke="#3975b2" stroke-width="3" stroke-linecap="round"></path><circle cx="62" cy="63" r="10" fill="#a6d4ff" stroke="#3c78b7" stroke-width="2"></circle><path d="m57 63 3 3 6-7" fill="none" stroke="#24588f" stroke-width="2.5" stroke-linecap="round"></path></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" class="app-icon" width="80" height="80" viewBox="0 0 92 92" aria-hidden="true"><defs><linearGradient id="base-settings" x2="0" y2="1"><stop stop-color="#91a5b8"></stop><stop offset="1" stop-color="#556c82"></stop></linearGradient></defs><rect x="4" y="5" width="84" height="84" rx="21" fill="#000" opacity=".16"></rect><rect x="4" y="3" width="84" height="84" rx="21" fill="url(#base-settings)" stroke="#d8edff" stroke-opacity=".3"></rect><path d="M25 5h42c11 0 19 8 19 19" fill="none" stroke="#e3f4ff" stroke-opacity=".22"></path><path d="m42 19 10 0 3 8 8 4 8-1 5 9-5 7 0 9 5 7-5 9-8-1-8 4-3 8H42l-3-8-8-4-8 1-5-9 5-7v-9l-5-7 5-9 8 1 8-4 3-8Z" transform="translate(8 0) scale(.84)" fill="#edf3f9"></path><circle cx="47" cy="43" r="14" fill="#50677e"></circle><circle cx="47" cy="43" r="8.5" fill="#a8bbce"></circle><circle cx="47" cy="43" r="4" fill="#e9f1fa"></circle></svg>

After

Width:  |  Height:  |  Size: 917 B

+31 -6
View File
@@ -4,7 +4,8 @@ maplibre.setWorkerUrl('/vendor/maplibre-gl-worker.mjs');
let map, layer, latest, ids = [], selected = '', pending = false;
let frameTimes = [], lastFrame = 0;
let marker=null, history=[], lastTrail=0;
let centered=false, workerWasmBytes=0;
let centered=false, workerWasmBytes=0, resizeObserver;
let occlusion={top:0,right:0,bottom:0,left:0};
function shader(gl, type, source) {
const s=gl.createShader(type);gl.shaderSource(s,source);gl.compileShader(s);
if (!gl.getShaderParameter(s,gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));return s;
@@ -20,6 +21,7 @@ function create(container) {
{id:'tdt-base',type:'raster',source:'tdt-base'},
{id:'tdt-labels',type:'raster',source:'tdt-labels'}
]}});
resizeObserver?.disconnect(); resizeObserver=new ResizeObserver(()=>map?.resize());resizeObserver.observe(document.getElementById(container));
map.addControl(new maplibre.AttributionControl({compact:true}),'bottom-right');
layer={id:'rid-targets',type:'custom',renderingMode:'2d',
onAdd(map,gl){
@@ -51,7 +53,7 @@ function create(container) {
},
onRemove(map,gl){gl.deleteBuffer(this.shape);gl.deleteBuffer(this.instances);gl.deleteVertexArray(this.vao);gl.deleteProgram(this.program);gl.deleteShader(this.vs);gl.deleteShader(this.fs);}
};
map.on('load',()=>{
map.on('style.load',()=>{
// Mission Control tactical radar grid & range rings
const features=[];
for(let lon=118;lon<=122;lon+=.05)features.push({type:'Feature',geometry:{type:'LineString',coordinates:[[lon,28],[lon,32]]},properties:{}});
@@ -95,9 +97,32 @@ function flush(){
map.getSource('selected-trail')?.setData({type:'FeatureCollection',features:history.length<2?[]:[{type:'Feature',properties:{},geometry:{type:'LineString',coordinates:history.map(p=>p.coordinate)}}]});}
}else{marker?.remove();marker=null;history=[];map.getSource('selected-trail')?.setData({type:'FeatureCollection',features:[]});}
}
function update(positions,newIds){latest=positions;if(newIds)ids=Array.from(newIds);if(!centered&&latest.length>=4){centered=true;map.jumpTo({center:[latest[0],latest[1]]});}if(!pending){pending=true;requestAnimationFrame(flush);}}
function update(positions,newIds){latest=positions;if(newIds)ids=Array.from(newIds);if(!centered&&latest.length>=4){centered=true;focusCoordinate([latest[0],latest[1]], false);}if(!pending){pending=true;requestAnimationFrame(flush);}}
function select(id){if(selected!==id){selected=id;history=[];flush();}const i=ids.indexOf(id);return i>=0&&latest?Array.from(latest.slice(i*4,i*4+4)):[];}
function metrics(){const sorted=[...frameTimes].sort((a,b)=>a-b);const gl=layer?.gl;const ext=gl?.getExtension('WEBGL_debug_renderer_info');return {samples:sorted.length,drawSubmissionIntervalP95Ms:sorted[Math.floor(sorted.length*.95)]||0,targets:ids.length,renderer:ext?gl.getParameter(ext.UNMASKED_RENDERER_WEBGL):'unavailable',selectedTrailPoints:history.length,workerWasmBytes};}
function connection(connected){const canvas=document.querySelector('.rt-map');if(canvas)canvas.dataset.stale=connected?'false':'true';}
function metrics(){const sorted=[...frameTimes].sort((a,b)=>a-b);const gl=layer?.gl;const ext=gl?.getExtension('WEBGL_debug_renderer_info');const projected=map&&latest&&ids.includes(selected)?map.project([latest[ids.indexOf(selected)*4],latest[ids.indexOf(selected)*4+1]]):null;return {selectedPixel:projected?{x:projected.x,y:projected.y}:null,occlusion:{...occlusion},mapReady:!!layer?.gl,styleReady:map?.isStyleLoaded()||false,mapCanvasWidth:map?.getCanvas().clientWidth||0,mapCanvasHeight:map?.getCanvas().clientHeight||0,samples:sorted.length,drawSubmissionIntervalP95Ms:sorted[Math.floor(sorted.length*.95)]||0,targets:ids.length,renderer:ext?gl.getParameter(ext.UNMASKED_RENDERER_WEBGL):'unavailable',selectedTrailPoints:history.length,workerWasmBytes};}
function connection(connected){const canvas=document.getElementById('rt-map');if(canvas)canvas.dataset.stale=connected?'false':'true';}
function refresh(){for(const [id,layer]of [['tdt-base','img_w'],['tdt-labels','cia_w']])map?.getSource(id)?.setTiles([`/api/maps/tile/${layer}/{z}/{x}/{y}`]);}
window.ridMap={workerMemory(bytes){if(Number.isFinite(bytes))workerWasmBytes=bytes;},create,update,select,metrics,connection,refresh,zoomIn(){if(map)map.zoomIn();},zoomOut(){if(map)map.zoomOut();},centerSelected(){if(!map||!latest||!selected)return;const index=ids.indexOf(selected);if(index>=0){map.flyTo({center:[latest[index*4],latest[index*4+1]],zoom:Math.max(map.getZoom(),13),essential:true});}},resetBearing(){if(map)map.resetNorthPitch({duration:400});},toggle3d(){if(!map)return;const p=map.getPitch();map.easeTo({pitch:p>10?0:55,duration:500});},destroy(){marker?.remove();marker=null;history=[];map?.remove();map=null;layer=null;latest=null;ids=[];centered=false;}};
function setOcclusion(value){
occlusion=Object.fromEntries(['top','right','bottom','left'].map(k=>[k,Number.isFinite(value?.[k])?Math.max(0,value[k]):0]));
}
function visiblePadding(){
if(!map)return {top:0,right:0,bottom:0,left:0};
const w=map.getCanvas().clientWidth,h=map.getCanvas().clientHeight;
const p={...occlusion};
// Hidden mobile overlays may have just closed; measure visible panels at focus time.
const root=document.getElementById('rt-layout')?.getBoundingClientRect();
if(root){const scale=Math.max(.01,root.width/w);for(const [id,side] of [['rt-directory','left'],['rt-details','right']]){const el=document.getElementById(id);const r=el?.getBoundingClientRect();p[side]=r?.height?side==='left'?(r.right-root.left)/scale+12:(root.right-r.left)/scale+12:0;}
const dock=document.getElementById('rt-dock')?.getBoundingClientRect();p.bottom=dock?.height?(root.bottom-dock.top)/scale+40:116;
}
if(p.left+p.right>w-80){p.left=0;p.right=0;}
if(p.top+p.bottom>h-80){p.top=0;p.bottom=0;}
return p;
}
function focusCoordinate(center,animate=true){
if(!map)return;
const p=visiblePadding();
const options={center,offset:[(p.left-p.right)/2,(p.top-p.bottom)/2]};
if(animate)map.flyTo({...options,zoom:Math.max(map.getZoom(),13),duration:400});else map.easeTo({...options,duration:0});
}
function centerSelected(){if(!map||!latest||!selected)return;const i=ids.indexOf(selected);if(i>=0)focusCoordinate([latest[i*4],latest[i*4+1]]);}
window.ridMap={workerMemory(bytes){if(Number.isFinite(bytes))workerWasmBytes=bytes;},create,update,select,metrics,connection,refresh,setOcclusion,focusVisible(){requestAnimationFrame(()=>requestAnimationFrame(centerSelected));},zoomIn(){if(map)map.zoomIn();},zoomOut(){if(map)map.zoomOut();},centerSelected,resetBearing(){if(map)map.resetNorthPitch({duration:400});},toggle3d(){if(!map)return;const p=map.getPitch();map.easeTo({pitch:p>10?0:55,duration:500});},destroy(){resizeObserver?.disconnect();resizeObserver=null;marker?.remove();marker=null;history=[];map?.remove();map=null;layer=null;latest=null;ids=[];centered=false;occlusion={top:0,right:0,bottom:0,left:0};}};
+124
View File
@@ -0,0 +1,124 @@
/* Approved B registration workspace. Kept separate from home, map and appearance. */
.registry-workspace{display:grid;grid-template-columns:292px minmax(0,1fr);height:calc(100dvh - 48px);min-height:0;overflow:hidden;color:var(--work-text);font-size:14px}
.registry-workspace *,#edit-dialog *{box-sizing:border-box}
.registry-workspace button,#edit-dialog button{border:1px solid var(--work-line);background:color-mix(in srgb,var(--work-text) 5%,transparent);color:var(--work-text);border-radius:9px;padding:9px 12px;font-size:13px;line-height:1.5;box-shadow:none;transition:background .15s;white-space:normal;min-width:0}
.registry-workspace button:hover:not(:disabled),#edit-dialog button:hover:not(:disabled){background:color-mix(in srgb,var(--work-text) 12%,transparent)}
.registry-workspace button:disabled,#edit-dialog button:disabled{opacity:.45;cursor:default}
.registry-workspace :focus-visible,#edit-dialog :focus-visible{outline:2px solid var(--mc-accent);outline-offset:3px}
.registry-workspace input:not([type=checkbox]),#edit-dialog input:not([type=checkbox]){display:block;width:100%;min-width:0;height:44px;border:1px solid var(--work-line);background:var(--work-input);color:var(--work-text);border-radius:8px;padding:11px 12px;font-size:14px;box-shadow:none}
.registry-workspace input::placeholder,#edit-dialog input::placeholder{color:var(--work-muted);font-size:13px}
.registry-workspace input[type=checkbox],#edit-dialog input[type=checkbox]{width:16px;height:16px;accent-color:#639dea;flex-shrink:0;margin:0}
.registry-workspace h1,.registry-workspace h2,.registry-workspace h3,#edit-dialog h2{color:var(--work-text);text-shadow:none;letter-spacing:0}
.registry-workspace .primary,#edit-dialog .primary{background:#3284df;color:#fff;border-color:#83b9f46b;font-weight:600}
.registry-workspace .primary:hover:not(:disabled),#edit-dialog .primary:hover:not(:disabled){background:#4392e9}
.registry-workspace .history-panel{display:flex;flex-direction:column;gap:16px;background:#92b3d108;border-right:1px solid var(--work-line);padding:24px 18px;overflow:auto;min-width:0;scrollbar-width:thin;position:relative}
.registry-workspace .history-heading{display:flex;align-items:center;justify-content:space-between}
.registry-workspace .history-heading h2{margin:0;font-size:17px;font-weight:600}
.registry-workspace #refresh-list{border:0;background:none;font-size:22px;padding:0 6px;min-height:32px}
.registry-workspace .history-search{position:relative}.registry-workspace .history-search input{font-size:13px}
.registry-workspace #search-count{display:block;color:var(--work-muted);font-size:12px}.registry-workspace #search-count:empty{display:none}
.registry-workspace #new-registration{margin:0;width:100%;min-height:42px}
.registry-workspace .history-toolbar{display:flex;justify-content:space-between;gap:10px;align-items:center}
.registry-workspace #selection-toggle,.registry-workspace #export-toggle{font-size:12px;padding:7px 11px;min-height:34px}
.registry-workspace .select-all{display:flex;align-items:center;gap:8px;font-size:12px;color:var(--work-muted)}
.registry-workspace .history-message,.registry-workspace .history-empty,.registry-workspace .archive-warning{margin:0;color:var(--work-muted);font-size:12px;line-height:1.8;overflow-wrap:anywhere}
.registry-workspace .history-message:empty{display:none}
.registry-workspace .history-cards{display:flex;flex-direction:column;gap:13px}
.registry-workspace .archive-card{margin:0;padding:15px;border:1px solid var(--work-line);background:#9fb7d009;border-radius:12px;box-shadow:none;min-height:0;position:relative;overflow:visible;color:var(--work-text)}
.registry-workspace .archive-card.is-current{box-shadow:inset 3px 0 var(--mc-accent);background:#80b3df12}
.registry-workspace .archive-card.selected{border-color:var(--mc-accent);background:#74a8e41a}
.registry-workspace .archive-card-head{display:flex;align-items:center;gap:8px;justify-content:space-between}
.registry-workspace .archive-card h3{margin:0;font-size:14px;font-weight:600;overflow-wrap:anywhere;min-width:0}
.registry-workspace .archive-select{display:flex;align-items:center;gap:7px;margin-bottom:9px;font-size:12px;color:var(--work-muted)}
.registry-workspace .archive-more{font-size:19px;border:0;background:none;padding:0 6px;min-width:30px;min-height:30px}
.registry-workspace .archive-card strong{display:block;font:12px/1.7 Consolas,monospace;color:var(--work-muted);margin:5px 0 7px;overflow-wrap:anywhere}
.registry-workspace .archive-card p{font-size:12px;color:var(--work-muted);line-height:1.7;margin:0;overflow-wrap:anywhere}
.registry-workspace .archive-card-foot{display:flex;justify-content:space-between;align-items:center;border-top:1px solid var(--work-line);padding-top:9px;margin-top:12px;gap:8px}
.registry-workspace .archive-card-foot time{font-size:12px;color:var(--work-muted)}
.registry-workspace .archive-card-foot button{border:0;background:none;padding:3px 0;font-size:12px}
.registry-workspace .registry-popup{position:relative;padding:6px;background:var(--work-panel);border:1px solid var(--work-line);border-radius:10px;box-shadow:0 8px 25px #0003;display:flex;flex-direction:column;gap:2px;z-index:2;margin-top:8px;max-height:calc(100dvh - 100px);overflow:auto}
.registry-workspace .registry-popup button,.registry-workspace .registry-popup a{background:none;border:0;padding:8px;text-align:left;display:block;font-size:12px;color:var(--work-text);text-decoration:none;border-radius:5px;overflow-wrap:anywhere}
.registry-workspace .registry-popup a:hover{background:#8db3da18}.registry-workspace .registry-popup p{font-size:12px;color:var(--work-muted);padding:5px 8px;margin:0}
.registry-workspace .registry-popup .delete-record{color:#edb5ab}.theme-white .registry-workspace .registry-popup .delete-record{color:#a13930}
.registry-workspace .export-controls{max-width:100%;text-align:right}.registry-workspace .export-controls .registry-popup{position:absolute;left:18px;right:18px;text-align:left}
.registry-workspace .pagination{margin-top:auto;padding-top:16px;border-top:1px solid var(--work-line);display:flex;flex-direction:column;gap:10px;font-size:12px;color:var(--work-muted)}
.registry-workspace .pagination>div{display:flex;gap:8px}.registry-workspace .pagination button{font-size:12px;padding:5px 9px}
.registry-workspace .registration-scroll{overflow:auto;padding:26px 38px 0;min-width:0;scroll-padding-block:20px 120px;scrollbar-width:thin}
.registry-workspace .registration-main{width:100%;max-width:950px;margin:auto;min-width:0}
.registry-workspace .registration-heading{display:flex;justify-content:space-between;align-items:center;margin-bottom:24px;gap:15px}
.registry-workspace .registration-heading h1{font-size:23px;font-weight:600;margin:0 0 5px;line-height:1.4}
.registry-workspace .registration-heading p{font-size:13px;color:var(--work-muted);margin:0}
.registry-workspace .registration-heading>span{font-size:12px;color:var(--work-muted);white-space:nowrap}
.registry-workspace .registry-group{border:1px solid var(--work-line);background:linear-gradient(140deg,#8bb5dc08,#07162422);border-radius:14px;padding:19px 20px;margin-bottom:17px;min-width:0}
.theme-white .registry-workspace .registry-group{background:#ffffff35}
.registry-workspace .registry-group h2{font-size:15px;font-weight:600;margin:0}
.registry-workspace .registry-group-heading{display:flex;justify-content:space-between;align-items:center;gap:10px;margin-bottom:17px}
.registry-workspace .registry-group-heading>span{font-size:12px;color:var(--work-muted)}
.registry-workspace .registration-fields,#edit-dialog .registration-fields{display:grid;grid-template-columns:1fr 1fr;gap:18px 16px}
.registry-workspace .registration-field,#edit-dialog .registration-field{display:flex;flex-direction:column;gap:8px;min-width:0}
.registry-workspace .registration-field.full{grid-column:1/-1}
.registry-workspace label,#edit-dialog label{font-size:13px;line-height:1.5;color:var(--work-text)}
.registry-workspace label small{font-size:12px;color:var(--work-muted);font-weight:400;margin-left:5px}
.registry-workspace .registry-help,#edit-dialog .registry-help{font-size:12px;line-height:1.8;color:var(--work-muted);margin:10px 0 0;overflow-wrap:anywhere}
.registry-workspace .registration-number{display:grid;grid-template-columns:1fr 1fr;gap:24px;align-items:center}
.registry-workspace .registration-prefix{display:flex;align-items:center;border:1px solid var(--work-line);border-radius:8px;background:var(--work-input);min-width:0;height:44px}
.registry-workspace .registration-prefix>span{font:13px Consolas,monospace;color:var(--work-muted);padding:0 13px;border-right:1px solid var(--work-line)}
.registry-workspace .registration-prefix input{border:0;background:none}
.registry-workspace .registration-photos,#edit-dialog .edit-photos{display:grid;grid-template-columns:1fr 1fr;gap:14px}
.registry-workspace .photo-slot,#edit-dialog .photo-slot{min-width:0}
.registry-workspace .photo-pick,#edit-dialog .photo-pick{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:5px;border:1px dashed var(--work-line);background:#86a9cc06;width:100%;min-height:110px;position:relative;overflow:hidden;padding:15px}
.photo-pick>strong{font-size:13px;font-weight:500}.photo-pick>span:not(.photo-plus){font-size:12px;color:var(--work-muted);overflow-wrap:anywhere;max-width:100%}
.photo-pick .photo-plus{font-size:23px;color:var(--work-muted);line-height:1.2}
.registry-workspace .photo-pick img,#edit-dialog .photo-pick img{width:100%;height:90px;object-fit:contain;border-radius:6px;margin-bottom:5px}
.registry-workspace .photo-slot-actions,#edit-dialog .photo-slot-actions{display:flex;justify-content:flex-end;margin-top:5px}
.registry-workspace .photo-slot-actions button,#edit-dialog .photo-slot-actions button{font-size:12px;padding:3px 7px;background:none;border:0}
.registry-workspace .photo-status,#edit-dialog .photo-status{font-size:12px;line-height:1.7;color:var(--work-muted);margin:5px 0 0;overflow-wrap:anywhere}.photo-status:empty{display:none}
.registry-workspace .form-message,#edit-dialog .form-message{font-size:13px;color:var(--work-muted);line-height:1.8;margin:12px 0;overflow-wrap:anywhere}
.registry-workspace .form-message:empty{display:none}
.registry-workspace .error,#edit-dialog .error{color:#f0b9ac}.theme-white .registry-workspace .error,.theme-white #edit-dialog .error{color:#9b3728}
.registry-workspace #register-form{display:flex;flex-direction:column;min-width:0}
.registry-workspace .registration-savebar{position:sticky;bottom:0;display:flex;align-items:center;justify-content:space-between;gap:15px;flex-wrap:wrap;padding:16px 0;background:var(--work-panel);backdrop-filter:blur(20px);border-top:1px solid var(--work-line);margin-top:10px;z-index:3;box-shadow:0 -8px 18px #0714210c}
.registry-workspace .registration-savebar>span{font-size:12px;color:var(--work-muted)}
.registry-workspace #register-button{margin:0;padding:12px 19px;min-height:46px;width:auto;font-size:14px}
.registry-workspace #register-form>.registry-group:last-of-type{margin-bottom:25px}
.registry-workspace .result-panel>h2{margin:0 0 12px}
.registry-workspace .empty-state{display:flex;align-items:center;gap:20px;padding:0;min-height:70px;text-align:left}
.registry-workspace .empty-glyph{display:grid;place-items:center;width:68px;height:68px;flex-shrink:0;border:1px dashed var(--work-line);border-radius:9px;color:var(--work-muted)}
.registry-workspace .empty-glyph svg{width:36px;height:36px}.registry-workspace .empty-state b{font-size:14px;font-weight:500}
.registry-workspace .empty-state p{color:var(--work-muted);font-size:12px;line-height:1.8;margin:5px 0 0}
.registry-workspace .empty-state ol{color:var(--work-muted);font-size:12px;line-height:2.2;border-left:1px solid var(--work-line);padding-left:30px;margin:0 0 0 auto;flex-shrink:0}
.registry-workspace .record-result{display:grid;grid-template-columns:170px minmax(0,1fr);gap:12px 23px;min-width:0}
.registry-workspace .qr-stage{width:170px;max-width:100%;background:white;padding:8px;border-radius:12px;grid-column:1;grid-row:1/5;align-self:start;margin:0}
.registry-workspace .qr-stage svg{display:block;width:100%;height:auto}
.registry-workspace .record-kicker{color:var(--work-muted);font-size:12px;overflow-wrap:anywhere}.registry-workspace .uas-display{font-size:20px;color:var(--work-text);line-height:1.4;overflow-wrap:anywhere}
.registry-workspace .result-fields{display:flex;flex-wrap:wrap;gap:10px 25px;margin:0}.registry-workspace .result-fields>div{display:block;border:0;padding:0}.registry-workspace .result-fields dt{font-size:12px;color:var(--work-muted)}.registry-workspace .result-fields dd{font-size:13px;color:var(--work-text);margin:4px 0 0;overflow-wrap:anywhere}
.registry-workspace .saved-photos{display:flex;gap:10px;grid-column:2}.registry-workspace .saved-photos a{color:var(--work-muted);font-size:12px}.registry-workspace .saved-photos img{width:70px;height:50px;object-fit:cover;border-radius:5px;display:block}
.registry-workspace .url-box{grid-column:1/-1;background:var(--work-input);border:1px solid var(--work-line);border-radius:8px;padding:10px 12px;display:flex;flex-wrap:wrap;gap:8px;font-size:12px;color:var(--work-muted);min-width:0}.registry-workspace .url-box code{font-size:12px;overflow-wrap:anywhere;word-break:break-all;color:var(--work-text)}
.registry-workspace .result-actions{display:flex;flex-wrap:wrap;gap:9px;grid-column:1/-1}.registry-workspace .result-actions a{border:1px solid var(--work-line);background:#8baed011;border-radius:9px;padding:9px 12px;font-size:13px;color:var(--work-text);text-decoration:none}
.registry-workspace .result-tip{font-size:12px;line-height:1.8;color:var(--work-muted);margin:0;grid-column:1/-1}
#edit-dialog{color:var(--work-text);background:var(--work-panel);backdrop-filter:blur(30px);border:1px solid var(--work-line);width:650px;max-width:calc(100vw - 30px);max-height:85dvh;overflow:auto;border-radius:17px;padding:25px}
#edit-dialog::backdrop{background:#020b1966}#edit-dialog h2{font-size:18px;margin:0 0 10px}#edit-dialog header{margin-bottom:22px}#edit-dialog #edit-identity{font-size:13px;color:var(--work-muted);overflow-wrap:anywhere}
#edit-dialog .edit-photos{margin-top:22px}#edit-dialog fieldset{border:1px solid var(--work-line);border-radius:10px;padding:12px;min-width:0}#edit-dialog legend{font-size:13px;padding:0 5px}#edit-dialog .edit-delete{display:flex;align-items:center;gap:7px;font-size:12px;margin-top:12px}
#edit-dialog .result-actions{display:flex;justify-content:flex-end;gap:9px;margin-top:20px}
@media(max-width:1200px){.registry-workspace{grid-template-columns:260px minmax(0,1fr)}.registry-workspace .registration-scroll{padding:23px 24px 0}.registry-workspace .empty-state ol{display:none}.registry-workspace .registration-number{grid-template-columns:1fr;gap:0}}
@media(max-width:760px){.registry-workspace{height:auto;min-height:calc(100dvh - 48px);display:flex;flex-direction:column;overflow:visible}.registry-workspace .registration-scroll{order:0;overflow:visible;padding:22px 18px 0}.registry-workspace .history-panel{order:1;overflow:visible;border-right:0;border-top:1px solid var(--work-line);padding:24px 18px}.registry-workspace .registration-heading>span{display:none}.registry-workspace .registration-heading h1{font-size:21px}.registry-workspace .registration-fields,#edit-dialog .registration-fields{grid-template-columns:1fr}.registry-workspace .registry-group{padding:16px}.registry-workspace .registry-group-heading{align-items:flex-start}.registry-workspace .registry-group-heading>span{font-size:12px;text-align:right}.registry-workspace .registration-photos,#edit-dialog .edit-photos{grid-template-columns:1fr}.registry-workspace .registration-savebar{padding:13px 0;gap:8px}.registry-workspace #register-button{width:100%}.registry-workspace .empty-state{gap:13px}.registry-workspace .empty-glyph{width:46px;height:55px}.registry-workspace .record-result{display:flex;flex-direction:column}.registry-workspace .qr-stage{align-self:center;width:180px}.registry-workspace .export-controls .registry-popup{left:18px;right:18px}#edit-dialog{padding:20px}.registry-workspace .registration-heading p{font-size:12px}}
@media(prefers-reduced-motion:reduce){.registry-workspace button,#edit-dialog button{transition:none}}
.registry-workspace [data-selecting="false"] .archive-select{display:none}
.registry-workspace [data-photo-keep],#edit-dialog [data-photo-keep]{font-size:12px;background:none;padding:4px 7px;margin-top:5px}
.registry-workspace .history-panel{margin:0}
.registry-workspace .history-search{width:100%;flex:none}
.registry-workspace .history-search input{padding:10px 12px}
.registry-workspace #search-count{position:static;transform:none;margin-top:5px;font-size:12px}
.registry-workspace .archive-card:hover{transform:none;box-shadow:none}
.registry-workspace .empty-state{height:auto;border:0;border-radius:0;background:none;flex-direction:row;justify-content:flex-start;color:var(--work-text)}
.registry-workspace .empty-glyph{margin:0;box-shadow:none;background:none}
.registry-workspace .record-result{align-items:stretch}
.registry-workspace .qr-stage{height:auto;aspect-ratio:1;box-shadow:none;border:0}
.registry-workspace .record-kicker{margin:0;letter-spacing:0;text-transform:none;font-weight:400}
.registry-workspace .uas-display{margin:0;text-shadow:none;letter-spacing:0;font-weight:600}
.registry-workspace .result-fields{border:0;min-width:0}
.registry-workspace .result-fields dd{text-align:left;font-weight:500}
#edit-dialog fieldset{background:none}
.registry-workspace .registration-field label,#edit-dialog .registration-field label{margin:0;font-weight:500}
.registry-workspace .photo-pick:has(img:not([hidden])) .photo-plus,#edit-dialog .photo-pick:has(img:not([hidden])) .photo-plus{display:none}
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1600" height="1140" viewBox="0 0 1600 1140"><defs><radialGradient id="base" cx=".35" cy=".05" r="1"><stop stop-color="#353d49"/><stop offset=".42" stop-color="#131923"/><stop offset="1" stop-color="#080b11"/></radialGradient><linearGradient id="s1" x1="0" y1="0" x2="1" y2=".7"><stop stop-color="#c3cbd2" stop-opacity=".65"/><stop offset=".12" stop-color="#596675" stop-opacity=".26"/><stop offset=".35" stop-color="#2b3441" stop-opacity=".2"/><stop offset="1" stop-color="#02060c" stop-opacity=".85"/></linearGradient><linearGradient id="edge" x1="0" y1="0" x2=".4" y2="1"><stop stop-color="#e2eaf4" stop-opacity=".4"/><stop offset=".55" stop-color="#8995a9" stop-opacity=".03"/><stop offset="1" stop-color="#202a3c" stop-opacity="0"/></linearGradient><filter id="soft"><feGaussianBlur stdDeviation="25"/></filter><filter id="grain"><feTurbulence type="fractalNoise" baseFrequency=".7" numOctaves="3" stitchTiles="stitch"/><feColorMatrix type="saturate" values="0"/><feComponentTransfer><feFuncA type="linear" slope=".035"/></feComponentTransfer><feBlend in="SourceGraphic" mode="soft-light"/></filter><radialGradient id="shade"><stop offset=".2" stop-color="#000" stop-opacity="0"/><stop offset="1" stop-color="#000" stop-opacity=".23"/></radialGradient></defs><rect width="1600" height="1140" fill="url(#base)"/><ellipse cx="400" cy="-250" rx="780" ry="510" fill="#9daebd" opacity=".12" filter="url(#soft)"/><path d="M-250-80C300-100 580 100 665 470S700 1030 1280 1270H-200Z" fill="url(#s1)"/><path d="M-250-80C300-100 580 100 665 470S700 1030 1280 1270" fill="none" stroke="url(#edge)" stroke-width="2"/><path d="M1560-130C1250 100 1210 410 1390 720S1600 1000 1630 1250H1800V-130Z" fill="#02050b" opacity=".45"/><path d="M1560-130C1250 100 1210 410 1390 720S1600 1000 1630 1250" fill="none" stroke="#a8b8cc" stroke-opacity=".13" stroke-width="1.2"/><rect width="1600" height="1140" fill="url(#shade)"/><rect width="1600" height="1140" filter="url(#grain)" opacity=".08"/></svg>

After

Width:  |  Height:  |  Size: 2.0 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1600" height="1140" viewBox="0 0 1600 1140"><defs><linearGradient id="base" x2=".8" y2="1"><stop stop-color="#101926"/><stop offset=".55" stop-color="#0b1120"/><stop offset="1" stop-color="#03070f"/></linearGradient><linearGradient id="silk" x1="0" y1="1" x2=".8" y2="0"><stop stop-color="#102037"/><stop offset=".4" stop-color="#132b50"/><stop offset=".64" stop-color="#365c82"/><stop offset=".72" stop-color="#779ebc"/><stop offset=".735" stop-color="#a4bdd0"/><stop offset=".75" stop-color="#385978"/><stop offset=".86" stop-color="#142841"/><stop offset="1" stop-color="#08121f"/></linearGradient><linearGradient id="fold" x1="0" y1="0" x2=".8" y2=".8"><stop stop-color="#080f1a"/><stop offset=".54" stop-color="#1c304a"/><stop offset=".68" stop-color="#4a6580"/><stop offset=".72" stop-color="#75899c"/><stop offset=".74" stop-color="#23374d"/><stop offset="1" stop-color="#090f19"/></linearGradient><filter id="grain"><feTurbulence type="fractalNoise" baseFrequency=".7" numOctaves="3" stitchTiles="stitch"/><feColorMatrix type="saturate" values="0"/><feComponentTransfer><feFuncA type="linear" slope=".035"/></feComponentTransfer><feBlend in="SourceGraphic" mode="soft-light"/></filter><radialGradient id="shade"><stop offset=".2" stop-color="#000" stop-opacity="0"/><stop offset="1" stop-color="#000" stop-opacity=".23"/></radialGradient></defs><rect width="1600" height="1140" fill="url(#base)"/><path d="M-200 1250C-60 920 650 1040 980 620S1130-70 1800-170V1250Z" fill="url(#silk)"/><path d="M-160 1190C180 830 700 1100 1140 680S1350 0 1770-110V1250Z" fill="url(#fold)" opacity=".8"/><path d="M-200 1250C-60 920 650 1040 980 620S1130-70 1800-170" fill="none" stroke="#d9e9f2" stroke-opacity=".2" stroke-width="1"/><rect width="1600" height="1140" fill="url(#shade)"/><rect width="1600" height="1140" filter="url(#grain)" opacity=".08"/></svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1600" height="1140" viewBox="0 0 1600 1140"><defs><radialGradient id="base" cx=".8" cy=".1"><stop stop-color="#3c424b"/><stop offset=".45" stop-color="#1b2028"/><stop offset="1" stop-color="#0b0f17"/></radialGradient><linearGradient id="plane" x1="0" y1="0" x2="1" y2=".8"><stop stop-color="#d4dee5" stop-opacity=".5"/><stop offset=".25" stop-color="#7d8a9b" stop-opacity=".12"/><stop offset="1" stop-color="#1a212d" stop-opacity=".18"/></linearGradient><linearGradient id="rim" x1="0" y1="0" x2="1" y2="1"><stop stop-color="#edf4fa" stop-opacity=".5"/><stop offset=".5" stop-color="#aab8ca" stop-opacity=".07"/><stop offset="1" stop-color="#fff" stop-opacity=".02"/></linearGradient><filter id="blur"><feGaussianBlur stdDeviation="13"/></filter><filter id="grain"><feTurbulence type="fractalNoise" baseFrequency=".7" numOctaves="3" stitchTiles="stitch"/><feColorMatrix type="saturate" values="0"/><feComponentTransfer><feFuncA type="linear" slope=".035"/></feComponentTransfer><feBlend in="SourceGraphic" mode="soft-light"/></filter><radialGradient id="shade"><stop offset=".2" stop-color="#000" stop-opacity="0"/><stop offset="1" stop-color="#000" stop-opacity=".23"/></radialGradient></defs><rect width="1600" height="1140" fill="url(#base)"/><g transform="translate(950 -300) rotate(32)"><rect x="-100" y="100" width="630" height="1600" rx="180" fill="#02050a" opacity=".5" filter="url(#blur)"/><rect width="630" height="1600" rx="180" fill="url(#plane)" stroke="url(#rim)" stroke-width="2"/><rect x="24" y="24" width="582" height="1552" rx="160" fill="none" stroke="#d8e4f1" stroke-opacity=".05"/></g><g transform="translate(-100 350) rotate(-32)"><rect width="430" height="1200" rx="170" fill="url(#plane)" stroke="url(#rim)" stroke-width="1.4"/></g><rect width="1600" height="1140" fill="url(#shade)"/><rect width="1600" height="1140" filter="url(#grain)" opacity=".08"/></svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 1000" preserveAspectRatio="xMidYMid slice"><defs><radialGradient id="wash" cx=".5" cy=".52" r=".73"><stop stop-color="#183243"></stop><stop offset=".57" stop-color="#101f2d"></stop><stop offset="1" stop-color="#080f17"></stop></radialGradient><linearGradient id="grid" x2="0" y2="1"><stop stop-color="#71a5ba" stop-opacity="0"></stop><stop offset="1" stop-color="#71a5ba" stop-opacity=".15"></stop></linearGradient><linearGradient id="pane" x2="1" y2="1"><stop stop-color="#9ab2c3" stop-opacity=".1"></stop><stop offset=".5" stop-color="#597b98" stop-opacity=".02"></stop><stop offset="1" stop-color="#afcadb" stop-opacity=".07"></stop></linearGradient></defs><rect width="1600" height="1000" fill="url(#wash)"></rect><g fill="none" stroke="url(#grid)" stroke-width="1"><path d="M448 620 -850 1100"></path><path d="M480 620 -700 1100"></path><path d="M512 620 -550 1100"></path><path d="M544 620 -400 1100"></path><path d="M576 620 -250 1100"></path><path d="M608 620 -100 1100"></path><path d="M640 620 50 1100"></path><path d="M672 620 200 1100"></path><path d="M704 620 350 1100"></path><path d="M736 620 500 1100"></path><path d="M768 620 650 1100"></path><path d="M800 620 800 1100"></path><path d="M832 620 950 1100"></path><path d="M864 620 1100 1100"></path><path d="M896 620 1250 1100"></path><path d="M928 620 1400 1100"></path><path d="M960 620 1550 1100"></path><path d="M992 620 1700 1100"></path><path d="M1024 620 1850 1100"></path><path d="M1056 620 2000 1100"></path><path d="M1088 620 2150 1100"></path><path d="M1120 620 2300 1100"></path><path d="M1152 620 2450 1100"></path><path d="M0 650H1600"></path><path d="M0 655H1600"></path><path d="M0 670H1600"></path><path d="M0 695H1600"></path><path d="M0 730H1600"></path><path d="M0 775H1600"></path><path d="M0 830H1600"></path><path d="M0 895H1600"></path><path d="M0 970H1600"></path><path d="M0 1055H1600"></path></g><path d="M0 620h1600" stroke="#a7c9dc" stroke-opacity=".025"></path><g fill="none" stroke="#709ab5" stroke-opacity=".09"><path d="M90 190h115m-115 0v80M1510 190h-115m115 0v80M90 810h115m-115 0v-80M1510 810h-115m115 0v-80"></path></g></svg>

After

Width:  |  Height:  |  Size: 2.1 KiB

+110
View File
@@ -0,0 +1,110 @@
/* Live Rust/Wasm workspace. Shared material follows the approved review package. */
[hidden]{display:none!important}
.bg img[style*="contain"]{transform:none!important}
.workspace-pane main.rt-page{margin:0!important;width:100%!important;max-width:none!important}
.mc-layout-b .mc-map-toolstrip{left:auto!important}
.mc-layout-b .mc-map-toolstrip{background:var(--work-panel);border-color:var(--work-line)}
.mc-layout-b .mc-map-toolstrip button{color:var(--work-text)}
.rt-target-label{color:#e4f0ff!important;background:#10223ed9;border:1px solid #8aaccb50;border-radius:6px;padding:4px 7px;font-size:13px}
.setting-row label{color:var(--work-text)!important;font-size:14px}
.live-events{display:flex;flex-wrap:wrap;gap:10px 28px;list-style:none;padding:10px 0;margin:0;font-size:12px;line-height:1.8;color:var(--work-muted)}
.live-events li{border-left:1px solid var(--work-line);padding-left:12px}
#rt-map[data-stale=true]{opacity:.7}
body.theme-white{color-scheme:light}
body{--work-text:#e6eefb;--work-muted:#a4b6d0;--work-line:#bdd8ff22;--work-panel:#1a2a3bc9;--work-input:#06101e61;--mc-text:var(--work-text);--mc-text-muted:var(--work-muted);--mc-text-dim:var(--work-muted);--mc-panel-bg:var(--work-panel);--mc-panel-dense:var(--work-panel);--mc-panel-raised:var(--work-panel);--mc-panel-card:#afcdfb0b;--mc-border:var(--work-line);--mc-accent:#8bbdff;font-size:14px}
body.theme-blue{--work-text:#e5efff;--work-muted:#abc3e2;--work-line:#acd0ff2f;--work-panel:#12365bd9;--work-input:#03132b66}
body.theme-white{--work-text:#243b57;--work-muted:#48617f;--work-line:#57759b2c;--work-panel:#e4eef9d4;--work-input:#f4f9ff55;--mc-accent:#2f6faf;--mc-accent-blue:#216bd0;--mc-success:#287957;--mc-warning:#95601d;--mc-shadow:0 5px 18px #233b5520}
.workspace-pane{position:absolute;top:48px;left:68px;right:0;bottom:0;overflow:auto;color:var(--work-text);background:linear-gradient(120deg,#202c3b8c,#0c15228c);backdrop-filter:blur(30px) saturate(115%)}
.theme-white .workspace-pane{background:linear-gradient(120deg,#f6faffd6,#e5effbc2)}.theme-blue .workspace-pane{background:linear-gradient(120deg,#1641747d,#071c4299)}
body[data-menu-hidden=true] .workspace-pane{left:0}body[data-menu-hidden=true] .reference-rail{display:none}body[data-menu-hidden=true] .homescreen{margin-left:0}
.workspace-pane>div{min-height:100%}.homescreen{position:absolute;top:48px;bottom:0;right:0;left:68px;margin:0;min-height:0;height:auto}.settings-layout{padding:26px 30px}.reference-top .theme-quick .theme-dot[data-theme=graphite]{background:#65778c}.reference-top .theme-quick .theme-dot[data-theme=blue]{background:#2864ad}.reference-top .theme-quick .theme-dot[data-theme=white]{background:#e5eef8}
/* Realtime B: full map with independent, bounded overlays. */
#workspace-content .rt-page{height:100%;min-height:0;padding:0;background:none;display:flex;flex-direction:column;overflow:hidden}
#workspace-content .mc-topbar{display:none}
.mc-layout-b{--dock-height:170px;--live-gap:16px;--list-width:260px;--detail-width:300px;--left-space:calc(var(--list-width) + 28px);--right-space:calc(var(--detail-width) + 28px);--dock-space:calc(var(--dock-height) + 56px);position:relative;height:100%;min-height:0;container-type:inline-size;overflow:hidden}
.mc-layout-b.list-hidden{--left-space:16px}
.mc-layout-b.detail-hidden{--right-space:16px}
.mc-layout-b.dock-hidden{--dock-space:104px}
.mc-layout-b .mc-map-area-top{position:absolute;inset:0;height:100%;min-height:0}
.mc-layout-b .mc-floating-panel{position:absolute;top:76px;bottom:var(--dock-space);padding:0!important;display:flex;flex-direction:column;min-height:0;overflow:hidden;background:var(--work-panel);border:1px solid var(--work-line);backdrop-filter:blur(24px);border-radius:12px;color:var(--work-text);box-shadow:0 12px 35px #0002;z-index:5}
.mc-layout-b .live-targets{left:var(--live-gap);width:var(--list-width)}
.mc-layout-b .live-detail{right:var(--live-gap)!important;left:auto;width:var(--detail-width)!important;top:76px!important;bottom:var(--dock-space)!important}
.mc-layout-b .rt-target-label{max-width:240px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.mc-layout-b .live-panel-head{height:52px;min-height:52px;display:flex;align-items:center;justify-content:space-between;gap:12px;padding:0 16px;border-bottom:1px solid var(--work-line)}
.mc-layout-b h2{font-size:15px;line-height:1.4;margin:0;font-weight:600;min-width:0}
.mc-layout-b button,.mc-layout-b a.mc-btn{font:inherit;min-height:34px;padding:6px 10px;background:var(--work-input);color:var(--work-text);border:1px solid var(--work-line);border-radius:7px;box-shadow:none;cursor:pointer;line-height:1.4}
.mc-layout-b button:hover:not(:disabled),.mc-layout-b a.mc-btn:hover{background:#7caff32a}
.mc-layout-b button:disabled,.mc-layout-b [aria-disabled=true]{opacity:.4;cursor:default;pointer-events:none}
.mc-layout-b :focus-visible{outline:2px solid var(--mc-accent);outline-offset:-3px}
.mc-layout-b .live-panel-head button{flex:none;min-width:34px;padding:5px;background:none}
.mc-layout-b .live-list-controls{display:flex;flex-direction:column;gap:10px;padding:14px 16px;flex:none}
.mc-layout-b .live-search{font:inherit;font-size:13px;background:var(--work-input);color:var(--work-text);border:1px solid var(--work-line);padding:10px;border-radius:8px;width:100%;min-width:0}
.mc-layout-b .live-list-body{flex:1;min-height:0;overflow:auto;padding:0 10px;overscroll-behavior:contain}
.mc-layout-b .live-target-list{display:flex;flex-direction:column;gap:6px}
.mc-layout-b .live-target-list button{display:flex;align-items:center;gap:9px;justify-content:flex-start;flex:none;font-size:13px;padding:13px 10px;text-align:left;white-space:normal;overflow-wrap:anywhere;background:none;border:1px solid transparent;border-radius:8px}
.mc-layout-b .live-target-list button[aria-pressed=true]{background:#669eeb26;border-color:#83b4e95c}
.mc-layout-b .live-empty{font-size:13px;line-height:1.9;color:var(--work-muted);padding:18px 6px}
.mc-layout-b .live-data-label{font-size:12px;color:var(--work-muted);line-height:1.8;overflow-wrap:anywhere}
.mc-layout-b .pagination{flex:none;margin:0;padding:12px 16px;border-top:1px solid var(--work-line);justify-content:space-between;align-items:center;gap:5px}
.mc-layout-b .pagination button{font-size:12px;padding:5px 8px}
.mc-layout-b .live-detail-body{flex:1;min-height:0;overflow:auto;padding:16px;overscroll-behavior:contain}
.mc-layout-b .live-target-heading{font-size:19px;line-height:1.5;font-weight:600;overflow-wrap:anywhere;margin:0 0 8px}
.mc-layout-b .live-back{margin-bottom:12px;font-size:12px}
.mc-layout-b .live-metrics{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px 10px;padding:20px 0;border-bottom:1px solid var(--work-line)}
.mc-layout-b .live-metrics>div:nth-child(n){grid-column:auto;min-width:0}
.mc-layout-b .live-metrics strong{font-size:16px!important;font-weight:500;overflow-wrap:anywhere;line-height:1.5}
.mc-layout-b .live-metrics span{font-size:11px;color:var(--work-muted);display:block;margin-bottom:6px}
.mc-layout-b .live-detail dl{display:grid;grid-template-columns:90px minmax(0,1fr);gap:12px 8px;font-size:13px;padding:18px 0;margin:0}
.mc-layout-b .live-detail dt{color:var(--work-muted);margin:0}
.mc-layout-b .live-detail dd{margin:0;overflow-wrap:anywhere}
.mc-layout-b .mc-btn-row{display:grid;grid-template-columns:1fr 1fr;gap:8px;padding:12px 16px;border-top:1px solid var(--work-line);flex:none;background:var(--work-panel)}
.mc-layout-b .mc-btn-row button,.mc-layout-b .mc-btn-row a{font-size:12px;text-align:center;text-decoration:none;white-space:normal;display:grid;place-items:center;min-height:38px}
.mc-layout-b .mc-btn-row .primary:hover:not(:disabled){background:#427db9;color:#fff}
.mc-layout-b .mc-btn-row .primary{background:#356ba6;color:#fff;border-color:#8bbdff55}
.mc-layout-b .mc-map-toolstrip{right:16px;top:16px;left:auto!important;width:auto;max-width:calc(100% - 32px);display:flex;flex-direction:row;gap:2px;padding:4px;background:var(--work-panel);border:1px solid var(--work-line);border-radius:9px;z-index:6;box-shadow:0 5px 18px #0002}
.mc-layout-b .mc-map-toolstrip button{background:none;border:0;min-width:34px;padding:6px 8px;font-size:14px}
.mc-layout-b .mc-map-infobar{left:16px;right:auto;bottom:calc(var(--dock-space) - 28px);max-width:min(420px,calc(100% - 32px));background:var(--work-panel);border:1px solid var(--work-line);border-radius:7px;padding:5px 9px;font-size:11px;line-height:1.5;white-space:normal;pointer-events:none;z-index:4;transform:translateY(-4px)}
.mc-layout-b:not(.compact) .mc-map-infobar{left:var(--left-space);max-width:calc(100% - var(--left-space) - var(--right-space) - 16px)}
.mc-layout-b .mc-hud-dock{position:absolute;left:16px;right:16px;bottom:16px;height:var(--dock-height);flex:none;min-height:0;max-height:none;border:1px solid var(--work-line);border-radius:12px;background:var(--work-panel);backdrop-filter:blur(24px);z-index:7;box-shadow:0 7px 25px #0002}
.mc-layout-b .live-resizer{height:10px;min-height:10px;display:grid;place-items:center;cursor:ns-resize;touch-action:none;user-select:none}
.mc-layout-b .live-resizer:after{content:'';width:40px;height:3px;background:var(--work-muted);opacity:.65;border-radius:3px}
.mc-layout-b .mc-dock-header{height:42px;min-height:42px;background:none;border-color:var(--work-line);padding:0 14px;gap:10px}
.mc-layout-b .mc-dock-tabs{display:flex;gap:14px;min-width:0}
.mc-layout-b .mc-dock-tab{font-size:12px;padding:5px 0;min-height:32px;border:0;border-radius:0;background:none;color:var(--work-muted);white-space:nowrap}
.mc-layout-b .mc-dock-tab.active{color:var(--work-text);background:none;border-bottom:2px solid var(--mc-accent)}
.mc-layout-b .live-dock-actions{display:flex;gap:6px;align-items:center;min-width:0}
.mc-layout-b .live-dock-actions button{font-size:12px;min-height:28px;white-space:nowrap;padding:4px 8px}
.mc-layout-b .mc-dock-substatus{color:var(--work-muted);font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:300px}
.mc-layout-b .mc-dock-body{flex:1;min-height:0;overflow:auto;padding:10px 16px;overscroll-behavior:contain;overflow-anchor:none}
.mc-layout-b .live-events{display:block;list-style:none;padding:0;margin:4px 0;font-size:12px;line-height:1.7;color:var(--work-muted)}
.mc-layout-b .live-events li{display:flex;gap:20px;padding:7px 0;border:0;border-bottom:1px solid var(--work-line);overflow-wrap:anywhere}
.mc-layout-b .live-events time{flex:0 0 60px;font-variant-numeric:tabular-nums;opacity:.8}
.mc-layout-b .live-dock-restore{position:absolute;bottom:14px;left:50%;transform:translateX(-50%);z-index:8;background:var(--work-panel);font-size:12px;white-space:nowrap;backdrop-filter:blur(20px)}
.mc-layout-b .receiver-expanded>summary{display:none}
.mc-layout-b .rt-receiver{margin:0;padding:0;border:0;background:none}
.mc-layout-b .rt-receiver-body{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px;margin:0;font-size:12px}
.mc-layout-b .rt-receiver-body>label,.mc-layout-b .rt-receiver-stat-box,.mc-layout-b .rt-capture-box,.mc-layout-b .rt-msg-pill{grid-column:1/-1}
.mc-layout-b .rt-form-row{display:flex;flex-direction:row;gap:10px}
.mc-layout-b .rt-switch-label{display:flex;flex-direction:row;align-items:center;gap:9px;margin:0;font-size:12px;line-height:1.7}
.mc-layout-b .rt-switch-label input[type=checkbox]{width:16px;height:16px;min-height:16px;padding:0;flex:none;accent-color:var(--mc-accent-blue)}
.mc-layout-b .rt-label{flex:1;min-width:0;font-size:12px;color:var(--work-muted)}
.mc-layout-b .rt-select,.mc-layout-b .rt-input{width:100%;min-width:0;min-height:34px;background:var(--work-input);color:var(--work-text);border-color:var(--work-line);font-size:13px}
.mc-layout-b .rt-btn-row{flex-wrap:wrap;margin:0;align-items:end}
.mc-layout-b .rt-capture-box{background:var(--work-input);color:var(--work-muted);border-color:var(--work-line);max-height:140px;overflow:auto;overflow-wrap:anywhere}
.mc-layout-b .rt-muted{white-space:pre-line;color:var(--work-muted)}
.mc-layout-b .rt-msg-pill:empty{display:none}
.mc-layout-b.compact .mc-floating-panel{left:16px;right:16px!important;top:76px!important;bottom:16px!important;width:auto!important;max-height:none}
.mc-layout-b.compact .mc-dock-substatus{display:none}
.mc-layout-b.compact .rt-receiver-body{grid-template-columns:1fr}
.mc-layout-b.compact .mc-dock-header{padding:4px 10px;gap:2px;flex-wrap:wrap;height:auto;min-height:74px;align-content:center}
.mc-layout-b.compact .mc-dock-tabs{gap:14px;width:100%;flex:none}
.mc-layout-b.compact .mc-dock-tab{font-size:11px}
.mc-layout-b.compact .live-dock-actions{gap:3px;margin-left:auto}
.mc-layout-b.compact .live-dock-actions button{font-size:11px;padding:4px 6px}
.mc-layout-b.compact .mc-map-infobar{bottom:var(--dock-space)}
.mc-layout-b #rt-map .maplibregl-ctrl-bottom-right{bottom:calc(var(--dock-space) - 28px);right:16px;max-width:calc(100% - 32px)}
@container(max-width:1199px){.mc-layout-b .live-targets{width:230px}.mc-layout-b .live-detail{width:280px!important}.mc-layout-b:not(.list-hidden):not(.compact) .mc-map-infobar{left:258px}}
.theme-white .mc-layout-b .mc-tag{color:#38604e}
@media(max-width:1400px){}
@media(max-width:1100px){.settings-layout{padding:24px;max-width:100%;overflow:auto}}
@media(max-width:760px){.workspace-pane{left:56px}.settings-layout{grid-template-columns:1fr;padding:18px}.settings-sidebar{display:none}.mc-dock-substatus{display:none}.homescreen{left:56px}}
File diff suppressed because one or more lines are too long
+15 -6
View File
@@ -1,19 +1,28 @@
use leptos::prelude::*;
mod realtime_layout;
mod realtime_ui;
mod receiver_ui;
mod registry;
mod workspace;
fn main() {
if web_sys::window()
let realtime = web_sys::window()
.unwrap()
.location()
.pathname()
.unwrap_or_default()
== "/realtime"
{
mount_to_body(|| view! { <realtime_ui::Realtime/> });
} else {
mount_to_body(|| view! { <Registry/> });
== "/realtime";
mount_to_body(move || {
view! {
<div inner_html=include_str!("workspace.html")/>
<section id="workspace-content" class="workspace-pane">
{if realtime { view! { <realtime_ui::Realtime/> }.into_any() }
else { view! { <Registry/> }.into_any() }}
</section>
}
});
workspace::init(realtime);
if !realtime {
registry::init();
}
}
+225
View File
@@ -0,0 +1,225 @@
//! Browser-local layout preferences, distinct from transient viewport constraints.
use leptos::prelude::*;
use serde_json::{Value, json};
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
use wasm_bindgen::JsCast;
const KEY: &str = "rid.realtime.layout.v1";
#[derive(Clone, Copy)]
pub struct Layout {
pub list: RwSignal<bool>,
pub detail: RwSignal<bool>,
pub receiver: RwSignal<bool>,
pub mounted: RwSignal<bool>,
pub dock: RwSignal<bool>,
pub compact: RwSignal<bool>,
pub mobile: RwSignal<u8>,
pub height: RwSignal<f64>,
pub maximum: RwSignal<f64>,
events_height: RwSignal<f64>,
receiver_height: RwSignal<f64>,
pub dragging: RwSignal<Option<(i32, f64)>>,
}
impl Layout {
pub fn new() -> Self {
let saved = web_sys::window()
.and_then(|w| w.local_storage().ok().flatten())
.and_then(|s| s.get_item(KEY).ok().flatten())
.and_then(|s| serde_json::from_str::<Value>(&s).ok())
.unwrap_or(Value::Null);
let boolean = |key: &str, default| saved[key].as_bool().unwrap_or(default);
let number = |key: &str, default| {
saved[key]
.as_f64()
.filter(|v| v.is_finite() && (100.0..=2000.0).contains(v))
.unwrap_or(default)
};
let receiver = boolean("receiver", false);
Self {
list: RwSignal::new(boolean("list", true)),
detail: RwSignal::new(boolean("detail", true)),
receiver: RwSignal::new(receiver),
mounted: RwSignal::new(receiver),
dock: RwSignal::new(boolean("dock", true)),
compact: RwSignal::new(false),
mobile: RwSignal::new(0),
height: RwSignal::new(170.0),
maximum: RwSignal::new(300.0),
events_height: RwSignal::new(number("eventsHeight", 170.0)),
receiver_height: RwSignal::new(number("receiverHeight", 0.0)),
dragging: RwSignal::new(None),
}
}
pub fn list_visible(self) -> bool {
if self.compact.get() {
self.mobile.get() == 1
} else {
self.list.get()
}
}
pub fn detail_visible(self) -> bool {
if self.compact.get() {
self.mobile.get() == 2
} else {
self.detail.get()
}
}
pub fn dock_visible(self) -> bool {
self.dock.get() && !(self.compact.get() && self.mobile.get() != 0)
}
pub fn toggle_list(self) {
if self.compact.get_untracked() {
self.mobile.update(|v| *v = if *v == 1 { 0 } else { 1 });
} else {
self.list.update(|v| *v = !*v);
}
self.save();
}
pub fn toggle_detail(self) {
if self.compact.get_untracked() {
self.mobile.update(|v| *v = if *v == 2 { 0 } else { 2 });
} else {
self.detail.update(|v| *v = !*v);
}
self.save();
}
pub fn select(self) {
if self.compact.get_untracked() {
self.mobile.set(2);
focus("rt-details");
}
}
pub fn tab(self, receiver: bool) {
self.receiver.set(receiver);
if receiver {
self.mounted.set(true);
}
self.save();
}
pub fn set_height(self, value: f64) {
let value = value.clamp(100.0, self.maximum.get_untracked());
if (self.height.get_untracked() - value).abs() > 0.1 {
self.height.set(value);
}
}
pub fn commit_height(self) {
let value = self.height.get_untracked();
if self.receiver.get_untracked() {
self.receiver_height.set(value)
} else {
self.events_height.set(value)
}
self.save();
}
pub fn save(self) {
let Some(root) = element("rt-layout") else {
return;
};
if root.client_height() == 0 {
return;
}
let value = json!({"list":self.list.get_untracked(),"detail":self.detail.get_untracked(),"dock":self.dock.get_untracked(),"receiver":self.receiver.get_untracked(),"eventsHeight":self.events_height.get_untracked(),"receiverHeight":self.receiver_height.get_untracked()});
if let Some(storage) = web_sys::window().and_then(|w| w.local_storage().ok().flatten()) {
let _ = storage.set_item(KEY, &value.to_string());
}
}
pub fn start(self) {
let stop = Arc::new(AtomicBool::new(false));
let cleanup = stop.clone();
on_cleanup(move || cleanup.store(true, Ordering::Relaxed));
wasm_bindgen_futures::spawn_local(async move {
while !stop.load(Ordering::Relaxed) {
if let Some(root) = element("rt-layout") {
let h = f64::from(root.client_height());
let w = root.client_width();
if h > 0.0 && w > 0 {
let compact = w < 900 || h < 520.0;
if compact != self.compact.get_untracked() {
self.compact.set(compact);
self.mobile.set(0);
self.dragging.set(None);
}
let max = if compact {
(h * 0.6).max(100.0)
} else {
(h - 432.0).min(h * 0.6).max(100.0)
};
if (self.maximum.get_untracked() - max).abs() > 0.1 {
self.maximum.set(max);
}
if self.dragging.get_untracked().is_none() {
let pref = if self.receiver.get_untracked() {
let v = self.receiver_height.get_untracked();
if v == 0.0 { h * 0.45 } else { v }
} else {
self.events_height.get_untracked()
};
self.set_height(pref);
}
let bounds = root.get_bounding_client_rect();
let scale = (bounds.width() / f64::from(w)).max(0.01);
let extent = |id: &str, left: bool| {
element(id)
.filter(|e| e.client_height() > 0)
.map(|e| {
let r = e.get_bounding_client_rect();
if left {
(r.right() - bounds.left()) / scale + 12.0
} else {
(bounds.right() - r.left()) / scale + 12.0
}
})
.unwrap_or(0.0)
};
let bottom = if self.dock_visible() {
self.height.get_untracked() + 72.0
} else {
116.0
};
let v = json!({"top":76,"left":extent("rt-directory",true),"right":extent("rt-details",false),"bottom":bottom});
let _ = super::realtime_ui::map_call(
"setOcclusion",
&[js_sys::JSON::parse(&v.to_string()).unwrap_or_default()],
);
if !web_sys::window()
.and_then(|w| w.document())
.is_some_and(|d| d.has_focus().unwrap_or(false))
{
self.dragging.set(None);
}
} else if self.dragging.get_untracked().is_some() {
self.dragging.set(None);
}
}
gloo_timers::future::TimeoutFuture::new(100).await;
}
});
}
pub fn focus(self) {
if self.compact.get_untracked() {
self.mobile.set(0);
focus("rt-map-focus");
}
let _ = super::realtime_ui::map_call("focusVisible", &[]);
}
}
pub fn element(id: &str) -> Option<web_sys::HtmlElement> {
web_sys::window()?
.document()?
.get_element_by_id(id)?
.dyn_into()
.ok()
}
pub fn focus(id: &str) {
let id = id.to_owned();
let callback = wasm_bindgen::closure::Closure::once_into_js(move || {
if let Some(e) = element(&id) {
let _ = e.focus();
}
});
if let Some(w) = web_sys::window() {
let _ = w.request_animation_frame(callback.unchecked_ref());
}
}
File diff suppressed because it is too large Load Diff
+14 -3
View File
@@ -1,9 +1,13 @@
use leptos::prelude::*;
use serde_json::json;
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
use wasm_bindgen_futures::spawn_local;
#[component]
pub fn ReceiverControls() -> impl IntoView {
pub fn ReceiverControls(#[prop(default = false)] expanded: bool) -> impl IntoView {
let enabled = RwSignal::new(false);
let transport = RwSignal::new("serial".to_owned());
let format = RwSignal::new("raw".to_owned());
@@ -16,12 +20,17 @@ pub fn ReceiverControls() -> impl IntoView {
let capture = RwSignal::new(String::new());
let ports = RwSignal::new(Vec::<String>::new());
let busy = RwSignal::new(false);
let stopped = Arc::new(AtomicBool::new(false));
let cleanup = stopped.clone();
on_cleanup(move || cleanup.store(true, Ordering::Relaxed));
Effect::new(move |_| {
let stopped = stopped.clone();
spawn_local(async move {
if let Ok(response) = gloo_net::http::Request::get("/api/receiver/config")
.send()
.await
&& let Ok(v) = response.json::<serde_json::Value>().await
&& !stopped.load(Ordering::Relaxed)
{
enabled.set(v["enabled"].as_bool().unwrap_or(false));
transport.set(v["transport"].as_str().unwrap_or("serial").into());
@@ -35,6 +44,7 @@ pub fn ReceiverControls() -> impl IntoView {
.send()
.await
&& let Ok(v) = response.json::<serde_json::Value>().await
&& !stopped.load(Ordering::Relaxed)
{
ports.set(
v["ports"]
@@ -47,11 +57,12 @@ pub fn ReceiverControls() -> impl IntoView {
.unwrap_or_default(),
);
}
loop {
while !stopped.load(Ordering::Relaxed) {
if let Ok(response) = gloo_net::http::Request::get("/api/receiver/status")
.send()
.await
&& let Ok(v) = response.json::<serde_json::Value>().await
&& !stopped.load(Ordering::Relaxed)
{
let state = match v["state"].as_str().unwrap_or("stopped") {
"serial-open" => "串口已打开",
@@ -107,7 +118,7 @@ pub fn ReceiverControls() -> impl IntoView {
});
};
view! {
<details class="rt-receiver">
<details class="rt-receiver" open=expanded class:receiver-expanded=expanded>
<summary class="rt-receiver-summary">
<span class="rt-summary-title">"📡 接收机设置 · 接口与解码"</span>
<span class="rt-summary-tag">{move||if enabled.get(){"● 接收中"}else{"○ 未启用"}}</span>
+18 -81
View File
@@ -1,59 +1,17 @@
<div class="shell">
<header class="topbar">
<img class="brand-mark" src="/fpv-rid-icon.png" alt="FPV-RID 图标">
<div class="brand-copy">
<strong>RID / 设备备案登记中心</strong>
<small>REMOTE ID REGISTRATION & AUDIT CENTER</small>
</div>
<nav class="mc-nav-tabs" style="margin-left: 20px;">
<span class="mc-nav-pill active"><span class="mc-pill-icon">📋</span> 设备备案登记</span>
<a class="mc-nav-pill mc-nav-link" href="/realtime"><span class="mc-pill-icon">🛰️</span> 实时目标工作台</a>
</nav>
<div class="top-status"><i></i> 本机沙盒运行</div>
</header>
<main>
<section class="hero">
<div>
<h1>登记设备,生成本地二维码</h1>
<p>为模块 SN 建立本机记录。二维码交给配套的本地版上位机扫描,校验 SN 后再由上位机完成设备操作。</p>
</div>
</section>
<div class="columns">
<section class="panel form-panel" aria-labelledby="register-title">
<div class="panel-head"><div><span class="step">01</span><h2 id="register-title">新建设备登记</h2></div><span class="subtle">同一 SN 只保留一条记录</span></div>
<form id="register-form">
<label for="serial-no">模块 SN <em>必填</em></label>
<input id="serial-no" name="serialNo" required maxlength="40" autocomplete="off" placeholder="例如 ZEX0RID1202605011000" pattern="[A-Za-z0-9-]{6,40}">
<p class="hint">请与上位机“RID 模块状态信息”里的 SN 完全一致。</p>
<div class="field-grid">
<div><label for="model-name">机型</label><input id="model-name" name="modelName" maxlength="60" placeholder="例如 5 寸穿越机"></div>
<div><label for="owner-name">登记人 / 备注</label><input id="owner-name" name="ownerName" maxlength="40" placeholder="可选"></div>
</div>
<label for="uas-code">FPV 编号 <span class="optional">可选</span></label>
<div class="input-prefix"><span>FPV</span><input id="uas-code" name="uasDigits" maxlength="8" inputmode="numeric" pattern="[0-9]{8}" placeholder="留空则自动生成 8 位数字"></div>
<p class="hint">已有 FPV 编号可输入后 8 位数字;留空则自动生成。</p>
<div class="field-grid photo-fields">
<div><label for="photo-1">登记照片 1 <span class="optional">可选</span></label><input id="photo-1" type="file" accept="image/jpeg,image/png,image/webp"></div>
<div><label for="photo-2">登记照片 2 <span class="optional">可选</span></label><input id="photo-2" type="file" accept="image/jpeg,image/png,image/webp"></div>
</div>
<p class="hint">每张最多 5 MB,支持 JPG、PNG 和 WebP。照片保存在本机数据库;同一 SN 再次保存可补充或替换照片。</p>
<button class="primary" id="register-button" type="submit">保存登记并生成二维码 <span aria-hidden="true">→</span></button>
<p class="form-message" id="form-message" role="status"></p>
</form>
</section>
<section class="panel result-panel" aria-labelledby="result-title">
<div class="panel-head"><div><span class="step muted">02</span><h2 id="result-title">二维码与核验</h2></div><span class="subtle">同机使用</span></div>
<div id="empty-result" class="empty-state"><div class="empty-glyph">▦</div><b>等待登记</b><span>保存后在这里生成二维码,供本地版上位机读取。</span></div>
<div id="record-result" class="record-result" hidden>
<div class="registry-workspace">
<aside class="history-panel" aria-labelledby="history-title"><header class="history-heading"><h2 id="history-title">本地档案</h2><button id="refresh-list" type="button" aria-label="刷新记录" title="刷新记录">↻</button></header>
<div class="history-search"><input id="history-query" type="search" maxlength="60" autocomplete="off" aria-label="搜索登记档案" placeholder="搜索 SN、FPV 编号或机型"><span id="search-count" aria-live="polite"></span></div>
<button id="new-registration" type="button" class="primary">+ 新建设备登记</button>
<div class="history-toolbar"><button id="selection-toggle" type="button" aria-pressed="false">选择</button><div class="export-controls"><button id="export-toggle" type="button" disabled aria-expanded="false" aria-controls="export-options">导出⌄</button><div id="export-options" class="registry-popup" hidden><button id="export-archive" type="button" disabled>导出档案包</button><button id="export-excel" type="button" disabled>导出 Excel</button><p>仅导出当前页已选档案</p></div></div></div>
<div id="selection-controls" hidden><label class="select-all"><input id="select-all" type="checkbox">全选当前页 <span id="selected-count">(0)</span></label></div>
<p class="history-message" id="history-message" role="status"></p><div id="history-empty" class="history-empty">正在读取档案…</div><div id="history-cards" class="history-cards"></div>
<nav class="pagination" aria-label="档案分页"><span id="page-status" aria-live="polite"></span><div><button id="previous-page" type="button">上一页</button><button id="next-page" type="button">下一页</button></div></nav>
<p id="archive-warning" class="archive-warning" role="status" hidden><span id="archive-warning-text"></span> <button id="retry-archive" type="button">重试同步</button></p></aside>
<div class="registration-scroll"><div class="registration-main"><header class="registration-heading"><div><h1 id="register-title">新建设备登记</h1><p>填写设备信息,生成本机登记二维码</p></div><span>资料保存在本机</span></header>
<section class="result-panel registry-group" aria-labelledby="result-title" id="registration-result" tabindex="-1"><h2 id="result-title">二维码与核验</h2>
<div id="empty-result" class="empty-state"><div class="empty-glyph"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" aria-hidden="true"><path d="M3 3h6v6H3z M15 3h6v6h-6z M3 15h6v6H3z M14 14h3v3h4v4h-7z"/></svg></div><div><b>等待完成登记</b><p>保存后自动生成二维码,供本地版上位机读取和核验。</p></div><ol><li>填写模块 SN</li><li>保存登记并生成二维码</li><li>在本地版上位机核验</li></ol></div><div id="record-result" class="record-result" hidden>
<div class="qr-stage" id="qr-stage" aria-label="本地登记二维码"></div>
<div class="record-kicker">本地记录已保存</div>
<div class="record-kicker" id="result-context" role="status"></div>
<div class="uas-display" id="display-uas"></div>
<dl class="result-fields"><div><dt>Serial No.</dt><dd id="display-sn"></dd></div><div><dt>机型</dt><dd id="display-model"></dd></div><div><dt>登记人</dt><dd id="display-owner"></dd></div></dl>
<div class="saved-photos" id="saved-photos" hidden>
@@ -66,29 +24,8 @@
<p class="result-tip">在本机同时启动登记站和本地版上位机,上传此二维码。上位机会从本地记录读取字段并比对模块 SN。</p>
</div>
</section>
</div>
<section class="panel history-panel" aria-labelledby="history-title">
<div class="panel-head history-head"><div><span class="step muted">03</span><h2 id="history-title">本地登记记录</h2></div><div class="history-controls"><div class="history-search"><input id="history-query" type="search" maxlength="60" autocomplete="off" aria-label="搜索登记档案" placeholder="搜索 SN、FPV 编号、机型、登记人"><span id="search-count" aria-live="polite"></span></div><label class="select-all"><input id="select-all" type="checkbox">全选 <span id="selected-count">(0)</span></label><button id="export-archive" class="export-button" type="button" disabled>导出档案包</button><button id="export-excel" class="export-button" type="button" disabled>导出 Excel</button><button id="refresh-list" class="text-button" type="button">刷新记录</button></div></div>
<p class="history-message" id="history-message" role="status">导出档案包包含离线档案卡、照片和登记信息;Excel 导出为登记表。</p>
<div id="history-empty" class="history-empty">暂无登记记录。</div>
<div id="history-cards" class="history-cards"></div>
<nav class="pagination" aria-label="档案分页"><span>全选仅当前页</span><button id="previous-page" type="button">上一页</button><span id="page-status" aria-live="polite"></span><button id="next-page" type="button">下一页</button></nav>
<p id="archive-warning" class="archive-warning" role="status" hidden><span id="archive-warning-text"></span> <button id="retry-archive" type="button">重试同步</button></p>
</section>
</main>
<footer><span>127.0.0.1:8787 · 数据保存在本机</span></footer>
</div>
<dialog id="edit-dialog" aria-labelledby="edit-title">
<form id="edit-form">
<h2 id="edit-title">编辑档案</h2><p id="edit-identity"></p><p class="edit-help">SN 与 FPV 编号不可修改;清空机型或登记人后保存,即清除该字段。</p>
<label for="edit-model">机型</label><input id="edit-model" maxlength="60">
<label for="edit-owner">登记人 / 备注</label><input id="edit-owner" maxlength="40">
<div class="edit-photos">
<fieldset><legend>照片 1</legend><img id="edit-preview-1" alt="现有照片 1" hidden><label for="edit-photo-1">替换照片 1</label><input id="edit-photo-1" type="file" accept="image/jpeg,image/png,image/webp"><label class="edit-delete"><input id="edit-delete-1" type="checkbox">删除现有照片 1</label></fieldset>
<fieldset><legend>照片 2</legend><img id="edit-preview-2" alt="现有照片 2" hidden><label for="edit-photo-2">替换照片 2</label><input id="edit-photo-2" type="file" accept="image/jpeg,image/png,image/webp"><label class="edit-delete"><input id="edit-delete-2" type="checkbox">删除现有照片 2</label></fieldset>
</div>
<p id="edit-message" role="status"></p><div class="result-actions"><button id="edit-save" class="secondary" type="submit">保存修改</button><button id="edit-cancel" class="ghost" type="button">取消</button></div>
</form>
</dialog>
<form id="register-form" aria-labelledby="register-title"><section class="registry-group"><div class="registry-group-heading"><h2>设备身份</h2><span>仅模块 SN 必填</span></div><div class="registration-fields"><div class="registration-field full"><label for="serial-no">模块 SN <span aria-hidden="true">*</span></label><input id="serial-no" name="serialNo" required maxlength="40" autocomplete="off" pattern="[A-Za-z0-9-]{6,40}" placeholder="输入完整模块序列号"></div><div class="registration-field"><label for="model-name">机型 <small>选填</small></label><input id="model-name" name="modelName" maxlength="60" placeholder="例如:5 寸穿越机"></div><div class="registration-field"><label for="owner-name">登记人 / 备注 <small>选填</small></label><input id="owner-name" name="ownerName" maxlength="40" placeholder="方便后续查找"></div></div><p class="registry-help">SN 需与上位机模块一致;相同 SN 再次保存将更新原档案。</p></section>
<section class="registry-group"><div class="registry-group-heading"><h2>登记编号</h2><span>自动生成或手动填写</span></div><div class="registration-number"><div class="registration-field"><label for="uas-code">FPV 编号 <small>选填</small></label><div class="registration-prefix"><span aria-hidden="true">FPV</span><input id="uas-code" name="uasDigits" maxlength="8" inputmode="numeric" pattern="[0-9]{8}" aria-describedby="fpv-hint" placeholder="8 位数字 · 留空自动生成"></div></div><p id="fpv-hint" class="registry-help">已有编号仅填写后 8 位数字。<br>留空时,保存后自动生成。</p></div></section>
<section class="registry-group"><div class="registry-group-heading"><h2>设备照片</h2><span>选填 · 最多 2 张</span></div><div class="registration-photos"><div class="photo-slot"><input id="photo-1" type="file" accept="image/jpeg,image/png,image/webp" data-photo-slot="0" hidden><button type="button" class="photo-pick" data-photo-choose="0" aria-label="添加照片 1"><img id="slot-preview-0" alt="照片 1预览" hidden><span class="photo-plus" aria-hidden="true">+</span><strong>添加照片 1</strong><span id="slot-name-0">点击选择本地图片</span></button><div class="photo-slot-actions"><button type="button" data-photo-remove="0" id="slot-remove-0" hidden>移除照片</button></div><button type="button" data-photo-keep="0" id="slot-keep-0" hidden>保留原选择</button><p id="slot-status-0" class="photo-status" role="status"></p></div><div class="photo-slot"><input id="photo-2" type="file" accept="image/jpeg,image/png,image/webp" data-photo-slot="1" hidden><button type="button" class="photo-pick" data-photo-choose="1" aria-label="添加照片 2"><img id="slot-preview-1" alt="照片 2预览" hidden><span class="photo-plus" aria-hidden="true">+</span><strong>添加照片 2</strong><span id="slot-name-1">点击选择本地图片</span></button><div class="photo-slot-actions"><button type="button" data-photo-remove="1" id="slot-remove-1" hidden>移除照片</button></div><button type="button" data-photo-keep="1" id="slot-keep-1" hidden>保留原选择</button><p id="slot-status-1" class="photo-status" role="status"></p></div></div><p class="registry-help">JPG、PNG、WebP · 每张不超过 5 MB · 仅保存在本机档案</p></section>
<p class="form-message" id="form-message" role="status"></p><div class="registration-savebar"><span id="draft-state">保存时校验 SN 与编号</span><button class="primary" id="register-button" type="submit">保存登记并生成二维码 →</button></div></form></div></div></div>
<dialog id="edit-dialog" aria-labelledby="edit-title"><form id="edit-form"><header><h2 id="edit-title">编辑档案</h2><p id="edit-identity"></p><p class="registry-help">SN 与 FPV 编号不可修改;清空机型或登记人后保存,即清除该字段。</p></header><div class="registration-fields"><div class="registration-field"><label for="edit-model">机型</label><input id="edit-model" maxlength="60"></div><div class="registration-field"><label for="edit-owner">登记人 / 备注</label><input id="edit-owner" maxlength="40"></div></div><div class="edit-photos"><fieldset><legend>照片 1</legend><div class="photo-slot"><input id="edit-photo-1" type="file" accept="image/jpeg,image/png,image/webp" data-photo-slot="2" hidden><button type="button" class="photo-pick" data-photo-choose="2" aria-label="替换照片 1"><img id="slot-preview-2" alt="照片 1预览" hidden><span class="photo-plus" aria-hidden="true">+</span><strong>选择替换照片 1</strong><span id="slot-name-2">点击选择本地图片</span></button><div class="photo-slot-actions"><button type="button" data-photo-remove="2" id="slot-remove-2" hidden>取消替换 / 恢复原图</button></div><button type="button" data-photo-keep="2" id="slot-keep-2" hidden>保留原选择</button><p id="slot-status-2" class="photo-status" role="status"></p></div><label class="edit-delete"><input id="edit-delete-1" type="checkbox">删除现有照片 1</label></fieldset><fieldset><legend>照片 2</legend><div class="photo-slot"><input id="edit-photo-2" type="file" accept="image/jpeg,image/png,image/webp" data-photo-slot="3" hidden><button type="button" class="photo-pick" data-photo-choose="3" aria-label="替换照片 2"><img id="slot-preview-3" alt="照片 2预览" hidden><span class="photo-plus" aria-hidden="true">+</span><strong>选择替换照片 2</strong><span id="slot-name-3">点击选择本地图片</span></button><div class="photo-slot-actions"><button type="button" data-photo-remove="3" id="slot-remove-3" hidden>取消替换 / 恢复原图</button></div><button type="button" data-photo-keep="3" id="slot-keep-3" hidden>保留原选择</button><p id="slot-status-3" class="photo-status" role="status"></p></div><label class="edit-delete"><input id="edit-delete-2" type="checkbox">删除现有照片 2</label></fieldset></div><p id="edit-message" class="form-message" role="status"></p><div class="result-actions"><button id="edit-save" class="primary" type="submit">保存修改</button><button id="edit-cancel" type="button">取消</button></div></form></dialog>
+330 -91
View File
@@ -1,5 +1,6 @@
//! Registration interactions compiled from Rust; no JavaScript business fallback.
use base64::{Engine, engine::general_purpose::STANDARD};
#[path = "registry_photos.rs"]
mod photos;
use gloo_net::http::Request;
use gloo_timers::future::TimeoutFuture;
use qrcodegen::{QrCode, QrCodeEcc};
@@ -8,8 +9,7 @@ use std::{cell::RefCell, collections::HashSet, rc::Rc};
use wasm_bindgen::{JsCast, JsValue, closure::Closure};
use wasm_bindgen_futures::{JsFuture, spawn_local};
use web_sys::{
Element, Event, HtmlAnchorElement, HtmlButtonElement, HtmlCanvasElement, HtmlDialogElement,
HtmlInputElement,
Element, Event, HtmlAnchorElement, HtmlCanvasElement, HtmlDialogElement, HtmlInputElement,
};
#[derive(Default)]
@@ -22,6 +22,11 @@ struct State {
pages: u64,
generation: u64,
busy: bool,
selecting: bool,
dirty: bool,
photos: photos::Shared,
menu: Option<(String, String)>,
edit_return: String,
}
type Shared = Rc<RefCell<State>>;
type Result<T> = std::result::Result<T, String>;
@@ -128,8 +133,18 @@ fn selection(state: &Shared) {
text("selected-count", &format!("({n})"));
input("select-all").set_checked(!s.rows.is_empty() && n == s.rows.len());
input("select-all").set_indeterminate(n > 0 && n < s.rows.len());
disabled("export-archive", n == 0);
disabled("export-excel", n == 0);
disabled("export-toggle", n == 0 || s.busy);
hidden("selection-controls", !s.selecting);
let _ = el("history-cards")
.set_attribute("data-selecting", if s.selecting { "true" } else { "false" });
text(
"selection-toggle",
if s.selecting { "完成" } else { "选择" },
);
let _ = el("selection-toggle")
.set_attribute("aria-pressed", if s.selecting { "true" } else { "false" });
disabled("export-archive", n == 0 || s.busy);
disabled("export-excel", n == 0 || s.busy);
}
fn page_buttons(state: &Shared) {
let s = state.borrow();
@@ -140,33 +155,76 @@ fn clear_selection(state: &Shared) {
state.borrow_mut().selected.clear();
render_rows(state);
}
fn focus(id: &str) {
let target = document()
.get_element_by_id(id)
.unwrap_or_else(|| el("selection-toggle"));
if let Some(target) = target.dyn_ref::<web_sys::HtmlElement>() {
let _ = target.focus();
}
}
fn close_menu(state: &Shared, restore: bool) {
let menu = state.borrow_mut().menu.take();
if let Some((popup, trigger)) = menu {
if let Some(e) = document().get_element_by_id(&popup) {
let _ = e.set_attribute("hidden", "");
}
if let Some(e) = document().get_element_by_id(&trigger) {
let _ = e.set_attribute("aria-expanded", "false");
}
if restore {
focus(&trigger);
}
}
}
fn toggle_menu(state: &Shared, popup: &str, trigger: &str) {
let same = state
.borrow()
.menu
.as_ref()
.is_some_and(|(p, _)| p == popup);
close_menu(state, false);
if same {
focus(trigger);
return;
}
hidden(popup, false);
let _ = el(trigger).set_attribute("aria-expanded", "true");
state.borrow_mut().menu = Some((popup.into(), trigger.into()));
el(popup).scroll_into_view();
if let Ok(Some(first)) = el(popup).query_selector("button:not(:disabled),a[href]")
&& let Some(first) = first.dyn_ref::<web_sys::HtmlElement>()
{
let _ = first.focus();
}
}
fn render_rows(state: &Shared) {
let focused = document()
.active_element()
.filter(|e| e.closest("#history-cards").ok().flatten().is_some())
.map(|e| e.id());
close_menu(state, false);
let s = state.borrow();
let mut html = String::new();
for row in &s.rows {
let id = escape(field(row, "id"));
let sn = escape(field(row, "serialNo"));
let selected = s.selected.contains(field(row, "id"));
html.push_str(&format!("<article class=\"archive-card{}\" data-id=\"{id}\"><label class=\"archive-select\"><input type=\"checkbox\" data-action=\"select\" aria-label=\"选择档案 {sn}\" {}>导出</label><h3>{sn}</h3><strong>{}</strong><p>{} · {} · {}</p><div class=\"archive-thumbs\">",if selected {" selected"} else {""},if selected {"checked"} else {""},escape(field(row,"uasCode")),escape(field(row,"modelName")),escape(field(row,"ownerName")),escape(field(row,"createdAt"))));
for slot in [1, 2] {
let url = field(row, &format!("photo{slot}Url"));
if url.is_empty() {
html.push_str(&format!("<div>照片 {slot} 未上传</div>"));
} else {
html.push_str(&format!(
"<div><img loading=\"lazy\" alt=\"登记照片 {slot}\" src=\"{}\"></div>",
escape(url)
));
}
}
html.push_str(&format!("</div><div class=\"archive-actions\"><button type=\"button\" data-action=\"edit\">编辑资料 / 照片</button><a href=\"{}\" target=\"_blank\" rel=\"noopener\">打开档案卡</a><a href=\"{}\">下载离线档案卡</a><button type=\"button\" data-action=\"qr\">查看二维码</button><button type=\"button\" class=\"delete-record\" data-action=\"delete\">删除档案</button></div></article>",escape(field(row,"archiveUrl")),escape(field(row,"downloadArchiveUrl"))));
let current = s.active.as_ref().is_some_and(|r| r["id"] == row["id"]);
let date = field(row, "createdAt");
let short = date.get(..10).unwrap_or(date).replace('-', ".");
html.push_str(&format!(r#"<article class="archive-card{}{}" data-id="{id}"><label class="archive-select"><input id="select-{id}" type="checkbox" data-action="select" aria-label="选择档案 {sn}" {}>选择导出</label><div class="archive-card-head"><h3>{sn}</h3><button id="more-{id}" type="button" class="archive-more" data-action="more" aria-label="{sn} 更多操作" aria-expanded="false" aria-controls="actions-{id}">···</button></div><strong>{}</strong><p>{} · {}</p><div class="archive-card-foot"><time datetime="{}" title="{}">{}</time><button id="view-{id}" type="button" data-action="view">查看档案 →</button></div><div id="actions-{id}" class="registry-popup" hidden><button type="button" data-action="edit">编辑资料 / 照片</button><a href="{}" target="_blank" rel="noopener">打开档案卡</a><a href="{}">下载离线档案卡</a><button type="button" data-action="qr">查看二维码</button><button type="button" class="delete-record" data-action="delete">删除档案</button></div></article>"#, if selected {" selected"} else {""}, if current {" is-current"} else {""}, if selected {"checked"} else {""}, escape(field(row,"uasCode")), escape(field(row,"modelName")), escape(field(row,"ownerName")), escape(date), escape(date), escape(&short), escape(field(row,"archiveUrl")), escape(field(row,"downloadArchiveUrl"))));
}
el("history-cards").set_inner_html(&html);
hidden("history-empty", !s.rows.is_empty());
drop(s);
selection(state);
if let Some(id) = focused {
focus(&id);
}
}
async fn load(state: Shared, mut page: u64) -> Result<()> {
close_menu(&state, false);
let generation = {
let mut s = state.borrow_mut();
s.generation += 1;
@@ -233,27 +291,13 @@ async fn load(state: Shared, mut page: u64) -> Result<()> {
return Ok(());
}
}
async fn photo(id: &str) -> Result<Option<String>> {
let Some(file) = input(id).files().and_then(|files| files.get(0)) else {
return Ok(None);
};
if !matches!(
file.type_().as_str(),
"image/jpeg" | "image/png" | "image/webp"
) || file.size() > 5.0 * 1024.0 * 1024.0
{
return Err("照片仅支持 5 MB 以内的 JPG、PNG 或 WebP".into());
}
let data = JsFuture::from(file.array_buffer()).await.map_err(err)?;
Ok(Some(format!(
"data:{};base64,{}",
file.type_(),
STANDARD.encode(js_sys::Uint8Array::new(&data).to_vec())
)))
}
fn draw(state: &Shared, record: Value) {
hidden("empty-result", true);
hidden("record-result", false);
text(
"result-context",
&format!("正在查看:{} · 已保存档案", field(&record, "serialNo")),
);
for (id, key) in [
("display-uas", "uasCode"),
("display-sn", "serialNo"),
@@ -300,6 +344,8 @@ fn draw(state: &Shared, record: Value) {
el("qr-stage").set_inner_html(&svg);
}
state.borrow_mut().active = Some(record);
render_rows(state);
el("registration-result").scroll_into_view();
}
fn edit(state: &Shared, row: Value) {
text("edit-message", "");
@@ -310,46 +356,66 @@ fn edit(state: &Shared, row: Value) {
input("edit-model").set_value(field(&row, "modelName"));
input("edit-owner").set_value(field(&row, "ownerName"));
for slot in [1, 2] {
let url = field(&row, &format!("photo{slot}Url"));
hidden(&format!("edit-preview-{slot}"), url.is_empty());
let _ = el(&format!("edit-preview-{slot}")).set_attribute("src", url);
input(&format!("edit-photo-{slot}")).set_value("");
input(&format!("edit-delete-{slot}")).set_checked(false);
input(&format!("edit-delete-{slot}")).set_disabled(url.is_empty());
photos::reset(
&state.borrow().photos,
slot + 1,
field(&row, &format!("photo{slot}Url")),
);
}
state.borrow_mut().editing = Some(row);
let _ = dialog().show_modal();
let _ = input("edit-model").focus();
}
fn editing_controls(disable: bool) {
let elements = el("edit-form").query_selector_all("input,button").unwrap();
for i in 0..elements.length() {
let node = elements.get(i).unwrap();
if let Some(input) = node.dyn_ref::<HtmlInputElement>() {
input.set_disabled(disable);
} else if let Some(button) = node.dyn_ref::<HtmlButtonElement>() {
button.set_disabled(disable);
fn saving_controls(state: &Shared, busy: bool) {
let _ = document()
.body()
.unwrap()
.set_attribute("data-registry-busy", if busy { "true" } else { "false" });
let _ = el("register-form").set_attribute("aria-busy", if busy { "true" } else { "false" });
let _ = el("edit-form").set_attribute("aria-busy", if busy { "true" } else { "false" });
if let Ok(nodes) = document().query_selector_all("#register-form input,#register-form button,#edit-form input,#edit-form button,#new-registration,#history-cards button,#history-cards input,#selection-toggle,#history-query,#refresh-list,#previous-page,#next-page,#select-all") {
for i in 0..nodes.length() {
if let Some(e) = nodes.item(i).and_then(|n| n.dyn_into::<Element>().ok()) {
if busy { let _ = e.set_attribute("disabled", ""); } else { let _ = e.remove_attribute("disabled"); }
}
}
}
if !busy {
for i in 2..4 {
photos::render(&state.borrow().photos, i);
}
}
text(
"register-button",
if busy {
"正在保存…"
} else {
"保存登记并生成二维码 →"
},
);
text(
"edit-save",
if busy {
"正在保存…"
} else {
"保存修改"
},
);
selection(state);
if !busy {
page_buttons(state);
}
}
async fn save(state: Shared, editing: bool) -> Result<()> {
if state.borrow().busy {
return Ok(());
}
state.borrow_mut().busy = true;
close_menu(&state, false);
saving_controls(&state, true);
let result = save_inner(state.clone(), editing).await;
state.borrow_mut().busy = false;
if editing {
editing_controls(false);
if let Some(row) = state.borrow().editing.clone() {
for slot in [1, 2] {
input(&format!("edit-delete-{slot}"))
.set_disabled(field(&row, &format!("photo{slot}Url")).is_empty());
}
}
} else {
disabled("register-button", false);
}
saving_controls(&state, false);
result
}
async fn save_inner(state: Shared, editing: bool) -> Result<()> {
@@ -359,23 +425,14 @@ async fn save_inner(state: Shared, editing: bool) -> Result<()> {
let digits = value("uas-code");
json!({"serialNo":value("serial-no"),"modelName":value("model-name"),"ownerName":value("owner-name"),"uasCode":if digits.is_empty(){String::new()}else{format!("FPV{digits}")}})
};
if editing {
editing_controls(true);
} else {
disabled("register-button", true);
let photos = state.borrow().photos.clone();
while photos::pending(&photos, editing) {
TimeoutFuture::new(20).await;
}
for slot in [1, 2] {
let id = if editing {
format!("edit-photo-{slot}")
} else {
format!("photo-{slot}")
};
if editing && input(&format!("edit-delete-{slot}")).checked() {
body[format!("photo{slot}")] = Value::Null;
} else if let Some(p) = photo(&id).await? {
body[format!("photo{slot}")] = json!(p);
}
if let Some(error) = photos::validation_error(&photos, editing) {
return Err(error);
}
photos::apply(&photos, editing, &mut body);
let url = if editing {
let s = state.borrow();
format!(
@@ -399,6 +456,8 @@ async fn save_inner(state: Shared, editing: bool) -> Result<()> {
draw(&state, payload["record"].clone());
}
} else {
state.borrow_mut().dirty = false;
text("draft-state", "已保存 · 修改后可再次保存");
draw(&state, payload["record"].clone());
message(
"form-message",
@@ -467,9 +526,8 @@ async fn export(state: Shared, kind: &str) -> Result<()> {
Ok(())
}
fn download_qr(state: &Shared) -> Result<()> {
let s = state.borrow();
let row = s.active.as_ref().ok_or("请先登记")?;
let qr = QrCode::encode_text(field(row, "qrUrl"), QrCodeEcc::Medium)
let row = state.borrow().active.clone().ok_or("请先登记")?;
let qr = QrCode::encode_text(field(&row, "qrUrl"), QrCodeEcc::Medium)
.map_err(|_| "二维码生成失败")?;
let canvas: HtmlCanvasElement = document()
.create_element("canvas")
@@ -501,20 +559,29 @@ fn download_qr(state: &Shared) -> Result<()> {
&canvas.to_data_url().map_err(err)?,
&format!(
"{}-{}-LOCAL.png",
field(row, "serialNo"),
field(row, "uasCode")
field(&row, "serialNo"),
field(&row, "uasCode")
),
);
Ok(())
}
fn listen(name: &str, handler: impl FnMut(Event) + 'static) {
let closure = Closure::<dyn FnMut(Event)>::new(handler);
fn listen(name: &str, handler: impl Fn(Event) + 'static) {
let closure = Closure::<dyn Fn(Event)>::new(handler);
document()
.add_event_listener_with_callback(name, closure.as_ref().unchecked_ref())
.unwrap();
closure.forget();
}
pub fn init() {
if let Ok(search) = window().location().search()
&& let Some(encoded) = search
.trim_start_matches('?')
.split('&')
.find_map(|part| part.strip_prefix("q="))
&& let Ok(query) = js_sys::decode_uri_component(encoded)
{
input("history-query").set_value(&String::from(query));
}
let state = Rc::new(RefCell::new(State {
page: 1,
..State::default()
@@ -549,6 +616,14 @@ pub fn init() {
{
let state = state.clone();
listen("input", move |event| {
if event
.target()
.and_then(|t| t.dyn_into::<Element>().ok())
.is_some_and(|t| t.closest("#register-form").ok().flatten().is_some())
{
state.borrow_mut().dirty = true;
text("draft-state", "有未保存的修改");
}
if event
.target()
.and_then(|t| t.dyn_into::<Element>().ok())
@@ -602,21 +677,60 @@ pub fn init() {
}
render_rows(&state);
}
} else if let Some(index) = t
.get_attribute("data-photo-slot")
.and_then(|x| x.parse::<usize>().ok())
.filter(|i| *i < 4)
{
if state.borrow().busy {
return;
}
if let Some(file) = t.files().and_then(|f| f.get(0)) {
if index < 2 {
state.borrow_mut().dirty = true;
text("draft-state", "有未保存的修改");
}
photos::choose(state.borrow().photos.clone(), index, file);
}
} else {
for slot in [1, 2] {
if id == format!("edit-photo-{slot}") {
input(&format!("edit-delete-{slot}")).set_checked(false);
}
if id == format!("edit-delete-{slot}") && t.checked() {
input(&format!("edit-photo-{slot}")).set_value("");
if id == format!("edit-delete-{slot}") && !state.borrow().busy {
photos::delete(&state.borrow().photos, slot + 1, t.checked());
}
}
}
});
}
{
let state = state.clone();
listen("keydown", move |event| {
if let Some(key) = event.dyn_ref::<web_sys::KeyboardEvent>()
&& key.key() == "Escape"
&& state.borrow().menu.is_some()
{
event.prevent_default();
close_menu(&state, true);
}
});
}
{
let state = state.clone();
listen("click", move |event| {
let target = event.target().and_then(|t| t.dyn_into::<Element>().ok());
if target.as_ref().is_some_and(|t| {
t.closest(".registry-popup,.archive-more,#export-toggle")
.ok()
.flatten()
.is_none()
}) {
close_menu(&state, true);
}
if target
.as_ref()
.is_some_and(|t| t.closest(".registry-popup a").ok().flatten().is_some())
{
close_menu(&state, true);
}
let Some(t) = event
.target()
.and_then(|t| t.dyn_into::<Element>().ok())
@@ -626,6 +740,87 @@ pub fn init() {
};
let id = t.id();
let state = state.clone();
if state.borrow().busy {
return;
}
if id == "selection-toggle" {
let selecting = !state.borrow().selecting;
{
let mut s = state.borrow_mut();
s.selecting = selecting;
s.selected.clear();
}
render_rows(&state);
return;
}
if id == "export-toggle" {
toggle_menu(&state, "export-options", "export-toggle");
return;
}
if let Some(index) = t
.get_attribute("data-photo-choose")
.and_then(|x| x.parse::<usize>().ok())
.filter(|i| *i < 4)
{
input(&if index < 2 {
format!("photo-{}", index + 1)
} else {
format!("edit-photo-{}", index - 1)
})
.click();
return;
}
if let Some(index) = t
.get_attribute("data-photo-keep")
.and_then(|x| x.parse::<usize>().ok())
.filter(|i| *i < 4)
{
photos::keep(&state.borrow().photos, index);
return;
}
if let Some(index) = t
.get_attribute("data-photo-remove")
.and_then(|x| x.parse::<usize>().ok())
.filter(|i| *i < 4)
{
photos::remove(&state.borrow().photos, index);
if index < 2 {
state.borrow_mut().dirty = true;
text("draft-state", "有未保存的修改");
}
return;
}
if id == "new-registration" {
if state.borrow().dirty
&& !window()
.confirm_with_message("放弃尚未保存的登记内容并新建?")
.unwrap_or(false)
{
return;
}
for index in 0..2 {
photos::reset(&state.borrow().photos, index, "");
}
state.borrow_mut().dirty = false;
text("draft-state", "保存时校验 SN 与编号");
for id in [
"serial-no",
"model-name",
"owner-name",
"uas-code",
"photo-1",
"photo-2",
] {
input(id).set_value("");
}
state.borrow_mut().active = None;
hidden("record-result", true);
hidden("empty-result", false);
text("form-message", "");
render_rows(&state);
let _ = input("serial-no").focus();
return;
}
if id == "edit-cancel" {
dialog().close();
return;
@@ -648,11 +843,21 @@ pub fn init() {
.find(|r| field(r, "id") == record_id)
.cloned();
let Some(row) = row else { return };
if action == "more" {
toggle_menu(
&state,
&format!("actions-{record_id}"),
&format!("more-{record_id}"),
);
return;
}
close_menu(&state, true);
if action == "edit" {
state.borrow_mut().edit_return = format!("more-{record_id}");
edit(&state, row);
return;
}
if action == "qr" {
if action == "qr" || action == "view" {
draw(&state, row);
return;
}
@@ -710,8 +915,14 @@ pub fn init() {
let page = state.borrow().page;
load(state, page).await
}
"export-excel" => export(state, "excel").await,
"export-archive" => export(state, "archive").await,
"export-excel" => {
close_menu(&state, true);
export(state, "excel").await
}
"export-archive" => {
close_menu(&state, true);
export(state, "archive").await
}
"retry-archive" => {
disabled("retry-archive", true);
let p = api("/api/archive/retry", "POST", Some(json!({}))).await;
@@ -753,6 +964,34 @@ pub fn init() {
.unwrap();
close.forget();
}
{
let state = state.clone();
let closed = Closure::<dyn FnMut(Event)>::new(move |_| {
for index in 2..4 {
photos::reset(&state.borrow().photos, index, "");
}
let target = state.borrow().edit_return.clone();
state.borrow_mut().editing = None;
focus(&target);
});
let _ = el("edit-dialog")
.add_event_listener_with_callback("close", closed.as_ref().unchecked_ref());
closed.forget();
}
{
let state = state.clone();
let unloading = Closure::<dyn FnMut(web_sys::BeforeUnloadEvent)>::new(
move |event: web_sys::BeforeUnloadEvent| {
if state.borrow().busy {
event.prevent_default();
event.set_return_value("正在保存,请稍候");
}
},
);
let _ = window()
.add_event_listener_with_callback("beforeunload", unloading.as_ref().unchecked_ref());
unloading.forget();
}
spawn_local(async move {
if let Err(e) = load(state, 1).await {
message("history-message", &e, true);
+215
View File
@@ -0,0 +1,215 @@
//! Validated photo selections survive cancelled and invalid file replacements.
use super::{el, hidden, input, text};
use base64::{Engine, engine::general_purpose::STANDARD};
use std::{cell::RefCell, rc::Rc};
use wasm_bindgen_futures::{JsFuture, spawn_local};
use web_sys::{File, HtmlImageElement, Url};
pub(super) type Shared = Rc<RefCell<[Slot; 4]>>;
#[derive(Default)]
pub(super) struct Slot {
version: u64,
pending: bool,
chosen: Option<Chosen>,
original: String,
deleted: bool,
error: String,
}
struct Chosen {
data: String,
name: String,
url: String,
}
impl Drop for Chosen {
fn drop(&mut self) {
let _ = Url::revoke_object_url(&self.url);
}
}
fn file_id(index: usize) -> String {
if index < 2 {
format!("photo-{}", index + 1)
} else {
format!("edit-photo-{}", index - 1)
}
}
pub(super) fn render(photos: &Shared, index: usize) {
let slots = photos.borrow();
let slot = &slots[index];
let src = if slot.deleted {
""
} else {
slot.chosen
.as_ref()
.map(|c| c.url.as_str())
.unwrap_or(&slot.original)
};
let preview = el(&format!("slot-preview-{index}"));
if src.is_empty() {
let _ = preview.remove_attribute("src");
} else {
let _ = preview.set_attribute("src", src);
}
hidden(&format!("slot-preview-{index}"), src.is_empty());
text(
&format!("slot-name-{index}"),
if slot.deleted {
"保存时删除现有照片"
} else {
slot.chosen
.as_ref()
.map(|c| c.name.as_str())
.unwrap_or(if slot.original.is_empty() {
"点击选择本地图片"
} else {
"现有照片 · 保留"
})
},
);
hidden(
&format!("slot-remove-{index}"),
slot.chosen.is_none() && !slot.deleted && !slot.pending,
);
hidden(&format!("slot-keep-{index}"), slot.error.is_empty());
let status = el(&format!("slot-status-{index}"));
let _ = status.set_attribute(
"class",
if slot.error.is_empty() {
"photo-status"
} else {
"photo-status error"
},
);
status.set_text_content(Some(if slot.pending {
"正在校验照片…"
} else {
&slot.error
}));
let _ = status.set_attribute("aria-busy", if slot.pending { "true" } else { "false" });
if index >= 2 {
let check = input(&format!("edit-delete-{}", index - 1));
check.set_checked(slot.deleted);
check.set_disabled(
slot.original.is_empty()
|| super::document().body().is_some_and(|b| {
b.get_attribute("data-registry-busy").as_deref() == Some("true")
}),
);
}
}
pub(super) fn reset(photos: &Shared, index: usize, original: &str) {
let version = photos.borrow()[index].version + 1;
photos.borrow_mut()[index] = Slot {
version,
original: original.into(),
..Slot::default()
};
input(&file_id(index)).set_value("");
render(photos, index);
}
pub(super) fn keep(photos: &Shared, index: usize) {
photos.borrow_mut()[index].error.clear();
render(photos, index);
}
pub(super) fn remove(photos: &Shared, index: usize) {
let original = photos.borrow()[index].original.clone();
reset(photos, index, &original);
}
pub(super) fn delete(photos: &Shared, index: usize, deleted: bool) {
remove(photos, index);
photos.borrow_mut()[index].deleted = deleted;
render(photos, index);
}
pub(super) fn pending(photos: &Shared, editing: bool) -> bool {
let offset = if editing { 2 } else { 0 };
photos.borrow()[offset..offset + 2]
.iter()
.any(|s| s.pending)
}
pub(super) fn validation_error(photos: &Shared, editing: bool) -> Option<String> {
let offset = if editing { 2 } else { 0 };
photos.borrow()[offset..offset + 2]
.iter()
.find(|slot| !slot.error.is_empty())
.map(|slot| slot.error.clone())
}
pub(super) fn apply(photos: &Shared, editing: bool, body: &mut serde_json::Value) {
let offset = if editing { 2 } else { 0 };
let slots = photos.borrow();
for (i, slot) in slots[offset..offset + 2].iter().enumerate() {
let key = format!("photo{}", i + 1);
if editing && slot.deleted {
body[key] = serde_json::Value::Null;
} else if let Some(chosen) = &slot.chosen {
body[key] = serde_json::json!(chosen.data);
}
}
}
async fn validate(file: File) -> Result<Chosen, String> {
let mime = file.type_();
if !matches!(mime.as_str(), "image/jpeg" | "image/png" | "image/webp")
|| file.size() <= 0.0
|| file.size() > 5.0 * 1024.0 * 1024.0
{
return Err("照片仅支持 5 MB 以内的 JPG、PNG 或 WebP;原选择已保留".into());
}
let buffer = JsFuture::from(file.array_buffer())
.await
.map_err(|_| "无法读取照片;原选择已保留")?;
let bytes = js_sys::Uint8Array::new(&buffer).to_vec();
let signature = match mime.as_str() {
"image/jpeg" => bytes.starts_with(&[255, 216, 255]),
"image/png" => bytes.starts_with(b"\x89PNG\r\n\x1a\n"),
_ => bytes.starts_with(b"RIFF") && bytes.get(8..12) == Some(b"WEBP"),
};
if !signature {
return Err("照片内容与格式不符;原选择已保留".into());
}
let url = Url::create_object_url_with_blob(&file).map_err(|_| "无法预览照片")?;
let chosen = Chosen {
data: format!("data:{mime};base64,{}", STANDARD.encode(bytes)),
name: file.name(),
url,
};
let image = HtmlImageElement::new().map_err(|_| "图片组件不可用")?;
image.set_src(&chosen.url);
JsFuture::from(image.decode())
.await
.map_err(|_| "照片损坏,无法解码;原选择已保留")?;
if image.natural_width() == 0 || image.natural_height() == 0 {
return Err("照片尺寸无效;原选择已保留".into());
}
Ok(chosen)
}
pub(super) fn choose(photos: Shared, index: usize, file: File) {
let version = {
let mut slots = photos.borrow_mut();
let slot = &mut slots[index];
slot.version += 1;
slot.pending = true;
slot.error.clear();
slot.version
};
// The File is captured, so clearing the picker also permits choosing the same file again.
input(&file_id(index)).set_value("");
render(&photos, index);
spawn_local(async move {
let result = validate(file).await;
{
let mut slots = photos.borrow_mut();
let slot = &mut slots[index];
if slot.version != version {
return;
}
slot.pending = false;
match result {
Ok(chosen) => {
slot.chosen = Some(chosen);
slot.deleted = false;
slot.error.clear();
}
Err(error) => slot.error = error,
}
}
render(&photos, index);
});
}
File diff suppressed because one or more lines are too long
+595
View File
@@ -0,0 +1,595 @@
//! Shared navigation and application-owned appearance settings; registration stays in registry.rs.
use base64::{Engine, engine::general_purpose::STANDARD};
use gloo_net::http::Request;
use gloo_timers::future::TimeoutFuture;
use serde_json::{Value, json};
use std::{cell::RefCell, rc::Rc};
use wasm_bindgen::{JsCast, JsValue, closure::Closure};
use wasm_bindgen_futures::{JsFuture, spawn_local};
use web_sys::{
Element, Event, HtmlCanvasElement, HtmlElement, HtmlImageElement, HtmlInputElement,
HtmlSelectElement,
};
struct State {
prefs: Value,
generation: u64,
busy: bool,
ready: bool,
dirty: bool,
}
type Shared = Rc<RefCell<State>>;
fn document() -> web_sys::Document {
web_sys::window()
.expect("browser window")
.document()
.expect("browser document")
}
fn el(id: &str) -> Option<Element> {
document().get_element_by_id(id)
}
fn text(id: &str, value: &str) {
if let Some(e) = el(id) {
e.set_text_content(Some(value));
}
}
fn hidden(id: &str, hide: bool) {
if let Some(e) = el(id) {
if hide {
let _ = e.set_attribute("hidden", "");
} else {
let _ = e.remove_attribute("hidden");
}
}
}
fn message(value: &str, error: bool) {
text("wall-message", value);
if let Some(e) = el("wall-message") {
let _ = e.set_attribute(
"class",
if error {
"wall-message error"
} else {
"wall-message success"
},
);
}
}
fn each(selector: &str, mut f: impl FnMut(Element)) {
if let Ok(list) = document().query_selector_all(selector) {
for i in 0..list.length() {
if let Some(e) = list.item(i).and_then(|n| n.dyn_into().ok()) {
f(e);
}
}
}
}
fn apply(state: &Shared) {
let s = state.borrow();
let p = &s.prefs;
let theme = p["theme"].as_str().unwrap_or("graphite");
if let Some(body) = document().body() {
let _ = body.set_attribute("data-theme", theme);
let _ = body.set_attribute(
"data-custom-wallpaper",
if p["image"].is_string() {
"true"
} else {
"false"
},
);
let _ = body.set_attribute("class", &format!("b R2 theme-{theme}"));
}
let image = p["image"].as_str().map(str::to_owned).unwrap_or_else(|| {
format!(
"/wallpapers/{}-wallpaper.svg",
p["wallpaper"].as_str().unwrap_or("B4")
)
});
if let Some(w) = el("workspace-wallpaper") {
let _ = w.set_attribute("src", &image);
if let Some(e) = w.dyn_ref::<HtmlElement>() {
let _ = e
.style()
.set_property("object-fit", p["fit"].as_str().unwrap_or("cover"));
}
}
if let Some(root) = document()
.document_element()
.and_then(|e| e.dyn_into::<HtmlElement>().ok())
{
let _ = root.style().set_property(
"--wall-shade",
&(p["dim"].as_f64().unwrap_or(14.0) / 100.0).to_string(),
);
let _ = root
.style()
.set_property("--wall-blur", &format!("{}px", p["blur"]));
}
for id in ["dim", "blur"] {
if let Some(input) = el(id).and_then(|e| e.dyn_into::<HtmlInputElement>().ok()) {
input.set_value(&p[id].to_string());
}
text(
&format!("{id}-output"),
&format!("{}{}", p[id], if id == "dim" { "%" } else { " px" }),
);
}
if let Some(fit) = el("fit").and_then(|e| e.dyn_into::<HtmlSelectElement>().ok()) {
fit.set_value(p["fit"].as_str().unwrap_or("cover"));
}
text(
"theme-name",
match theme {
"blue" => "深蓝玻璃",
"white" => "透明白玻璃",
_ => "石墨玻璃",
},
);
each("[data-theme]", |e| {
if e.tag_name() == "BODY" {
return;
}
let active = e.get_attribute("data-theme").as_deref() == Some(theme);
let _ = e.set_attribute("aria-pressed", if active { "true" } else { "false" });
let classes = e
.get_attribute("class")
.unwrap_or_default()
.split_whitespace()
.filter(|c| *c != "active")
.collect::<Vec<_>>()
.join(" ");
let _ = e.set_attribute(
"class",
&format!("{classes}{}", if active { " active" } else { "" }),
);
});
each("[data-wall]", |e| {
let active = p["image"].is_null()
&& e.get_attribute("data-wall").as_deref() == p["wallpaper"].as_str();
let _ = e.set_attribute("aria-pressed", if active { "true" } else { "false" });
let _ = e.set_attribute(
"class",
if active {
"wall-choice active"
} else {
"wall-choice"
},
);
});
if let Some(sample) = el("desktop-sample").and_then(|e| e.dyn_into::<HtmlElement>().ok()) {
let _ = sample
.style()
.set_property("background-image", &format!("url(\"{image}\")"));
}
}
async fn fetch_preferences(state: Shared) {
let result = async {
let r = Request::get("/api/appearance")
.send()
.await
.map_err(|e| e.to_string())?;
if !r.ok() {
return Err("无法读取本机外观设置".into());
}
r.json::<Value>().await.map_err(|e| e.to_string())
}
.await;
match result {
Ok(p) => {
let mut s = state.borrow_mut();
if s.busy || s.dirty {
return;
}
s.prefs = p;
s.ready = true;
drop(s);
apply(&state);
}
Err(e) => message(&e, true),
}
}
fn queue_save(state: Shared) {
let generation = {
let mut s = state.borrow_mut();
s.generation += 1;
s.dirty = true;
s.generation
};
apply(&state);
message("正在保存到本机…", false);
spawn_local(async move {
TimeoutFuture::new(250).await;
{
let mut s = state.borrow_mut();
if s.generation != generation || s.busy || !s.ready {
return;
}
s.busy = true;
}
loop {
let (body, version) = {
let s = state.borrow();
(s.prefs.clone(), s.generation)
};
let result = async {
let r = Request::patch("/api/appearance")
.json(&body)
.map_err(|e| e.to_string())?
.send()
.await
.map_err(|e| e.to_string())?;
let p = r.json::<Value>().await.map_err(|e| e.to_string())?;
if !r.ok() {
return Err(p["error"].as_str().unwrap_or("保存失败").to_owned());
}
Ok(p)
}
.await;
match result {
Ok(saved) => {
let mut s = state.borrow_mut();
s.prefs["revision"] = saved["revision"].clone();
if s.generation == version {
s.busy = false;
s.dirty = false;
drop(s);
message(
"已保存到本机应用,其他浏览器重新打开设置后使用同一外观。",
false,
);
break;
}
}
Err(e) => {
{
let mut s = state.borrow_mut();
s.busy = false;
s.dirty = false;
}
fetch_preferences(state.clone()).await;
message(&e, true);
break;
}
}
}
});
}
fn show(view: &str, realtime: bool) {
let previous = document()
.body()
.and_then(|body| body.get_attribute("data-screen"));
let view = match view {
"register" | "realtime" | "settings" => view,
_ => "home",
};
if (view == "realtime" && !realtime) || (view == "register" && realtime) {
let _ = web_sys::window()
.expect("browser")
.location()
.set_href(if view == "realtime" {
"/realtime"
} else {
"/?app=register"
});
return;
}
hidden("workspace-content", view == "home" || view == "settings");
hidden("appearance-view", view != "settings");
hidden("home-top", view != "home");
if let Ok(Some(header)) = document().query_selector(".reference-top") {
if view == "home" {
let _ = header.set_attribute("hidden", "");
} else {
let _ = header.remove_attribute("hidden");
}
}
each(".homescreen", |e| {
if view == "home" {
let _ = e.remove_attribute("hidden");
} else {
let _ = e.set_attribute("hidden", "");
}
});
if let Some(body) = document().body() {
let _ = body.set_attribute("data-screen", view);
}
text(
"reference-title",
match view {
"register" => "设备登记",
"realtime" => "实时目标工作台",
"settings" => "壁纸与外观",
_ => "应用总览",
},
);
each("[data-menu]", |e| {
if e.get_attribute("data-menu").as_deref() == Some(view) {
let _ = e.set_attribute("aria-current", "page");
} else {
let _ = e.remove_attribute("aria-current");
}
});
if view == "home" {
if let Some(previous) =
previous.filter(|p| matches!(p.as_str(), "register" | "realtime" | "settings"))
&& let Some(card) =
el(&format!("home-app-{previous}")).and_then(|e| e.dyn_into::<HtmlElement>().ok())
{
let _ = card.focus();
}
} else if previous.as_deref() == Some("home") {
let region = if view == "settings" {
"appearance-view"
} else {
"workspace-content"
};
if let Some(element) = el(region).and_then(|e| e.dyn_into::<HtmlElement>().ok()) {
let _ = element.set_attribute("tabindex", "-1");
let _ = element.focus();
}
}
if view == "realtime"
&& let Some(w) = web_sys::window()
&& let Ok(event) = Event::new("resize")
{
let _ = w.dispatch_event(&event);
}
}
async fn upload(state: Shared, input: HtmlInputElement) -> std::result::Result<(), String> {
let Some(file) = input.files().and_then(|f| f.get(0)) else {
return Ok(());
};
input.set_value("");
if !matches!(
file.type_().as_str(),
"image/jpeg" | "image/png" | "image/webp"
) || file.size() > 8.0 * 1024.0 * 1024.0
{
return Err("请选择 8 MB 以内的 JPG、PNG 或 WebP 图片。".into());
}
let data = JsFuture::from(file.array_buffer())
.await
.map_err(|_| "无法读取壁纸")?;
let image = HtmlImageElement::new().map_err(|_| "图片组件不可用")?;
image.set_src(&format!(
"data:{};base64,{}",
file.type_(),
STANDARD.encode(js_sys::Uint8Array::new(&data).to_vec())
));
JsFuture::from(image.decode())
.await
.map_err(|_| "图片损坏,无法读取")?;
let (w, h) = (image.natural_width(), image.natural_height());
if w == 0 || h == 0 || u64::from(w) * u64::from(h) > 60_000_000 {
return Err("壁纸尺寸过大或无效".into());
}
let scale = (2560.0 / f64::from(w.max(h))).min(1.0);
let canvas: HtmlCanvasElement = document()
.create_element("canvas")
.map_err(|_| "画布不可用")?
.unchecked_into();
canvas.set_width((f64::from(w) * scale) as u32);
canvas.set_height((f64::from(h) * scale) as u32);
let ctx: web_sys::CanvasRenderingContext2d = canvas
.get_context("2d")
.map_err(|_| "画布不可用")?
.ok_or("画布不可用")?
.unchecked_into();
ctx.draw_image_with_html_image_element_and_dw_and_dh(
&image,
0.0,
0.0,
f64::from(canvas.width()),
f64::from(canvas.height()),
)
.map_err(|_| "无法处理壁纸")?;
let encoded = canvas
.to_data_url_with_type_and_encoder_options("image/jpeg", &JsValue::from_f64(0.82))
.map_err(|_| "无法压缩壁纸")?;
if encoded.len() > 2_700_000 {
return Err("壁纸压缩后仍过大,请选择较小图片".into());
}
state.borrow_mut().prefs["image"] = json!(encoded);
queue_save(state);
Ok(())
}
fn listen(event: &str, callback: impl Fn(Event) + 'static) {
let handler = Closure::<dyn Fn(Event)>::new(callback);
let _ = document().add_event_listener_with_callback(event, handler.as_ref().unchecked_ref());
handler.forget();
}
pub fn init(realtime: bool) {
// A restored document must recreate its terminated realtime worker and WebGL map.
let restored = Closure::<dyn FnMut(Event)>::new(move |event: Event| {
if js_sys::Reflect::get(event.as_ref(), &"persisted".into())
.ok()
.and_then(|v| v.as_bool())
== Some(true)
&& let Some(window) = web_sys::window()
{
let _ = window.location().reload();
}
});
if let Some(window) = web_sys::window() {
let _ =
window.add_event_listener_with_callback("pageshow", restored.as_ref().unchecked_ref());
}
restored.forget();
let state = Rc::new(RefCell::new(State {
prefs: json!({"theme":"graphite","wallpaper":"B4","dim":14,"blur":0,"fit":"cover","image":null,"revision":0}),
generation: 0,
busy: false,
ready: false,
dirty: false,
}));
apply(&state);
if let Some(body) = document().body() {
let collapsed = web_sys::window()
.and_then(|w| w.session_storage().ok().flatten())
.and_then(|s| s.get_item("rid.workspace.menu-hidden").ok().flatten())
.as_deref()
== Some("true");
let _ = body.set_attribute("data-menu-hidden", if collapsed { "true" } else { "false" });
if let Some(button) = el("toggle-menu") {
let _ = button.set_attribute("aria-expanded", if collapsed { "false" } else { "true" });
let _ = button.set_attribute(
"aria-label",
if collapsed {
"展开菜单"
} else {
"收起菜单"
},
);
}
}
let search = web_sys::window()
.and_then(|w| w.location().search().ok())
.unwrap_or_default();
show(
if realtime {
"realtime"
} else if search.contains("app=register") {
"register"
} else {
"home"
},
realtime,
);
let initial = state.clone();
spawn_local(async move {
fetch_preferences(initial).await;
});
let clicked = state.clone();
listen("click", move |event| {
let Some(button) = event
.target()
.and_then(|e| e.dyn_into::<Element>().ok())
.and_then(|e| e.closest("button").ok().flatten())
else {
return;
};
if document()
.body()
.is_some_and(|b| b.get_attribute("data-registry-busy").as_deref() == Some("true"))
&& (button.has_attribute("data-home") || button.has_attribute("data-open"))
{
event.prevent_default();
return;
}
if button.has_attribute("data-home") {
show("home", realtime);
return;
}
if let Some(view) = button.get_attribute("data-open") {
show(&view, realtime);
if view == "settings" {
let s = clicked.clone();
spawn_local(async move {
fetch_preferences(s).await;
});
}
return;
}
if let Some(theme) = button.get_attribute("data-theme") {
if clicked.borrow().ready {
clicked.borrow_mut().prefs["theme"] = json!(theme);
queue_save(clicked.clone());
}
return;
}
if let Some(wall) = button.get_attribute("data-wall") {
if clicked.borrow().ready {
let mut s = clicked.borrow_mut();
s.prefs["wallpaper"] = json!(wall);
s.prefs["image"] = Value::Null;
drop(s);
queue_save(clicked.clone());
}
return;
}
match button.id().as_str() {
"toggle-menu" => {
if let Some(body) = document().body() {
let hide = body.get_attribute("data-menu-hidden").as_deref() != Some("true");
let _ =
body.set_attribute("data-menu-hidden", if hide { "true" } else { "false" });
let _ =
button.set_attribute("aria-expanded", if hide { "false" } else { "true" });
let _ = button
.set_attribute("aria-label", if hide { "展开菜单" } else { "收起菜单" });
if let Some(storage) =
web_sys::window().and_then(|w| w.session_storage().ok().flatten())
{
let _ = storage.set_item(
"rid.workspace.menu-hidden",
if hide { "true" } else { "false" },
);
}
}
}
"choose-wallpaper" => {
if let Some(f) =
el("custom-wallpaper").and_then(|e| e.dyn_into::<HtmlInputElement>().ok())
{
f.click();
}
}
"reset-wallpaper" => {
if clicked.borrow().ready {
let rev = clicked.borrow().prefs["revision"].clone();
clicked.borrow_mut().prefs = json!({"theme":"graphite","wallpaper":"B4","dim":14,"blur":0,"fit":"cover","image":null,"revision":rev});
queue_save(clicked.clone());
}
}
"full-screen" => {
if document().fullscreen_element().is_some() {
document().exit_fullscreen();
} else if let Some(root) = document().document_element() {
let _ = root.request_fullscreen();
}
}
_ => {}
}
});
let changed = state.clone();
listen("input", move |event| {
let Some(input) = event
.target()
.and_then(|e| e.dyn_into::<HtmlInputElement>().ok())
else {
return;
};
if matches!(input.id().as_str(), "dim" | "blur")
&& changed.borrow().ready
&& let Ok(n) = input.value().parse::<u8>()
{
changed.borrow_mut().prefs[input.id()] = json!(n);
queue_save(changed.clone());
}
});
listen("change", move |event| {
let Some(e) = event.target().and_then(|e| e.dyn_into::<Element>().ok()) else {
return;
};
if !state.borrow().ready {
message("外观尚未加载,请稍后再试。", true);
return;
}
if e.id() == "fit" {
if let Ok(select) = e.dyn_into::<HtmlSelectElement>() {
state.borrow_mut().prefs["fit"] = json!(select.value());
queue_save(state.clone());
}
} else if e.id() == "custom-wallpaper"
&& let Ok(input) = e.dyn_into::<HtmlInputElement>()
{
let state = state.clone();
spawn_local(async move {
if let Err(e) = upload(state, input).await {
message(&e, true);
}
});
}
});
}