feat(target-lists): 新增黑白名单管理与实时告警功能

- rid-shared 新增 target_lists 模块,定义名单数据契约
- 地图适配器支持按名单类型着色渲染目标(白/黑/未知)
- 新增名单筛选器与目标目录过滤联动
- 实时详情面板支持加入/编辑白名单与黑名单操作
- 新增黑名单命中告警横幅与事件日志高亮
- 新增名单管理浮层(Manager 组件)与徽章展示
- 底图默认切换为影像图,相机初始俯仰角归零
- color-scheme 切换为 dark,新增 glass/workbench 样式
```
This commit is contained in:
2026-10-23 09:12:50 +08:00
parent 3cf50f2e8b
commit df9e8bdeb5
24 changed files with 1481 additions and 120 deletions
+2
View File
@@ -1,6 +1,8 @@
//! Versioned synthetic telemetry contract. This is not a device wire protocol.
use serde::{Deserialize, Serialize};
pub mod target_lists;
pub const PROTOCOL_VERSION: u16 = 1;
pub const MAX_BATCH: usize = 4096;
+97
View File
@@ -0,0 +1,97 @@
//! Manual target classification, independent of registration and telemetry transport.
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
pub const MAX_ENTRIES: usize = 5000;
pub const MAX_NOTE_CHARS: usize = 200;
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ListKind {
White,
Black,
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct Entry {
pub target_id: String,
pub list_kind: ListKind,
pub note: String,
pub updated_at: String,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
pub struct Snapshot {
pub revision: u64,
pub entries: Vec<Entry>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Mutation {
pub list_kind: ListKind,
#[serde(default)]
pub note: String,
pub expected_revision: u64,
}
pub fn valid_target_id(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 64
&& value
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
/// Alert once per continuous active black-list membership, including list changes.
#[derive(Default)]
pub struct AlertTracker {
active_black: HashSet<String>,
}
impl AlertTracker {
pub fn update(&mut self, active: &[String], kinds: &HashMap<String, ListKind>) -> Vec<String> {
let current: HashSet<_> = active
.iter()
.filter(|id| kinds.get(*id) == Some(&ListKind::Black))
.cloned()
.collect();
let mut newly_active: Vec<_> = current.difference(&self.active_black).cloned().collect();
newly_active.sort();
self.active_black = current;
newly_active
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn identities_match_telemetry_limits_without_case_folding() {
assert!(valid_target_id(&"A".repeat(64)));
assert!(valid_target_id("Drone_01-a"));
for value in ["", "with space", "路径", "../id", &"X".repeat(65)] {
assert!(!valid_target_id(value));
}
}
#[test]
fn alerts_are_independent_of_frames_notes_and_view_filters() {
let mut tracker = AlertTracker::default();
let active = vec!["A".into(), "a".into()];
let mut kinds = HashMap::from([("A".into(), ListKind::Black)]);
assert_eq!(tracker.update(&active, &kinds), vec!["A"]);
for _ in 0..100 {
assert!(tracker.update(&active, &kinds).is_empty());
}
kinds.insert("a".into(), ListKind::White);
assert!(tracker.update(&active, &kinds).is_empty());
kinds.insert("A".into(), ListKind::White);
assert!(tracker.update(&active, &kinds).is_empty());
kinds.insert("A".into(), ListKind::Black);
assert_eq!(tracker.update(&active, &kinds), vec!["A"]);
assert!(tracker.update(&[], &kinds).is_empty());
assert_eq!(tracker.update(&active, &kinds), vec!["A"]);
}
}
+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 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>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="dark"><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 data-trunk rel="copy-file" href="public/glass.css"><link rel="stylesheet" href="/glass.css"><link data-trunk rel="copy-file" href="public/workbench.css"><link rel="stylesheet" href="/workbench.css"><link data-trunk rel="copy-file" href="public/target-lists.css"><link rel="stylesheet" href="/target-lists.css"><link rel="icon" href="/fpv-rid-icon.png"></head><body></body></html>
+104
View File
@@ -0,0 +1,104 @@
/* Approved A+C material. Loaded last so legacy theme preferences share one appearance. */
html { background: #020b18; }
:root {
color-scheme: dark;
--glass-base: #020b18;
--glass-workspace: rgba(2, 11, 24, .65);
--glass-surface: rgba(6, 18, 33, .40);
--glass-solid: rgba(6, 18, 33, .94);
--glass-edge: rgba(179, 213, 255, .32);
--glass-filter: blur(7px) saturate(120%);
--glass-action: #245d9d;
}
body.b {
color-scheme: dark;
--work-text: #e9f0fa;
--work-muted: #b5c6d9;
--work-line: var(--glass-edge);
--work-panel: var(--glass-surface);
--work-input: rgba(2, 11, 24, .58);
--mc-bg: var(--glass-base);
--mc-text: var(--work-text);
--mc-text-muted: var(--work-muted);
--mc-text-dim: var(--work-muted);
--mc-panel-bg: var(--glass-surface);
--mc-panel-dense: var(--glass-solid);
--mc-panel-raised: var(--glass-surface);
--mc-panel-card: rgba(6, 18, 33, .16);
--mc-border: var(--glass-edge);
--mc-panel-blur: var(--glass-filter);
--mc-accent: #8bbdff;
--mc-accent-blue: var(--glass-action);
--mc-success: #81d8af;
--mc-warning: #ffd08a;
--mc-danger: #ffaaa4;
background: transparent;
color: var(--work-text);
}
body.b .bg { background: var(--glass-base); }
body.b .workspace-pane {
background: transparent;
backdrop-filter: none;
-webkit-backdrop-filter: none;
}
body.b :is(.reference-top, .reference-rail, .home-top, .home-card, .mc-floating-panel, .mc-hud-dock, .live-dock-restore, .mc-map-toolstrip, .mc-map-infobar, .native-group, .glass) {
background: var(--glass-surface);
border-color: var(--glass-edge);
color: var(--work-text);
backdrop-filter: var(--glass-filter);
-webkit-backdrop-filter: var(--glass-filter);
box-shadow: 0 12px 26px #0005, inset 0 1px 0 #ffffff12;
}
body.b .home-launcher.homescreen { background: none; backdrop-filter: none; }
body.b .home-card:hover {
background: rgba(6, 18, 33, .56);
border-color: #b3d5ff80;
}
body.b .registry-workspace .registry-group {
background: var(--glass-surface);
backdrop-filter: var(--glass-filter);
-webkit-backdrop-filter: var(--glass-filter);
}
body.b :is(.registration-savebar, .registry-popup, #edit-dialog) {
background: var(--glass-solid);
backdrop-filter: var(--glass-filter);
-webkit-backdrop-filter: var(--glass-filter);
}
body.b #edit-dialog::backdrop { background: rgba(2, 11, 24, .65); }
body.b :is(.primary, .registry-workspace .primary, #edit-dialog .primary) {
background: var(--glass-action);
color: #fff;
border-color: var(--glass-edge);
box-shadow: none;
}
body.b :is(.primary, .registry-workspace .primary, #edit-dialog .primary):hover:not(:disabled) { background: #2c6cb1; }
body.b :is(input, select, textarea) { color-scheme: dark; color: var(--work-text); }
body.b option, body.b .mc-layout-b .live-basemap option { background: var(--glass-base); color: var(--work-text); }
body.b :is(.micro, .muted, .tiny, .rt-muted, .setting-status, .reference-local, .section-caption span, .setting-row small) { color: var(--work-muted); }
body.b .mc-layout-b .mc-tag { color: var(--mc-success); }
body.b :is(button, a, input, select, textarea):focus-visible { outline: 2px solid #8bbdff; outline-offset: 3px; }
.glass-material-note { padding: 15px 18px; border: 1px solid var(--work-line); border-radius: 12px; background: var(--glass-surface); margin-bottom: 15px; }
.glass-material-note p { margin-top: 7px; color: var(--work-muted); font-size: 13px; line-height: 1.8; }
@supports not ((backdrop-filter: blur(7px)) or (-webkit-backdrop-filter: blur(7px))) {
body.b { --glass-surface: rgba(6, 18, 33, .94); }
}
body.b .desktop-sample::before { background: var(--glass-surface); border-color: var(--glass-edge); backdrop-filter: var(--glass-filter); -webkit-backdrop-filter: var(--glass-filter); }
/* Fill the desktop for raster uploads as well as intrinsic-size SVG wallpapers. */
body.b .bg img {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
filter: blur(var(--wall-blur)) !important;
}
/* One shared A-tone veil behind the UI, rather than stacking it on each workspace. */
body.b .bg::after {
background: linear-gradient(var(--glass-workspace), var(--glass-workspace)), rgba(0, 0, 0, var(--wall-shade));
}
body.b[data-custom-wallpaper="true"] .home-launcher.homescreen { background: none !important; }
/* Restore collapsed panels without bringing back the removed map toolbar. */
.live-panel-restores { position: absolute; top: 16px; left: 16px; display: flex; gap: 8px; z-index: 6; }
body.b .live-panel-restores button { background: var(--glass-solid); border-color: var(--work-line); color: var(--work-text); font-size: 12px; padding: 7px 12px; }
-2
View File
@@ -1,6 +1,4 @@
/* 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}
+18 -13
View File
@@ -5,18 +5,22 @@ let map, layer, latest, ids = [], selected = '', pending = false;
let frameTimes = [], lastFrame = 0;
let marker=null, history=[], lastTrail=0;
let centered=false, workerWasmBytes=0, resizeObserver;
let basemap="road",tileRevision=0,mapCreations=0;
let basemap="imagery",tileRevision=0,mapCreations=0;
const basemapLayers={road:["vec_w","cva_w"],imagery:["img_w","cia_w"]};
function tileUrl(index){return `/api/maps/tile/${basemapLayers[basemap][index]}/{z}/{x}/{y}?v=${tileRevision}`;}
let classification=new Map(),listFilter="all";
function targetKind(id){return classification.get(id)||"unknown";}
function targetVisible(id){return listFilter==="all"||targetKind(id)===listFilter;}
function setClassification(value,filter="all"){classification=new Map(Object.entries(value||{}).filter(([,kind])=>kind==="white"||kind==="black"));listFilter=["white","black","unknown"].includes(filter)?filter:"all";flush();}
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;
}
function create(container,initialBasemap="road") {
basemap=initialBasemap==="imagery"?"imagery":"road";mapCreations++;
function create(container,initialBasemap="imagery") {
basemap=initialBasemap==="road"?"road":"imagery";mapCreations++;
if (map) map.remove();
map=new maplibre.Map({container,center:[120.1538,30.2874],zoom:11,pitch:35,bearing:0,attributionControl:false,
map=new maplibre.Map({container,center:[120.1538,30.2874],zoom:11,pitch:0,bearing:0,attributionControl:false,
style:{version:8,sources:{
'tdt-base':{type:'raster',tiles:[tileUrl(0)],tileSize:256,maxzoom:18,attribution:'天地图 © 自然资源部 / 本地缓存与离线资源'},
'tdt-labels':{type:'raster',tiles:[tileUrl(1)],tileSize:256,maxzoom:18}
@@ -36,7 +40,7 @@ function create(container,initialBasemap="road") {
precision highp float; in vec2 shape; in vec4 target; uniform mat4 matrix; uniform vec2 pixel; uniform float bearing; out float chosen;
void main(){vec4 p=matrix*vec4(target.xy,0.,1.);float c=cos(target.z+bearing),s=sin(target.z+bearing);vec2 q=vec2(shape.x*c-shape.y*s,shape.x*s+shape.y*c);p.xy+=q*pixel*p.w;gl_Position=p;chosen=target.w;}`);
this.fs=shader(gl,gl.FRAGMENT_SHADER,`#version 300 es
precision highp float; in float chosen; out vec4 color; void main(){color=mix(vec4(.22,.74,.97,1.),vec4(1.,.75,.15,1.),chosen);}`);
precision highp float; in float chosen; out vec4 color; void main(){float kind=floor(chosen/2.);float picked=mod(chosen,2.);vec4 base=kind>1.5?vec4(.98,.42,.39,1.):kind>.5?vec4(.38,.82,.63,1.):vec4(.22,.74,.97,1.);color=kind<.5?mix(base,vec4(1.,.75,.15,1.),picked):mix(base,vec4(1.),picked*.25);}`);
gl.attachShader(this.program,this.vs);gl.attachShader(this.program,this.fs);gl.linkProgram(this.program);
if (!gl.getProgramParameter(this.program,gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(this.program));
this.vao=gl.createVertexArray();gl.bindVertexArray(this.vao);
@@ -82,7 +86,7 @@ function create(container,initialBasemap="road") {
});
map.on('click',event=>{
if(!latest)return;let index=-1,distance=18;
for(let i=0;i<ids.length;i++){const p=map.project([latest[i*4],latest[i*4+1]]);const d=Math.hypot(p.x-event.point.x,p.y-event.point.y);if(d<distance){index=i;distance=d;}}
for(let i=0;i<ids.length;i++){if(!targetVisible(ids[i]))continue;const p=map.project([latest[i*4],latest[i*4+1]]);const d=Math.hypot(p.x-event.point.x,p.y-event.point.y);if(d<distance){index=i;distance=d;}}
if(index>=0)window.dispatchEvent(new CustomEvent('rid-select',{detail:ids[index]}));
});
map.on('error',e=>{if(!e.sourceId?.startsWith('tdt-'))console.error('map:',e.error?.message || e);});
@@ -90,23 +94,23 @@ function create(container,initialBasemap="road") {
}
function flush(){
pending=false;if(!latest||!layer?.gl)return;const gl=layer.gl;
const data=new Float32Array(ids.length*4);for(let i=0;i<ids.length;i++){const p=maplibre.MercatorCoordinate.fromLngLat([latest[i*4],latest[i*4+1]]);data[i*4]=p.x-layer.origin.x;data[i*4+1]=p.y-layer.origin.y;data[i*4+2]=-latest[i*4+3]*Math.PI/180;data[i*4+3]=ids[i]===selected?1:0;}
gl.bindBuffer(gl.ARRAY_BUFFER,layer.instances);gl.bufferSubData(gl.ARRAY_BUFFER,0,data);layer.count=ids.length;map.triggerRepaint();
const data=new Float32Array(ids.length*4);let visible=0;for(let i=0;i<ids.length;i++){if(!targetVisible(ids[i]))continue;const j=visible++;const p=maplibre.MercatorCoordinate.fromLngLat([latest[i*4],latest[i*4+1]]);data[j*4]=p.x-layer.origin.x;data[j*4+1]=p.y-layer.origin.y;data[j*4+2]=-latest[i*4+3]*Math.PI/180;const kind=targetKind(ids[i]);data[j*4+3]=(kind==="black"?4:kind==="white"?2:0)+(ids[i]===selected?1:0);}
gl.bindBuffer(gl.ARRAY_BUFFER,layer.instances);gl.bufferSubData(gl.ARRAY_BUFFER,0,data);layer.count=visible;map.triggerRepaint();
const index=ids.indexOf(selected);
if(index>=0){
if(index>=0&&targetVisible(selected)){
const coordinate=[latest[index*4],latest[index*4+1]];
if(!marker){const label=document.createElement('div');label.className='rt-target-label';marker=new maplibre.Marker({element:label,anchor:'bottom'}).setLngLat(coordinate).addTo(map);}
marker.getElement().textContent=selected;marker.setLngLat(coordinate);
marker.getElement().textContent=selected+(targetKind(selected)==="black"?" · 黑名单":targetKind(selected)==="white"?" · 白名单":"");marker.getElement().dataset.listKind=targetKind(selected);marker.setLngLat(coordinate);
const now=performance.now();if(now-lastTrail>=100){lastTrail=now;history.push({time:now,coordinate});history=history.filter(p=>now-p.time<30000).slice(-200);
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;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');const projected=map&&latest&&ids.includes(selected)?map.project([latest[ids.indexOf(selected)*4],latest[ids.indexOf(selected)*4+1]]):null;return {basemap,mapCreations,camera:map?{center:map.getCenter().toArray(),zoom:map.getZoom(),pitch:map.getPitch(),bearing:map.getBearing()}:null,baseTiles:map?.getSource('tdt-base')?.tiles,labelTiles:map?.getSource('tdt-labels')?.tiles,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 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 {basemap,mapCreations,camera:map?{center:map.getCenter().toArray(),zoom:map.getZoom(),pitch:map.getPitch(),bearing:map.getBearing()}:null,baseTiles:map?.getSource('tdt-base')?.tiles,labelTiles:map?.getSource('tdt-labels')?.tiles,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,visibleTargets:ids.filter(targetVisible).length,listFilter,classifiedTargets:{white:ids.filter(id=>targetKind(id)==="white").length,black:ids.filter(id=>targetKind(id)==="black").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(){tileRevision++;for(const [i,id]of ['tdt-base','tdt-labels'].entries())map?.getSource(id)?.setTiles([tileUrl(i)]);}
function setBasemap(value){const next=value==='imagery'?'imagery':'road';if(next!==basemap){basemap=next;refresh();}}
function setBasemap(value){const next=value==='road'?'road':'imagery';if(next!==basemap){basemap=next;refresh();}}
function baseReady(ready){if(map?.getLayer('grid'))map.setLayoutProperty('grid','visibility',ready?'none':'visible');}
function setOcclusion(value){
occlusion=Object.fromEntries(['top','right','bottom','left'].map(k=>[k,Number.isFinite(value?.[k])?Math.max(0,value[k]):0]));
@@ -118,6 +122,7 @@ function visiblePadding(){
// 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 manager=document.getElementById("rt-list-manager")?.getBoundingClientRect();if(manager?.height)p.right=Math.max(p.right,(root.right-manager.left)/scale+12);
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;}
@@ -131,4 +136,4 @@ function focusCoordinate(center,animate=true){
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,setBasemap,baseReady,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};}};
window.ridMap={workerMemory(bytes){if(Number.isFinite(bytes))workerWasmBytes=bytes;},create,update,select,metrics,connection,refresh,setBasemap,setClassification,baseReady,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;classification=new Map();listFilter="all";occlusion={top:0,right:0,bottom:0,left:0};}};
+76
View File
@@ -0,0 +1,76 @@
/* Approved A: manual target classification and an on-demand management drawer. */
.rt-list-badge { display: inline-flex; align-items: center; flex: none; border: 1px solid #b5c6d946; border-radius: 4px; padding: 3px 5px; font-size: 10px; line-height: 1.3; color: #c2d0df; background: #b5c6d90b; white-space: nowrap; }
.rt-list-badge::before { content: '○'; margin-right: 4px; }
.rt-list-badge[data-kind=white] { color: #9edac1; border-color: #9edac14a; background: #69bd9712; }
.rt-list-badge[data-kind=white]::before { content: '✓'; }
.rt-list-badge[data-kind=black] { color: #ffb1a9; border-color: #ffb1a94a; background: #d35e5712; }
.rt-list-badge[data-kind=black]::before { content: '!'; font-weight: 700; }
.rt-target-id { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.mc-layout-b .rt-target { gap: 7px; }
.mc-layout-b #rt-list-manager-from-directory { font-size: 11px; padding: 6px; white-space: nowrap; min-width: 0; }
.rt-target-list-filters { display: flex; flex-wrap: wrap; gap: 5px; margin-top: 10px; }
.mc-layout-b .rt-target-list-filters button { font-size: 10px; padding: 5px 6px; border: 1px solid var(--work-line); border-radius: 5px; color: var(--work-text); background: #8bbdff08; }
.mc-layout-b .rt-target-list-filters button[aria-pressed=true], .rt-list-tabs button[aria-pressed=true] { background: #8bbdff24; border-color: #8bbdff99; }
.rt-detail-classification { margin: 18px 0; padding: 15px 0; border-top: 1px solid var(--work-line); border-bottom: 1px solid var(--work-line); }
.rt-detail-classification > p { font-size: 12px; line-height: 1.8; color: var(--work-muted); overflow-wrap: anywhere; margin-top: 9px; }
.rt-detail-classification > p:empty { display: none; }
.rt-detail-list-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-top: 14px; }
.mc-layout-b .rt-detail-list-actions button { padding: 8px 5px; font-size: 11px; border-color: var(--work-line); background: #8bbdff0a; color: var(--work-text); }
.rt-detail-list-actions button:last-child { grid-column: 1 / -1; }
.mc-layout-b .rt-detail-list-actions .rt-white-action { color: #9edac1; }
.mc-layout-b .rt-detail-list-actions .rt-black-action { color: #ffb1a9; }
.rt-detail-classification .rt-list-inline-feedback.error { color: #ffb1a9; }
.rt-blacklist-alert { position: absolute; top: 17px; left: calc(var(--list-width) + 40px); right: calc(var(--detail-width) + 40px); z-index: 5; display: flex; align-items: center; justify-content: center; gap: 12px; padding: 10px 14px; border-radius: 8px; border: 1px solid #ffb1a94a; background: #231719e8; color: #ffb1a9; font-size: 12px; }
.rt-blacklist-alert strong { flex-shrink: 0; font-size: 12px; }
.rt-blacklist-alert span { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
.live-events li[data-alert=true] span { color: #ffb1a9; }
.rt-target-label[data-list-kind=black] { color: #ffb1a9 !important; border-color: #ffb1a97a; }
.rt-target-label[data-list-kind=white] { color: #9edac1 !important; border-color: #9edac17a; }
.rt-list-sync-error { display: flex; flex-wrap: wrap; align-items: center; gap: 7px; color: #ffb1a9; font-size: 11px; line-height: 1.8; margin: 10px 0; }
.mc-layout-b .rt-list-sync-error button { font-size: 11px; padding: 4px 7px; }
#rt-list-manager { position: absolute; top: 76px; right: 16px; bottom: 16px; width: 420px; max-width: calc(100% - 32px); z-index: 10; border: 1px solid var(--work-line); border-radius: 12px; background: #081625ed; backdrop-filter: var(--glass-filter); -webkit-backdrop-filter: var(--glass-filter); box-shadow: 0 12px 35px #0005; display: flex; flex-direction: column; color: var(--work-text); overflow: hidden; }
.mc-layout-b[data-lists-open=true] .live-detail { visibility: hidden; pointer-events: none; }
.rt-list-manager-head { display: flex; align-items: center; gap: 8px; padding: 0 16px; height: 54px; min-height: 54px; border-bottom: 1px solid var(--work-line); background: var(--glass-solid); }
.rt-list-manager-head h2 { font-size: 16px; margin-right: auto; }
.rt-list-manager button { font-size: 12px; border: 1px solid var(--work-line); border-radius: 6px; padding: 7px 9px; color: var(--work-text); background: #8bbdff0b; box-shadow: none; }
.rt-list-manager button:hover:not(:disabled) { background: #8bbdff24; }
.rt-list-manager button:disabled { opacity: .45; cursor: default; }
.rt-list-manager-body { flex: 1; min-height: 0; overflow: auto; padding: 16px; scrollbar-width: thin; }
.rt-list-help { font-size: 11px; color: var(--work-muted); line-height: 1.8; }
.rt-list-tabs { display: flex; flex-wrap: wrap; gap: 7px; margin: 13px 0; }
.rt-list-search { display: block; }
.rt-list-search > span { display: block; font-size: 11px; color: var(--work-muted); margin-bottom: 7px; }
.rt-list-manager :is(input, select, textarea) { width: 100%; min-width: 0; padding: 9px 10px; background: var(--work-input); border: 1px solid var(--work-line); border-radius: 7px; color: var(--work-text); font-size: 12px; box-shadow: none; }
.rt-list-manager input, .rt-list-manager select { height: 38px; }
.rt-list-manager input::placeholder { color: var(--work-muted); }
.rt-list-rows { max-height: 240px; overflow: auto; scrollbar-width: thin; margin-top: 6px; }
.rt-list-row { display: flex; gap: 7px; align-items: center; border-bottom: 1px solid var(--work-line); padding: 13px 0; }
.rt-list-row-main { flex: 1; min-width: 0; }
.rt-list-row strong { font-size: 12px; overflow-wrap: anywhere; }
.rt-list-row p { font-size: 11px; color: var(--work-muted); line-height: 1.7; overflow-wrap: anywhere; margin-top: 6px; }
.rt-list-row p:empty { display: none; }
.rt-list-row button { font-size: 11px; padding: 5px 7px; flex-shrink: 0; }
.rt-list-pagination { display: flex; justify-content: space-between; align-items: center; gap: 9px; margin: 12px 0 18px; font-size: 11px; color: var(--work-muted); }
#rt-list-entry-form { border-top: 1px solid var(--work-line); padding-top: 18px; }
#rt-list-entry-form h3 { font-size: 14px; }
#rt-list-entry-form label { display: block; font-size: 12px; margin: 14px 0 7px; }
#rt-list-entry-form textarea { height: 65px; resize: vertical; max-height: 180px; }
.rt-list-manager #rt-list-entry-form .primary { width: 100%; background: var(--glass-action); color: white; margin-top: 14px; }
.rt-list-manager-footer { background: var(--glass-solid); border-top: 1px solid var(--work-line); padding: 11px 16px; flex-shrink: 0; }
.rt-list-manager-footer p { font-size: 12px; line-height: 1.8; margin-bottom: 5px; color: #9edac1; overflow-wrap: anywhere; }
.rt-list-manager-footer p:empty { display: none; }
.rt-list-manager-footer p.error { color: #ffb1a9; }
.rt-list-manager-footer small { color: var(--work-muted); font-size: 10px; line-height: 1.8; }
.mc-layout-b.compact #rt-list-manager { left: 16px; right: 16px; width: auto; max-width: none; }
.mc-layout-b.compact[data-lists-open=true] :is(#rt-directory, #rt-details, #rt-dock) { visibility: hidden; pointer-events: none; }
.mc-layout-b.compact .rt-blacklist-alert { top: 61px; left: 16px; right: 16px; justify-content: space-between; }
.mc-layout-b.compact .rt-blacklist-alert span { font-size: 11px; }
@container(max-width: 500px) {
.rt-list-row { flex-wrap: wrap; }
.rt-list-row-main { flex-basis: calc(100% - 80px); }
.rt-list-rows { max-height: 180px; }
.rt-list-manager-head { padding: 0 13px; }
.rt-list-manager-head h2 { font-size: 14px; }
.rt-list-manager-body { padding: 14px; }
.rt-blacklist-alert span { display: none; }
}
+194
View File
@@ -0,0 +1,194 @@
/* Approved A workbench: only home, registration and appearance use this layout. */
body[data-screen=home] .home-launcher.homescreen {
inset: 48px 0 0 68px !important;
margin: 0 !important;
padding: 34px 28px;
container: home-workbench / inline-size;
}
body[data-screen=home][data-menu-hidden=true] .home-launcher.homescreen { left: 0 !important; }
.home-space { width: 100%; max-width: 1170px; }
.home-kicker { color: var(--work-muted); font-size: 11px; letter-spacing: .14em; margin-bottom: 10px; }
.home-heading h1 { font-size: 27px; }
.home-cards { gap: 20px; }
.home-card { min-height: 370px; padding: 25px; }
.home-card-title { margin-top: 23px; font-size: 20px; }
.home-card-desc { min-height: 52px; }
.home-card-preview { margin-bottom: 8px; }
.home-card-open { margin-top: auto; }
body[data-screen=register] #workspace-content,
#appearance-view { container: workbench / inline-size; overflow: auto; }
body[data-screen=register] #workspace-content > div { height: 100%; min-height: 0; }
body[data-screen=register] .registry-workspace {
height: 100%; min-height: 0; max-height: 100%; padding: 24px;
grid-template-columns: 240px minmax(0, 1fr) 280px;
grid-template-rows: minmax(0, 1fr); gap: 18px;
}
.workbench-panel,
body[data-screen=register] .registry-workspace :is(.history-panel, .registration-editor, #registration-result) {
min-width: 0; min-height: 0; border: 1px solid var(--work-line); border-radius: 12px;
background: var(--work-panel); color: var(--work-text);
backdrop-filter: var(--glass-filter); -webkit-backdrop-filter: var(--glass-filter);
box-shadow: 0 12px 28px #0003, inset 0 1px 0 #ffffff0b;
}
body[data-screen=register] .registry-workspace .history-panel {
display: flex; flex-direction: column; gap: 0; padding: 0; overflow: hidden;
}
.registry-workspace .history-heading {
padding: 0 16px; min-height: 54px; flex-shrink: 0; border-bottom: 1px solid var(--work-line);
}
.registry-workspace .history-heading h2 { font-size: 16px; }
.registry-workspace .history-content { padding: 16px; min-height: 0; overflow: auto; flex: 1; scrollbar-width: thin; }
.registry-workspace .history-search { margin-bottom: 14px; }
.registry-workspace .history-toolbar { margin: 13px 0; }
.registry-workspace #selection-controls { margin: 12px 0; }
.registry-workspace .history-message { margin: 10px 0; }
.registry-workspace .pagination { margin: 0; padding: 14px 16px; flex-shrink: 0; }
.registry-workspace #archive-warning:not([hidden]) { padding: 10px 16px; flex-shrink: 0; }
.registry-workspace .export-controls .registry-popup { left: 10px; right: 10px; }
body[data-screen=register] .registry-workspace .registration-editor { display: flex; flex-direction: column; overflow: hidden; }
.registry-workspace .registration-editor .registration-heading {
padding: 17px 20px; margin: 0; min-height: 70px; flex-shrink: 0; border-bottom: 1px solid var(--work-line);
}
.registry-workspace .registration-editor .registration-heading h1 { font-size: 16px; line-height: 1.5; margin: 0 0 4px; }
.registry-workspace .registration-editor .registration-heading p { font-size: 12px; }
.registry-workspace #register-form { display: flex; flex-direction: column; min-height: 0; flex: 1; }
.registry-workspace .registration-fields-scroll { flex: 1; min-height: 0; overflow: auto; padding: 22px 20px; scroll-padding-block: 18px; scrollbar-width: thin; }
body[data-screen=register] .registry-workspace #register-form .registry-group {
border: 0; border-radius: 0; border-bottom: 1px solid var(--work-line);
background: none; backdrop-filter: none; -webkit-backdrop-filter: none;
padding: 0 0 23px; margin: 0 0 23px; box-shadow: none;
}
body[data-screen=register] .registry-workspace #register-form .registry-group:last-of-type { border-bottom: 0; padding-bottom: 10px; margin-bottom: 0; }
.registry-workspace .registration-number { grid-template-columns: 1fr; gap: 8px; }
.registry-workspace .registration-number #fpv-hint { margin-top: 0; }
body[data-screen=register] .registry-workspace .registration-savebar {
position: static; flex-shrink: 0; margin: 0; padding: 15px 20px;
background: var(--glass-solid); box-shadow: none; backdrop-filter: none;
-webkit-backdrop-filter: none; gap: 12px;
}
.registry-workspace .registration-savebar #draft-state { font-size: 11px; }
.registry-workspace #register-button { font-size: 12px; }
body[data-screen=register] .registry-workspace #registration-result {
padding: 0; margin: 0; overflow: auto; scroll-padding-top: 60px; scrollbar-width: thin;
}
#registration-result > h2 {
position: sticky; top: 0; z-index: 2; padding: 17px 20px; min-height: 54px;
background: var(--glass-solid); border-bottom: 1px solid var(--work-line);
}
.registry-workspace #registration-result .empty-state {
display: flex; flex-direction: column; align-items: flex-start; padding: 24px 20px; gap: 16px;
}
.registry-workspace #registration-result .empty-state ol { margin: 0; padding-left: 20px; border: 0; font-size: 12px; }
.registry-workspace #registration-result .record-result { display: flex; flex-direction: column; padding: 22px 18px; gap: 17px; }
.registry-workspace #registration-result .qr-stage { width: 170px; align-self: center; flex-shrink: 0; }
.registry-workspace #registration-result .uas-display { font-size: 21px; overflow-wrap: anywhere; }
.registry-workspace #registration-result .result-fields { display: flex; flex-direction: column; gap: 14px; }
.registry-workspace #registration-result .result-fields > div { display: block; padding: 0; }
.registry-workspace #registration-result .result-fields dt { margin-bottom: 6px; font-size: 11px; }
.registry-workspace #registration-result .result-fields dd { overflow-wrap: anywhere; font-size: 13px; }
.registry-workspace #registration-result :is(.result-actions, .url-box) { display: flex; flex-direction: column; align-items: stretch; }
.registry-workspace #registration-result .result-actions :is(button, a) { text-align: center; }
.registry-workspace #registration-result .result-tip { font-size: 12px; }
#appearance-view .settings-layout {
height: 100%; min-height: 0; max-width: none; width: 100%; padding: 24px;
display: grid; grid-template-columns: 190px minmax(0, 1fr) 285px;
grid-template-rows: minmax(0, 1fr); align-items: start; gap: 18px; overflow: hidden;
}
#appearance-view .settings-sidebar { padding: 20px 12px; height: auto; }
.settings-sidebar h2 { padding: 0 8px 16px; font-size: 16px; }
.settings-sidebar .setting-link { width: 100%; text-align: left; justify-content: flex-start; margin: 0 0 7px; border: 1px solid transparent; background: none; padding: 11px 10px; font-size: 13px; color: var(--work-text); }
.settings-sidebar .setting-link.active { border-color: var(--work-line); background: #8bbdff14; }
.settings-sidebar .micro { padding: 9px 9px 0; font-size: 11px; line-height: 1.9; }
#appearance-view .setting-content { padding: 0; height: 100%; max-height: 100%; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
.setting-panel-head { min-height: 54px; padding: 0 20px; display: flex; align-items: center; justify-content: space-between; gap: 10px; border-bottom: 1px solid var(--work-line); flex-shrink: 0; }
.setting-panel-head h2 { margin: 0; font-size: 16px; }
.setting-panel-head > span { font-size: 11px; color: var(--work-muted); }
.settings-scroll { padding: 20px; overflow: auto; min-height: 0; flex: 1; scroll-padding-block: 20px; scrollbar-width: thin; }
#appearance-view .glass-material-note { padding: 14px 0 20px; border: 0; border-radius: 0; background: none; border-bottom: 1px solid var(--work-line); margin: 0; }
#appearance-view .glass-material-note p { font-size: 12px; }
#appearance-view .section-caption { margin: 23px 0 13px; }
#appearance-view .wall-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
#appearance-view .wall-choice { padding: 0; border-radius: 8px; border: 1px solid var(--work-line); background: #07152544; }
#appearance-view .wall-choice img { height: 80px !important; }
#appearance-view .wall-choice span { padding: 9px 11px; font-size: 12px; }
#appearance-view .native-group { background: none; backdrop-filter: none; -webkit-backdrop-filter: none; box-shadow: none; border: 0; margin: 10px 0; }
#appearance-view .setting-row { padding: 18px 0; gap: 16px; }
#appearance-view .setting-row label { font-size: 13px; }
#appearance-view .setting-row small { font-size: 11px; }
#appearance-view .setting-row .row { gap: 8px; }
#appearance-view .setting-row input[type=range] { width: 110px; }
#appearance-view .setting-row output { min-width: 32px; font-size: 11px; }
#appearance-view .setting-row select { min-width: 0; width: 125px; }
#appearance-view .setting-actions { flex-wrap: wrap; gap: 12px; }
.settings-preview { max-height: 100%; display: flex; flex-direction: column; overflow: hidden; }
.preview-content { padding: 20px; min-height: 0; overflow: auto; scrollbar-width: thin; }
#desktop-sample { width: 100% !important; height: 180px !important; margin: 0 0 22px !important; border: 1px solid var(--work-line); border-radius: 9px; background: var(--glass-base); box-shadow: none; position: relative; isolation: isolate; overflow: hidden; }
#desktop-sample::before, #desktop-sample::after { display: none; }
#appearance-wallpaper { position: absolute; inset: 0; width: 100%; height: 100%; filter: blur(var(--preview-blur, 0px)); }
.preview-shade { position: absolute; inset: 0; background: linear-gradient(var(--glass-workspace), var(--glass-workspace)), rgba(0, 0, 0, var(--preview-shade, .14)); }
.preview-material { position: absolute; inset: 20px 16px; border: 1px solid var(--work-line); border-radius: 8px; padding: 17px 14px; display: flex; flex-direction: column; gap: 10px; background: var(--work-panel); backdrop-filter: var(--glass-filter); -webkit-backdrop-filter: var(--glass-filter); }
.preview-material span, .preview-material small { font-size: 10px; color: var(--work-muted); }
.preview-material strong { font-size: 14px; font-weight: 600; }
.preview-values { display: grid; grid-template-columns: 1fr 1fr; gap: 21px 12px; margin: 0 0 23px; }
.preview-values div { min-width: 0; }
.preview-values dt { color: var(--work-muted); font-size: 11px; margin-bottom: 7px; }
.preview-values dd { margin: 0; font-size: 12px; overflow-wrap: anywhere; }
.preview-content .micro { font-size: 11px; line-height: 1.9; }
#edit-dialog #edit-cancel { min-width: 76px; flex-shrink: 0; white-space: nowrap; }
@container home-workbench (max-width: 899px) {
.home-space { margin: auto; }
.home-cards { grid-template-columns: 1fr; gap: 16px; }
.home-card { display: grid; grid-template-columns: 65px minmax(0, 1fr) 20px; gap: 5px 17px; padding: 20px; min-height: 132px; }
.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: 18px; }
.home-card-desc { grid-column: 2; grid-row: 2; min-height: 0; margin: 0; font-size: 13px; align-self: start; }
.home-card-preview { display: none; }
.home-card-open { grid-column: 3; grid-row: 1/3; display: block; width: 20px; height: 22px; font-size: 0; padding: 0; margin: 0; border: 0; }
.home-card-open svg { position: static; }
}
@container workbench (max-width: 1199px) {
body[data-screen=register] .registry-workspace { height: auto; min-height: 100%; max-height: none; overflow: visible; grid-template-columns: 224px minmax(0, 1fr); grid-template-rows: auto auto; }
body[data-screen=register] .registry-workspace .history-panel { grid-row: 1/3; max-height: calc(100dvh - 96px); position: sticky; top: 24px; }
body[data-screen=register] .registry-workspace .registration-editor { height: max(480px, calc(100dvh - 96px)); }
body[data-screen=register] .registry-workspace #registration-result { grid-column: 2; max-height: none; }
#appearance-view .settings-layout { height: auto; min-height: 100%; overflow: visible; grid-template-columns: 160px minmax(0, 1fr); grid-template-rows: auto auto; }
#appearance-view .settings-sidebar { grid-row: 1/3; }
#appearance-view .setting-content { height: auto; max-height: none; }
#appearance-view .settings-scroll { overflow: visible; }
#appearance-view .settings-preview { grid-column: 2; max-height: none; }
}
/* The container itself scrolls at narrower sizes; descendants control the columns. */
@media(max-width: 1267px) {
body[data-screen=register] #workspace-content, #appearance-view { overflow: auto; }
}
@container workbench (max-width: 767px) {
body[data-screen=register] .registry-workspace { display: flex; flex-direction: column; gap: 16px; padding: 16px; }
body[data-screen=register] .registry-workspace .history-panel { order: 0; height: 280px; max-height: 280px; flex-shrink: 0; position: relative; top: auto; }
.registry-workspace .history-content { padding: 13px 15px; }
.registry-workspace .pagination { padding: 10px 15px; gap: 6px; }
body[data-screen=register] .registry-workspace .registration-editor { order: 1; height: auto; min-height: 0; overflow: visible; flex-shrink: 0; }
.registry-workspace #register-form { display: block; }
.registry-workspace .registration-fields-scroll { overflow: visible; padding: 20px 16px 30px; }
.registry-workspace .registration-fields { grid-template-columns: 1fr; }
body[data-screen=register] .registry-workspace .registration-savebar { position: sticky; bottom: 0; padding: 14px 16px; z-index: 3; }
.registry-workspace #register-button { width: 100%; }
body[data-screen=register] .registry-workspace #registration-result { order: 2; flex-shrink: 0; overflow: visible; }
#registration-result > h2 { position: static; }
.registry-workspace #registration-result .empty-state { flex-direction: column; }
#appearance-view .settings-layout { display: flex; flex-direction: column; padding: 16px; gap: 16px; }
#appearance-view .settings-sidebar { display: flex; flex-wrap: wrap; gap: 6px; width: 100%; padding: 10px; flex-shrink: 0; }
.settings-sidebar h2, .settings-sidebar .micro { display: none; }
.settings-sidebar .setting-link { width: auto; margin: 0; }
#appearance-view .setting-content, #appearance-view .settings-preview { width: 100%; height: auto; max-height: none; flex-shrink: 0; }
.settings-scroll, .preview-content { padding: 18px 16px; overflow: visible; }
#appearance-view .setting-row { flex-wrap: wrap; }
#appearance-view .setting-row > .row { width: 100%; justify-content: space-between; }
#appearance-view .setting-row input[type=range] { width: 75%; }
.setting-panel-head { padding: 0 16px; }
}
@media(max-width: 760px) {
body[data-screen=home] .home-launcher.homescreen { left: 56px !important; padding: 28px 20px; }
body[data-screen=home] .workspace-home-link > #workspace-brand { display: inline; font-size: 12px; }
body[data-screen=home] #reference-title { display: none; }
.home-heading h1 { font-size: 24px; }
}
+1 -1
View File
@@ -110,7 +110,7 @@ body[data-menu-hidden=true] .workspace-pane{left:0}body[data-menu-hidden=true] .
@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}}
/* Basemap selection uses the existing toolbar, including compact windows. */
.mc-layout-b .live-basemap{height:34px;width:82px;min-width:0;padding:4px 6px;border:1px solid var(--work-line);border-radius:6px;background:var(--work-input);color:var(--work-text);font:inherit;font-size:12px;cursor:pointer}
.mc-layout-b .live-basemap{height:34px;width:102px;min-width:0;padding:4px 6px;border:1px solid var(--work-line);border-radius:6px;background:var(--work-input);color:var(--work-text);font:inherit;font-size:12px;cursor:pointer}
.mc-layout-b.compact .live-basemap{width:68px;padding:4px 2px}
.mc-layout-b.compact .mc-map-toolstrip button{min-width:28px;padding:6px 4px;font-size:12px}
.mc-layout-b .live-basemap option{background:var(--mc-bg);color:var(--work-text)}
+1
View File
@@ -3,6 +3,7 @@ mod realtime_layout;
mod realtime_ui;
mod receiver_ui;
mod registry;
mod target_lists;
mod workspace;
fn main() {
+2 -2
View File
@@ -178,7 +178,7 @@ impl Layout {
} else {
116.0
};
let v = json!({"top":76,"left":extent("rt-directory",true),"right":extent("rt-details",false),"bottom":bottom});
let v = json!({"top":76,"left":extent("rt-directory",true),"right":extent("rt-details",false).max(extent("rt-list-manager",false)),"bottom":bottom});
let _ = super::realtime_ui::map_call(
"setOcclusion",
&[js_sys::JSON::parse(&v.to_string()).unwrap_or_default()],
@@ -200,7 +200,7 @@ impl Layout {
pub fn focus(self) {
if self.compact.get_untracked() {
self.mobile.set(0);
focus("rt-map-focus");
focus("rt-map");
}
let _ = super::realtime_ui::map_call("focusVisible", &[]);
}
+71 -19
View File
@@ -1,7 +1,10 @@
//! Map-overlay workspace: observed telemetry and actual local registration records only.
use super::target_lists::{Badge, Filter, Lists, Manager};
use gloo_timers::future::TimeoutFuture;
use leptos::prelude::*;
use rid_shared::target_lists::{AlertTracker, ListKind};
use serde_json::Value;
use std::collections::HashMap;
use std::{
cell::{Cell, RefCell},
rc::Rc,
@@ -66,13 +69,13 @@ fn log_event(events: RwSignal<Vec<LiveEvent>>, message: String) {
}
}
}
const BASEMAP_KEY: &str = "rid.realtime.basemap.v1";
const BASEMAP_KEY: &str = "rid.realtime.basemap.v2";
fn initial_basemap() -> String {
web_sys::window()
.and_then(|w| w.local_storage().ok().flatten())
.and_then(|s| s.get_item(BASEMAP_KEY).ok().flatten())
.filter(|s| s == "imagery" || s == "road")
.unwrap_or_else(|| "road".into())
.unwrap_or_else(|| "imagery".into())
}
fn basemap_layers(kind: &str) -> [&'static str; 2] {
if kind == "imagery" {
@@ -83,9 +86,9 @@ fn basemap_layers(kind: &str) -> [&'static str; 2] {
}
fn map_label(value: &Value, kind: &str) -> String {
let name = if kind == "imagery" {
"影像图"
"影像+路网"
} else {
"路网图"
"纯路网"
};
let states = basemap_layers(kind).map(|layer| &value["layers"][layer]);
let real = states
@@ -130,6 +133,16 @@ fn map_label(value: &Value, kind: &str) -> String {
#[component]
pub fn Realtime() -> impl IntoView {
let ids = RwSignal::new(Vec::<String>::new());
let lists = Lists::new();
let classification = Memo::new(move |_| {
lists
.snapshot
.get()
.entries
.into_iter()
.map(|entry| (entry.target_id, entry.list_kind))
.collect::<HashMap<_, _>>()
});
let query = RwSignal::new(String::new());
let selected = RwSignal::new(String::new());
let position = RwSignal::new(None::<[f64; 4]>);
@@ -146,9 +159,11 @@ pub fn Realtime() -> impl IntoView {
let events = RwSignal::new(Vec::<LiveEvent>::new());
let filtered = Memo::new(move |_| {
let q = query.get().to_lowercase();
let filter = lists.filter.get();
let kinds = classification.get();
ids.get()
.into_iter()
.filter(|id| id.to_lowercase().contains(&q))
.filter(|id| id.to_lowercase().contains(&q) && filter.matches(kinds.get(id).copied()))
.collect::<Vec<_>>()
});
let visible_page = Memo::new(move |_| {
@@ -156,6 +171,7 @@ pub fn Realtime() -> impl IntoView {
.min(filtered.get().len().div_ceil(100).max(1) - 1)
});
let choose = move |id: String| {
lists.open.set(false);
layout.select();
if selected.get_untracked() != id {
selected.set(id.clone());
@@ -218,7 +234,45 @@ pub fn Realtime() -> impl IntoView {
p.iter().all(|x| x.is_finite()).then_some(p)
}));
};
let active_black = Memo::new(move |_| {
let kinds = classification.get();
ids.get()
.into_iter()
.filter(|id| kinds.get(id) == Some(&ListKind::Black))
.collect::<Vec<_>>()
});
let tracker = Rc::new(RefCell::new(AlertTracker::default()));
Effect::new(move |_| {
let kinds = classification.get();
let active = ids.get();
if lists.ready.get() {
for id in tracker.borrow_mut().update(&active, &kinds) {
log_event(events, format!("黑名单命中:{id}"));
}
}
let filter = lists.filter.get();
if let Ok(value) =
serde_json::to_string(&kinds).map(|text| js_sys::JSON::parse(&text).unwrap_or_default())
{
let _ = map_call("setClassification", &[value, filter.wire().into()]);
}
let current = selected.get_untracked();
if !current.is_empty() && !filter.matches(kinds.get(&current).copied()) {
selected.set(String::new());
position.set(None);
record.set(None);
lookup.set("请选择目标".into());
let _ = map_call("select", &["".into()]);
}
});
let stopped = Rc::new(Cell::new(false));
let list_stop = stopped.clone();
spawn_local(async move {
while !list_stop.get() {
lists.refresh().await;
gloo_timers::future::TimeoutFuture::new(5000).await;
}
});
let worker_holder: Rc<RefCell<Option<web_sys::Worker>>> = Rc::new(RefCell::new(None));
let stop = stopped.clone();
let workers = worker_holder.clone();
@@ -460,25 +514,21 @@ pub fn Realtime() -> impl IntoView {
});
});
view! {
<main class="rt-page"><div id="rt-layout" class="mc-layout-b" class:compact=move||layout.compact.get() class:dock-hidden=move||!layout.dock_visible() class:list-hidden=move||!layout.list_visible() class:detail-hidden=move||!layout.detail_visible() style=("--dock-height",move||format!("{}px",layout.height.get()))>
<section class="mc-map-area-top"><div id="rt-map" class="rt-map-canvas"></div>
<div class="mc-map-toolstrip" role="toolbar" aria-label="地图工具">
<select class="live-basemap" aria-label="底图类型" prop:value=move||basemap.get() on:change=move |e|{let value=event_target_value(&e);if !matches!(value.as_str(),"road"|"imagery"){return}basemap.set(value.clone());if let Some(s)=web_sys::window().and_then(|w|w.local_storage().ok().flatten()){let _=s.set_item(BASEMAP_KEY,&value);}let _=map_call("setBasemap",&[value.into()]);}><option value="road">"路网图"</option><option value="imagery">"影像图"</option></select>
<button title="放大" aria-label="放大" on:click=move |_|{let _=map_call("zoomIn",&[]);}>"+"</button>
<button title="缩小" aria-label="缩小" on:click=move |_|{let _=map_call("zoomOut",&[]);}>"−"</button>
<button id="rt-map-focus" title="聚焦选中目标" aria-label="聚焦选中目标" disabled=move||position.get().is_none() on:click=move |_|layout.focus()>"◎"</button>
<button title="正北复位" aria-label="正北复位" on:click=move |_|{let _=map_call("resetBearing",&[]);}>"N ↑"</button>
<button id="rt-list-toggle" title="显示目标目录" aria-label="显示目标目录" aria-controls="rt-directory" aria-expanded=move||layout.list_visible().to_string() on:click=move |_|layout.toggle_list()>"☷"</button>
<button id="rt-detail-toggle" title="显示目标详情" aria-label="显示目标详情" aria-controls="rt-details" aria-expanded=move||layout.detail_visible().to_string() on:click=move |_|layout.toggle_detail()>"ⓘ"</button>
<main class="rt-page"><div id="rt-layout" class="mc-layout-b" class:compact=move||layout.compact.get() class:dock-hidden=move||!layout.dock_visible() class:list-hidden=move||!layout.list_visible() class:detail-hidden=move||!layout.detail_visible() data-lists-open=move||lists.open.get().to_string() style=("--dock-height",move||format!("{}px",layout.height.get()))>
<section class="mc-map-area-top"><div tabindex="-1" id="rt-map" class="rt-map-canvas"></div>
<div class="live-panel-restores"><button id="rt-list-manager-open" title="管理黑白名单" aria-label="管理黑白名单" hidden=move||layout.list_visible() on:click=move |_|lists.show()>"名单管理"</button>
<button id="rt-list-toggle" title="显示目标目录" aria-label="显示目标目录" aria-controls="rt-directory" hidden=move||layout.list_visible() on:click=move |_|layout.toggle_list()>"目标目录"</button>
<button id="rt-detail-toggle" title="显示目标详情" aria-label="显示目标详情" aria-controls="rt-details" hidden=move||layout.detail_visible() on:click=move |_|layout.toggle_detail()>"目标详情"</button>
</div>
<div class="rt-blacklist-alert" role="status" hidden=move||active_black.get().is_empty()><strong>{move||format!("黑名单目标 {}",active_black.get().len())}</strong><span>{move||active_black.get().into_iter().take(2).collect::<Vec<_>>().join("、")}</span></div>
<div class="mc-map-infobar">{move||map_label(&map_status.get(),&basemap.get())}</div>
</section>
<aside id="rt-directory" class="mc-floating-panel live-targets" aria-label="目标目录" hidden=move||!layout.list_visible()>
<div class="live-panel-head"><h2>"目标目录"</h2><button title="收起目标目录" aria-label="收起目标目录" on:click=move |_|{layout.toggle_list();super::realtime_layout::focus("rt-list-toggle");}>"‹"</button></div><div class="live-list-controls">
<div class="live-panel-head"><h2>"目标目录"</h2><button id="rt-list-manager-from-directory" title="管理黑白名单" aria-label="管理黑白名单" on:click=move |_|lists.show()>"名单管理"</button><button title="收起目标目录" aria-label="收起目标目录" on:click=move |_|{layout.toggle_list();super::realtime_layout::focus("rt-list-toggle");}>"‹"</button></div><div class="live-list-controls">
<span class="live-data-label rt-status">{move||status.get()}</span>
<input class="live-search" aria-label="搜索实时目标" placeholder="搜索目标标识" prop:value=move||query.get() on:input=move|e|{query.set(event_target_value(&e));page.set(0);}/>
<span class="live-data-label">{move||format!("目标 {} · 数据年龄 {} ms",ids.get().len(),age.get())}</span>
</div><div class="live-list-body"><div class="live-target-list">{move||filtered.get().into_iter().skip(visible_page.get()*100).take(100).map(|id|{let check=id.clone();let pick=id.clone();view!{<button class="rt-target" aria-pressed=move||(selected.get()==check).to_string() on:click=move |_|choose(pick.clone())><span aria-hidden="true">"◈"</span>{id}</button>}}).collect_view()}</div>
<span class="live-data-label">{move||format!("目标 {} · 数据年龄 {} ms",ids.get().len(),age.get())}</span><div class="rt-target-list-filters" role="group" aria-label="目标名单筛选">{[Filter::All,Filter::White,Filter::Black,Filter::Unknown].into_iter().map(move |filter|view!{<button type="button" disabled=move||!lists.ready.get() aria-pressed=move||(lists.filter.get()==filter).to_string() on:click=move |_|{lists.filter.set(filter);page.set(0);}>{filter.label()}" "{move||{let kinds=classification.get();ids.with(|targets|targets.iter().filter(|id|filter.matches(kinds.get(*id).copied())).count())}}</button>}).collect_view()}</div><p class="rt-list-sync-error" role="status" hidden=move||lists.sync_error.get().is_empty()>{move||lists.sync_error.get()}<button type="button" on:click=move |_|spawn_local(lists.refresh())>"重试"</button></p>
</div><div class="live-list-body"><div class="live-target-list">{move||filtered.get().into_iter().skip(visible_page.get()*100).take(100).map(|id|{let check=id.clone();let pick=id.clone();let badge_id=id.clone();let description_id=id.clone();view!{<button class="rt-target" aria-label=id.clone() aria-description=move||if lists.ready.get(){super::target_lists::label(lists.kind(&description_id))}else{"名单未知"} aria-pressed=move||(selected.get()==check).to_string() on:click=move |_|choose(pick.clone())><span aria-hidden="true">"◈"</span><span class="rt-target-id">{id.clone()}</span><Badge lists=lists target=badge_id/></button>}}).collect_view()}</div>
<p class="live-empty" hidden=move||!filtered.get().is_empty()>{move||if ids.get().is_empty(){"暂无目标。请检查接收器和数据源。"}else{"没有匹配的目标。"}}</p>
</div><nav class="pagination"><button disabled=move||{visible_page.get()==0} on:click=move |_|page.set(visible_page.get().saturating_sub(1))>"上一组"</button><span>{move||format!("{} / {}",visible_page.get()+1,filtered.get().len().div_ceil(100).max(1))}</span><button disabled=move||{(visible_page.get()+1)*100>=filtered.get().len()} on:click=move |_|page.set(visible_page.get()+1)>"下一组"</button></nav>
</aside>
@@ -487,12 +537,14 @@ pub fn Realtime() -> impl IntoView {
<div class="live-detail-body"><button class="live-back" hidden=move||!layout.compact.get() on:click=move |_|layout.mobile.set(1)>"‹ 返回目标目录"</button>
<div class="live-target-heading">{move||if selected.get().is_empty(){"请选择目标".into()}else{selected.get()}}</div>
<p class="live-data-label">{move||lookup.get()}</p>
<div class="rt-detail-classification" hidden=move||selected.get().is_empty()>{move||view!{<Badge lists=lists target=selected.get()/>}}<p>{move||lists.snapshot.with(|snapshot|snapshot.entries.iter().find(|entry|entry.target_id==selected.get()).map(|entry|entry.note.clone()).unwrap_or_default())}</p><div class="rt-detail-list-actions"><button class="rt-white-action" disabled=move||selected.get().is_empty()||!lists.ready.get()||lists.busy.get() on:click=move |_|lists.mark(selected.get_untracked(),ListKind::White)>"加入白名单"</button><button class="rt-black-action" disabled=move||selected.get().is_empty()||!lists.ready.get()||lists.busy.get() on:click=move |_|lists.mark(selected.get_untracked(),ListKind::Black)>"加入黑名单"</button><button disabled=move||selected.get().is_empty()||!lists.ready.get()||lists.busy.get() on:click=move |_|lists.edit(selected.get_untracked())>"编辑名单备注"</button></div><p class="rt-list-inline-feedback" role="status" class:error=move||lists.failed.get()>{move||lists.message.get()}</p></div>
<div class="live-metrics"><div><span>"经度"</span><strong>{move||position.get().map(|p|format!("{:.6}",p[0])).unwrap_or_else(||"—".into())}</strong></div><div><span>"纬度"</span><strong>{move||position.get().map(|p|format!("{:.6}",p[1])).unwrap_or_else(||"—".into())}</strong></div><div><span>"高度(数据源)"</span><strong>{move||position.get().map(|p|format!("{:.1} m",p[2])).unwrap_or_else(||"—".into())}</strong></div><div><span>"航向"</span><strong>{move||position.get().map(|p|format!("{:.0}°",p[3])).unwrap_or_else(||"—".into())}</strong></div></div>
<dl><dt>"登记机型"</dt><dd>{move||record.get().and_then(|r|r["modelName"].as_str().map(str::to_owned)).unwrap_or_else(||"—".into())}</dd><dt>"登记人"</dt><dd>{move||record.get().and_then(|r|r["ownerName"].as_str().map(str::to_owned)).unwrap_or_else(||"—".into())}</dd></dl>
<p class="live-data-label">"未收到的字段显示 —。未匹配本地记录不代表违法或未官方备案。"</p>
</div><div class="mc-btn-row"><button class="primary" disabled=move||position.get().is_none() on:click=move |_|layout.focus()>"聚焦此目标"</button><a class="mc-btn mc-btn-secondary" aria-disabled=move||selected.get().is_empty().to_string() tabindex=move||if selected.get().is_empty(){-1}else{0} href=move||if selected.get().is_empty(){None}else{Some(format!("/?app=register&q={}",js_sys::encode_uri_component(&selected.get())))}>"查看本地登记"</a></div>
</aside>
<Manager lists=lists/>
<section id="rt-dock" class="mc-hud-dock" tabindex="-1" aria-label="事件与接收器" hidden=move||!layout.dock_visible()>
<div class="live-resizer" role="separator" tabindex="0" aria-label="调整底栏高度" aria-orientation="horizontal" aria-valuemin="100" aria-valuemax=move||layout.maximum.get().round().to_string() aria-valuenow=move||layout.height.get().round().to_string()
on:pointerdown=move |e|{if e.button()!=0{return}
@@ -513,7 +565,7 @@ pub fn Realtime() -> impl IntoView {
<div id="rt-event-scroll" class="mc-dock-body" hidden=move||layout.receiver.get()>
<div class="live-data-label">{move||format!("{} · 当前 {} 个目标",status.get(),ids.get().len())}</div>
<p class="live-data-label" hidden=move||!events.get().is_empty()>"暂无事件,等待实时通道消息。"</p>
<ol class="live-events"><For each=move||events.get() key=|event|event.id children=move |event|view!{<li id=format!("rt-event-{}",event.id) data-event-id=event.id><time>{event.time}</time><span>{event.message}</span></li>}/></ol>
<ol class="live-events"><For each=move||events.get() key=|event|event.id children=move |event|{let alert=event.message.starts_with("黑名单命中:");view!{<li data-alert=alert.to_string() id=format!("rt-event-{}",event.id) data-event-id=event.id><time>{event.time}</time><span>{event.message}</span></li>}}/></ol>
</div>
<div class="mc-dock-body live-receiver-body" hidden=move||!layout.receiver.get()><Show when=move||layout.mounted.get()><crate::receiver_ui::ReceiverControls expanded=true/></Show></div>
</section>
+8 -8
View File
@@ -1,14 +1,17 @@
<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>
<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-content">
<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>
</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>
<section class="registration-editor" aria-labelledby="register-title"><header class="registration-heading"><div><h1 id="register-title">新建设备登记</h1><p>填写设备信息,生成本机登记二维码</p></div><span></span></header>
<form id="register-form" aria-labelledby="register-title"><div class="registration-fields-scroll"><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><div class="registration-savebar"><span id="draft-state">保存时校验 SN 与编号</span><button class="primary" id="register-button" type="submit">保存登记并生成二维码 →</button></div></form></section><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" id="result-context" role="status"></div>
@@ -24,8 +27,5 @@
<p class="result-tip">在本机同时启动登记站和本地版上位机,上传此二维码。上位机会从本地记录读取字段并比对模块 SN。</p>
</div>
</section>
<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>
</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>
+4
View File
@@ -346,6 +346,10 @@ fn draw(state: &Shared, record: Value) {
state.borrow_mut().active = Some(record);
render_rows(state);
el("registration-result").scroll_into_view();
if let Some(result) = el("registration-result").dyn_ref::<web_sys::HtmlElement>() {
result.set_scroll_top(0);
let _ = result.focus();
}
}
fn edit(state: &Shared, row: Value) {
text("edit-message", "");
+350
View File
@@ -0,0 +1,350 @@
//! Manual target lists and their editor. Telemetry and registration retain their own state.
use gloo_net::http::Request;
use leptos::prelude::*;
use rid_shared::target_lists::{
Entry, ListKind, MAX_NOTE_CHARS, Mutation, Snapshot, valid_target_id,
};
use serde_json::Value;
use wasm_bindgen_futures::spawn_local;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) enum Filter {
#[default]
All,
White,
Black,
Unknown,
}
impl Filter {
pub fn matches(self, kind: Option<ListKind>) -> bool {
match self {
Self::All => true,
Self::White => kind == Some(ListKind::White),
Self::Black => kind == Some(ListKind::Black),
Self::Unknown => kind.is_none(),
}
}
pub fn wire(self) -> &'static str {
match self {
Self::All => "all",
Self::White => "white",
Self::Black => "black",
Self::Unknown => "unknown",
}
}
pub fn label(self) -> &'static str {
match self {
Self::All => "全部",
Self::White => "白名单",
Self::Black => "黑名单",
Self::Unknown => "未分类",
}
}
}
pub(super) fn label(kind: Option<ListKind>) -> &'static str {
match kind {
Some(ListKind::White) => "白名单",
Some(ListKind::Black) => "黑名单",
None => "未分类",
}
}
#[derive(Clone, Copy)]
pub(super) struct Lists {
pub snapshot: RwSignal<Snapshot>,
pub ready: RwSignal<bool>,
pub busy: RwSignal<bool>,
pub open: RwSignal<bool>,
pub filter: RwSignal<Filter>,
pub sync_error: RwSignal<String>,
query: RwSignal<String>,
manager_filter: RwSignal<Filter>,
manager_page: RwSignal<usize>,
draft_id: RwSignal<String>,
draft_note: RwSignal<String>,
draft_kind: RwSignal<ListKind>,
editing: RwSignal<bool>,
pub message: RwSignal<String>,
pub failed: RwSignal<bool>,
}
impl Lists {
pub fn new() -> Self {
Self {
snapshot: RwSignal::new(Snapshot::default()),
ready: RwSignal::new(false),
busy: RwSignal::new(false),
open: RwSignal::new(false),
filter: RwSignal::new(Filter::All),
sync_error: RwSignal::new(String::new()),
query: RwSignal::new(String::new()),
manager_filter: RwSignal::new(Filter::All),
manager_page: RwSignal::new(0),
draft_id: RwSignal::new(String::new()),
draft_note: RwSignal::new(String::new()),
draft_kind: RwSignal::new(ListKind::Black),
editing: RwSignal::new(false),
message: RwSignal::new(String::new()),
failed: RwSignal::new(false),
}
}
fn apply(self, snapshot: Snapshot) {
if snapshot.revision >= self.snapshot.get_untracked().revision {
self.snapshot.set(snapshot);
}
self.ready.set(true);
self.sync_error.set(String::new());
}
pub async fn refresh(self) {
let url = if self.ready.get_untracked() {
format!(
"/api/target-lists?revision={}",
self.snapshot.get_untracked().revision
)
} else {
"/api/target-lists".into()
};
let result = async {
let response = Request::get(&url)
.send()
.await
.map_err(|_| "名单同步失败,请检查本机服务")?;
if response.status() == 304 {
return Ok(None);
}
if !response.ok() {
return Err("名单读取失败,请重试");
}
response
.json::<Snapshot>()
.await
.map(Some)
.map_err(|_| "名单响应无效,请重试")
}
.await;
match result {
Ok(Some(snapshot)) => self.apply(snapshot),
Ok(None) => self.sync_error.set(String::new()),
Err(error) => self.sync_error.set(error.into()),
}
}
pub fn kind(self, id: &str) -> Option<ListKind> {
self.snapshot.with(|snapshot| {
snapshot
.entries
.iter()
.find(|entry| entry.target_id == id)
.map(|entry| entry.list_kind)
})
}
pub fn show(self) {
self.open.set(true);
}
pub fn close(self) {
self.open.set(false);
let directory_visible = super::realtime_layout::element("rt-directory")
.is_some_and(|e| !e.has_attribute("hidden"));
super::realtime_layout::focus(if directory_visible {
"rt-list-manager-from-directory"
} else {
"rt-list-manager-open"
});
}
pub fn edit(self, id: String) {
if self.busy.get_untracked() {
return;
}
let entry = self.snapshot.with_untracked(|snapshot| {
snapshot.entries.iter().find(|e| e.target_id == id).cloned()
});
self.draft_id.set(id);
self.draft_note
.set(entry.as_ref().map(|e| e.note.clone()).unwrap_or_default());
self.draft_kind.set(
entry
.as_ref()
.map(|e| e.list_kind)
.unwrap_or(ListKind::Black),
);
self.editing.set(entry.is_some());
self.message.set(String::new());
self.failed.set(false);
self.show();
super::realtime_layout::focus("rt-list-entry-note");
}
fn feedback(self, message: String, failed: bool) {
self.message.set(message);
self.failed.set(failed);
}
pub fn mark(self, id: String, kind: ListKind) {
let note = self.snapshot.with_untracked(|snapshot| {
snapshot
.entries
.iter()
.find(|e| e.target_id == id)
.map(|e| e.note.clone())
.unwrap_or_default()
});
self.save(id, kind, note);
}
fn save(self, id: String, kind: ListKind, note: String) {
if self.busy.get_untracked() || !self.ready.get_untracked() {
return;
}
if !valid_target_id(&id) {
self.feedback(
"目标标识须为 1–64 位字母、数字、短横线或下划线".into(),
true,
);
return;
}
if note.chars().count() > MAX_NOTE_CHARS {
self.feedback("名单备注最多 200 字".into(), true);
return;
}
let mutation = Mutation {
list_kind: kind,
note,
expected_revision: self.snapshot.get_untracked().revision,
};
self.busy.set(true);
self.feedback("正在保存名单…".into(), false);
spawn_local(async move {
let result = async {
let request = Request::put(&format!("/api/target-lists/{id}"))
.json(&mutation)
.map_err(|_| "名单提交失败".to_owned())?;
mutation_response(
request
.send()
.await
.map_err(|_| "名单保存失败,请检查本机服务".to_owned())?,
)
.await
}
.await;
self.busy.set(false);
match result {
Ok(snapshot) => {
self.apply(snapshot);
self.feedback(format!("已将 {id} 保存为{}", label(Some(kind))), false);
if self.draft_id.get_untracked() == id {
self.editing.set(true);
}
}
Err(error) => {
self.feedback(error, true);
self.refresh().await;
}
}
});
}
fn remove(self, id: String) {
if self.busy.get_untracked() || !self.ready.get_untracked() {
return;
}
let revision = self.snapshot.get_untracked().revision;
self.busy.set(true);
self.feedback("正在移除条目…".into(), false);
spawn_local(async move {
let result = async {
mutation_response(
Request::delete(&format!("/api/target-lists/{id}?revision={revision}"))
.send()
.await
.map_err(|_| "名单移除失败,请检查本机服务".to_owned())?,
)
.await
}
.await;
self.busy.set(false);
match result {
Ok(snapshot) => {
self.apply(snapshot);
if self.draft_id.get_untracked() == id {
self.editing.set(false);
}
self.feedback(format!("已移除 {id},恢复未分类"), false);
}
Err(error) => {
self.feedback(error, true);
self.refresh().await;
}
}
});
}
}
async fn mutation_response(response: gloo_net::http::Response) -> Result<Snapshot, String> {
if !response.ok() {
let value = response.json::<Value>().await.unwrap_or(Value::Null);
return Err(value["error"]
.as_str()
.unwrap_or("名单操作失败,请刷新后重试")
.to_owned());
}
response
.json::<Snapshot>()
.await
.map_err(|_| "名单响应无效,请刷新后重试".into())
}
#[component]
pub(super) fn Badge(lists: Lists, target: String) -> impl IntoView {
let class_id = target.clone();
view! { <span class="rt-list-badge" data-kind=move||if !lists.ready.get(){"unavailable"}else{match lists.kind(&class_id){Some(ListKind::White)=>"white",Some(ListKind::Black)=>"black",None=>"unknown"}}>{move||if lists.ready.get(){label(lists.kind(&target))}else{"名单未知"}}</span> }
}
#[component]
pub(super) fn Manager(lists: Lists) -> impl IntoView {
let rows = Memo::new(move |_| {
let query = lists.query.get().to_lowercase();
let filter = lists.manager_filter.get();
lists
.snapshot
.get()
.entries
.into_iter()
.filter(|entry| {
filter.matches(Some(entry.list_kind))
&& (query.is_empty()
|| entry.target_id.to_lowercase().contains(&query)
|| entry.note.to_lowercase().contains(&query))
})
.collect::<Vec<Entry>>()
});
let page = Memo::new(move |_| {
lists
.manager_page
.get()
.min(rows.get().len().div_ceil(50).max(1) - 1)
});
view! {
<aside id="rt-list-manager" class="rt-list-manager" aria-label="黑白名单管理" hidden=move||!lists.open.get() on:keydown=move|event|{if event.key()=="Escape"{event.stop_propagation();lists.close();}}>
<header class="rt-list-manager-head"><h2>"黑白名单管理"</h2><button type="button" disabled=move||lists.busy.get() on:click=move |_|{lists.draft_id.set(String::new());lists.draft_note.set(String::new());lists.editing.set(false);lists.message.set(String::new());super::realtime_layout::focus("rt-list-entry-id");}>"新增条目"</button><button type="button" aria-label="关闭名单管理" on:click=move |_|lists.close()>"关闭"</button></header>
<div class="rt-list-manager-body">
<p class="rt-list-help">"按目标标识精确匹配,区分大小写。名单独立于备案档案;可提前录入离线目标。"</p>
<div class="rt-list-tabs" role="group" aria-label="管理名单分类">{[Filter::All,Filter::White,Filter::Black].into_iter().map(move |filter|view!{<button type="button" aria-pressed=move||(lists.manager_filter.get()==filter).to_string() on:click=move |_|{lists.manager_filter.set(filter);lists.manager_page.set(0);}>{filter.label()}" "{move||lists.snapshot.with(|s|s.entries.iter().filter(|entry|filter.matches(Some(entry.list_kind))).count())}</button>}).collect_view()}</div>
<label class="rt-list-search"><span>"搜索名单"</span><input placeholder="搜索目标标识或备注" prop:value=move||lists.query.get() on:input=move|event|{lists.query.set(event_target_value(&event));lists.manager_page.set(0);}/></label>
<p class="rt-list-help" hidden=move||lists.ready.get()>"正在读取本机名单…"</p>
<p class="rt-list-sync-error" role="status" hidden=move||lists.sync_error.get().is_empty()>{move||lists.sync_error.get()}<button type="button" on:click=move |_|spawn_local(lists.refresh())>"重试"</button></p>
<div class="rt-list-rows"><For each={move||rows.get().into_iter().skip(page.get()*50).take(50).collect::<Vec<_>>()} key=|entry|entry.target_id.clone() children=move |entry|{
let edit_id=entry.target_id.clone();let remove_id=entry.target_id.clone();let badge_id=entry.target_id.clone();
view!{<div class="rt-list-row" data-target-id=entry.target_id.clone()><div class="rt-list-row-main"><strong>{entry.target_id.clone()}</strong><p>{entry.note.clone()}</p></div><Badge lists=lists target=badge_id/><button type="button" disabled=move||lists.busy.get() on:click=move |_|lists.edit(edit_id.clone())>"编辑"</button><button type="button" disabled=move||lists.busy.get() on:click=move |_|lists.remove(remove_id.clone())>"移除"</button></div>}
}/></div>
<p class="rt-list-help" hidden=move||!lists.ready.get()||!rows.get().is_empty()>"暂无匹配条目,可在下面新增。"</p>
<nav class="rt-list-pagination" aria-label="名单分页"><button type="button" disabled=move||page.get()==0 on:click=move |_|lists.manager_page.set(page.get().saturating_sub(1))>"上一页"</button><span>{move||format!("{} / {}",page.get()+1,rows.get().len().div_ceil(50).max(1))}</span><button type="button" disabled=move||(page.get()+1)*50>=rows.get().len() on:click=move |_|lists.manager_page.set(page.get()+1)>"下一页"</button></nav>
<form id="rt-list-entry-form" on:submit=move |event|{event.prevent_default();lists.save(lists.draft_id.get_untracked().trim().to_owned(),lists.draft_kind.get_untracked(),lists.draft_note.get_untracked());}>
<h3>{move||if lists.editing.get(){"编辑名单条目"}else{"新增名单条目"}}</h3>
<label for="rt-list-entry-id">"目标标识"</label><input id="rt-list-entry-id" required maxlength="64" pattern="[A-Za-z0-9_-]{1,64}" autocomplete="off" readonly=move||lists.editing.get() disabled=move||lists.busy.get() prop:value=move||lists.draft_id.get() on:input=move|event|lists.draft_id.set(event_target_value(&event))/>
<label for="rt-list-entry-kind">"名单类型"</label><select id="rt-list-entry-kind" disabled=move||lists.busy.get() prop:value=move||match lists.draft_kind.get(){ListKind::White=>"white",ListKind::Black=>"black"} on:change=move|event|lists.draft_kind.set(if event_target_value(&event)=="white"{ListKind::White}else{ListKind::Black})><option value="white">"白名单"</option><option value="black">"黑名单"</option></select>
<label for="rt-list-entry-note">"备注(选填,最多 200 字)"</label><textarea id="rt-list-entry-note" maxlength="200" disabled=move||lists.busy.get() prop:value=move||lists.draft_note.get() on:input=move|event|lists.draft_note.set(event_target_value(&event))></textarea>
<button class="primary" type="submit" disabled=move||!lists.ready.get()||lists.busy.get()>{move||if lists.busy.get(){"正在保存…"}else{"保存名单条目"}}</button>
</form>
</div>
<footer class="rt-list-manager-footer"><p role="status" class:error=move||lists.failed.get()>{move||lists.message.get()}</p><small>"名单保存在本机。移除后恢复未分类,不删除遥测或登记档案。"</small></footer>
</aside>
}
}
File diff suppressed because one or more lines are too long
+69 -41
View File
@@ -78,7 +78,8 @@ fn apply(state: &Shared) {
"false"
},
);
let _ = body.set_attribute("class", &format!("b R2 theme-{theme}"));
// Legacy preference values remain intact; all use the approved dark material.
let _ = body.set_attribute("class", "b R2 theme-graphite");
}
let image = p["image"].as_str().map(str::to_owned).unwrap_or_else(|| {
format!(
@@ -118,32 +119,7 @@ fn apply(state: &Shared) {
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 { "" }),
);
});
text("theme-name", "深海蓝玻璃");
each("[data-wall]", |e| {
let active = p["image"].is_null()
&& e.get_attribute("data-wall").as_deref() == p["wallpaper"].as_str();
@@ -158,10 +134,43 @@ fn apply(state: &Shared) {
);
});
if let Some(sample) = el("desktop-sample").and_then(|e| e.dyn_into::<HtmlElement>().ok()) {
let _ = sample.style().set_property(
"--preview-shade",
&(p["dim"].as_f64().unwrap_or(14.0) / 100.0).to_string(),
);
let _ = sample
.style()
.set_property("background-image", &format!("url(\"{image}\")"));
.set_property("--preview-blur", &format!("{}px", p["blur"]));
}
if let Some(preview) = el("appearance-wallpaper") {
let _ = preview.set_attribute("src", &image);
if let Some(element) = preview.dyn_ref::<HtmlElement>() {
let _ = element
.style()
.set_property("object-fit", p["fit"].as_str().unwrap_or("cover"));
}
}
let wallpaper_name = if p["image"].is_string() {
"自定义壁纸"
} else {
match p["wallpaper"].as_str().unwrap_or("B4") {
"B1" => "黑曜石柔光",
"B2" => "午夜蓝丝绸",
"B3" => "石墨空间玻璃",
_ => "科技网格",
}
};
text("appearance-wallpaper-name", wallpaper_name);
text("appearance-dim-value", &format!("{}%", p["dim"]));
text("appearance-blur-value", &format!("{} px", p["blur"]));
text(
"appearance-fit-value",
if p["fit"].as_str() == Some("contain") {
"完整显示"
} else {
"铺满屏幕"
},
);
}
async fn fetch_preferences(state: Shared) {
let result = async {
@@ -276,14 +285,14 @@ fn show(view: &str, realtime: bool) {
}
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") {
text(
"workspace-brand",
if view == "home" {
let _ = header.set_attribute("hidden", "");
"RID 工作空间"
} else {
let _ = header.remove_attribute("hidden");
}
}
"应用"
},
);
each(".homescreen", |e| {
if view == "home" {
let _ = e.remove_attribute("hidden");
@@ -481,6 +490,32 @@ pub fn init(realtime: bool) {
show("home", realtime);
return;
}
if let Some(section) = button.get_attribute("data-setting-section") {
if let Some(target) = el(&section) {
target.scroll_into_view();
if let Some(element) = target.dyn_ref::<HtmlElement>() {
let _ = element.focus();
}
}
each("[data-setting-section]", |entry| {
let active = entry.get_attribute("data-setting-section").as_deref()
== Some(section.as_str());
let _ = entry.set_attribute(
"class",
if active {
"setting-link active"
} else {
"setting-link"
},
);
if active {
let _ = entry.set_attribute("aria-current", "location");
} else {
let _ = entry.remove_attribute("aria-current");
}
});
return;
}
if let Some(view) = button.get_attribute("data-open") {
show(&view, realtime);
if view == "settings" {
@@ -491,13 +526,6 @@ pub fn init(realtime: bool) {
}
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();
+12 -10
View File
@@ -21,7 +21,7 @@ let output='',child,browser;const errors=[],csp=[];
function start(){const previous=process.env.TIANDITU_TOKEN;delete process.env.TIANDITU_TOKEN;child=spawn(exe,['--data-root',root,'--simulation-api'],{env:{...process.env,PATH:'C:\\Windows\\System32',RID_TEST_PORT:'18890'},windowsHide:true,stdio:['ignore','pipe','pipe']});if(previous!==undefined)process.env.TIANDITU_TOKEN=previous;child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);child.on('error',e=>output+=e.message);}
async function ready(){for(let i=0;i<150;i++){if(child.exitCode!==null)throw Error(output);try{if((await fetch(base+'/api/appearance')).ok)return;}catch{}await new Promise(r=>setTimeout(r,100));}throw Error('server timeout '+output);}
async function stop(){if(child&&child.exitCode===null){const done=new Promise(r=>child.once('exit',r));child.kill();await done;}}
let report={};let keepalive;let minimumOptionContrast=Infinity;
let report={};let keepalive;
const wait=ms=>new Promise(r=>setTimeout(r,ms));
const token=JSON.parse(await readFile(path.resolve('maps/config.json'),'utf8')).tianditu_token;
await mkdir(path.join(root,'maps'),{recursive:true});await writeFile(path.join(root,'maps/config.json'),JSON.stringify({tianditu_token:token}));
@@ -30,20 +30,22 @@ try {
for(const file of ['index.html','map-adapter.js','workspace-native.css']){const response=await fetch(base+'/'+(file==='index.html'?'realtime':file));assert.equal(response.status,200);const body=await response.text();assert.ok(body===await readFile(path.join('dist/web-ui',file),'utf8'),'stale embedded '+file);assert.ok(!body.includes(token),'credential in frontend');}
const initial=await(await fetch(base+'/api/maps/status')).json();assert.equal(initial.keyConfigured,true);assert.ok(!JSON.stringify(initial).includes(token));
browser=await chromium.launch({headless:true,executablePath:process.env.RID_BROWSER_PATH||'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'});
const context=await browser.newContext({viewport:{width:1600,height:1000}});const page=await context.newPage();const loaded=new Set();let credentialRequest=false;
const context=await browser.newContext({viewport:{width:1600,height:1000}});await context.addInitScript(()=>localStorage.setItem('rid.realtime.basemap.v1','road'));const page=await context.newPage();const loaded=new Set();let credentialRequest=false;
page.on('pageerror',e=>errors.push(e.message));page.on('console',m=>{if(/violates.*Content Security|Refused.*policy/i.test(m.text()))csp.push(m.text())});
page.on('request',r=>{if(r.url().includes(token)||r.url().includes('tianditu.gov.cn'))credentialRequest=true;});
page.on('response',r=>{const m=r.url().match(/\/api\/maps\/tile\/([^/]+)\//);if(m&&r.status()===200)loaded.add(m[1]);});
await page.goto(base+'/realtime');await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();const picker=page.getByRole('combobox',{name:'底图类型'});assert.equal(await picker.inputValue(),'road');
await page.waitForFunction(()=>window.ridMap?.metrics().mapReady);await page.waitForFunction(()=>document.querySelector('.mc-map-infobar').textContent.includes('路网图')&&!document.querySelector('.mc-map-infobar').textContent.includes('暂无'),null,{timeout:45000});
await page.goto(base+'/realtime');await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();assert.equal(await page.locator('.mc-map-toolstrip').count(),0);await page.waitForFunction(()=>{const m=window.ridMap?.metrics();return m?.mapReady&&m.baseTiles[0].includes('img_w')&&m.labelTiles[0].includes('cia_w')});await page.waitForFunction(()=>document.querySelector('.mc-map-infobar').textContent.includes('影像+路网')&&!document.querySelector('.mc-map-infobar').textContent.includes('暂无'),null,{timeout:45000});await page.screenshot({path:path.join(root,'hybrid-default.png')});await changeBasemap('road');
await page.waitForFunction(()=>window.ridMap?.metrics().mapReady);await page.waitForFunction(()=>window.ridMap.metrics().basemap==='road'&&!document.querySelector('.mc-map-infobar').textContent.includes('暂无'),null,{timeout:45000});
async function changeBasemap(value){await page.evaluate(v=>window.ridMap.setBasemap(v),value);}
assert.deepEqual(await page.evaluate(()=>{const {pitch,bearing}=window.ridMap.metrics().camera;return {pitch,bearing}}),{pitch:0,bearing:0});
async function ingest(sequence){const r=await fetch(base+'/api/realtime/ingest',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify([{target_id:'MAP-TEST-001',receiver_id:'MAP-TEST',source_epoch:1,sequence,longitude:120.1538,latitude:30.2874,altitude_m:120,heading_deg:42}])});assert.equal(r.status,200)}
let seq=1;await ingest(seq);keepalive=setInterval(()=>ingest(++seq).catch(()=>{}),5000);await page.getByRole('button',{name:'MAP-TEST-001',exact:true}).click();await wait(500);const camera=(await page.evaluate(()=>window.ridMap.metrics())).camera;
await page.screenshot({path:path.join(root,'road-live.png')});
await picker.selectOption('imagery');await page.waitForFunction(()=>window.ridMap.metrics().baseTiles[0].includes('img_w'));await page.waitForFunction(()=>document.querySelector('.mc-map-infobar').textContent.includes('影像图')&&!document.querySelector('.mc-map-infobar').textContent.includes('暂无'),null,{timeout:45000});await wait(1200);await page.screenshot({path:path.join(root,'imagery-live.png')});
for(let i=0;i<8;i++)await picker.selectOption(i%2?'imagery':'road');await wait(1200);
await changeBasemap('imagery');await page.waitForFunction(()=>window.ridMap.metrics().baseTiles[0].includes('img_w'));await page.waitForFunction(()=>document.querySelector('.mc-map-infobar').textContent.includes('影像+路网')&&!document.querySelector('.mc-map-infobar').textContent.includes('暂无'),null,{timeout:45000});await wait(1200);await page.screenshot({path:path.join(root,'imagery-live.png')});
for(let i=0;i<8;i++)await changeBasemap(i%2?'imagery':'road');await wait(1200);
const switched=await page.evaluate(()=>window.ridMap.metrics());assert.equal(switched.mapCreations,1);assert.equal(switched.targets,1);assert.deepEqual(switched.camera,camera);assert.ok(switched.labelTiles[0].includes('cia_w'));assert.ok(switched.selectedTrailPoints>0);
await page.reload();await picker.waitFor();assert.equal(await picker.inputValue(),'imagery');await page.waitForFunction(()=>window.ridMap?.metrics().mapReady);await wait(3500);
for(const [width,height]of [[1600,1000],[1280,720],[390,844],[360,740]]){await page.setViewportSize({width,height});await wait(250);for(const theme of ['graphite','blue','white']){await page.evaluate(t=>{document.body.classList.remove('theme-blue','theme-white');if(t!=='graphite')document.body.classList.add('theme-'+t)},theme);const clipped=await page.evaluate(()=>{const bar=document.querySelector('.mc-map-toolstrip').getBoundingClientRect();return [...document.querySelectorAll('.mc-map-toolstrip button,.mc-map-toolstrip select')].some(e=>{const r=e.getBoundingClientRect();return r.left<bar.left-1||r.right>bar.right+1||r.right>innerWidth||r.top<bar.top-1||r.bottom>bar.bottom+1})});assert.equal(clipped,false,JSON.stringify({width,height,theme}));assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);const contrast=await picker.locator('option').first().evaluate(e=>{const s=getComputedStyle(e);const lum=color=>{const rgb=color.match(/[\d.]+/g).slice(0,3).map(Number).map(v=>{v/=255;return v<=.04045?v/12.92:((v+.055)/1.055)**2.4});return rgb[0]*.2126+rgb[1]*.7152+rgb[2]*.0722};const a=lum(s.color),b=lum(s.backgroundColor);return (Math.max(a,b)+.05)/(Math.min(a,b)+.05)});minimumOptionContrast=Math.min(minimumOptionContrast,contrast);assert.ok(contrast>=4.5,'Basemap option contrast is insufficient in '+theme);}}
await page.reload();await page.waitForFunction(()=>window.ridMap?.metrics().basemap==='imagery');await page.waitForFunction(()=>window.ridMap?.metrics().mapReady);await wait(3500);
for(const [width,height]of [[1600,1000],[1280,720],[390,844],[360,740]]){await page.setViewportSize({width,height});await wait(250);assert.equal(await page.locator('.mc-map-toolstrip').count(),0);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.equal(await page.evaluate(()=>window.ridMap.metrics().camera.pitch),0);}
await page.setViewportSize({width:1600,height:1000});await page.evaluate(()=>document.body.classList.remove('theme-blue','theme-white'));await wait(250);
// Browser failure/recovery fixtures; backend outage/timeout/offline paths are tested with real local mock upstreams in Rust.
let fixture={provider:'tianditu',keyConfigured:true,mode:'offline',retryAfterMs:Date.now()+30000,layers:{img_w:{source:'missing',error:'key-or-permission'},cia_w:{source:'missing',error:'key-or-permission'}}};
@@ -53,7 +55,7 @@ try {
assert.deepEqual([...loaded].sort(),['cia_w','cva_w','img_w','vec_w']);assert.equal(credentialRequest,false);assert.deepEqual(errors,[]);assert.deepEqual(csp,[]);
const status=await(await fetch(base+'/api/maps/status')).json();assert.ok(status.servedOnline>0);assert.ok(status.servedOffline>0);assert.equal((await(await fetch(base+'/api/realtime/status')).json()).clients,1);
assert.ok(!output.includes(token),'credential in server log');
await picker.selectOption('road');await wait(4000);await page.screenshot({path:path.join(root,'road-final.png')});await picker.selectOption('imagery');await wait(4000);await page.screenshot({path:path.join(root,'imagery-final.png')});
report={status:'PASS',root,exe,serverPid:child.pid,loadedLayers:[...loaded].sort(),servedOnline:status.servedOnline,servedOffline:status.servedOffline,mapCreations:switched.mapCreations,frames:12,minimumOptionContrast,checks:['real-road-and-labels','real-imagery-and-labels','same-camera-target-trail-on-switch','preference-after-reload','toolbar-four-sizes-three-themes','dropdown-text-contrast','credential-not-in-browser-or-log','error-and-recovery-ui-fixtures','one-worker-connection'],note:'Real TianDiTu tiles; isolated synthetic target. Actual upstream outage tests run in Rust, browser recovery uses provider-state fixtures.'};console.log(JSON.stringify(report));
await changeBasemap('road');await wait(4000);await page.screenshot({path:path.join(root,'road-final.png')});await changeBasemap('imagery');await wait(4000);await page.screenshot({path:path.join(root,'imagery-final.png')});
report={status:'PASS',root,exe,serverPid:child.pid,loadedLayers:[...loaded].sort(),servedOnline:status.servedOnline,servedOffline:status.servedOffline,mapCreations:switched.mapCreations,frames:12,checks:['legacy-road-preference-upgrades-to-hybrid-default','real-road-and-labels','real-imagery-and-labels','same-camera-target-trail-on-switch','preference-after-reload','removed-toolbar-four-sizes','topdown-default','credential-not-in-browser-or-log','error-and-recovery-ui-fixtures','one-worker-connection'],note:'Real TianDiTu tiles; isolated synthetic target. Actual upstream outage tests run in Rust, browser recovery uses provider-state fixtures.'};console.log(JSON.stringify(report));
}finally{clearInterval(keepalive);if(browser){if(report.status!=='PASS'){const p=browser.contexts()[0]?.pages()[0];if(p){await p.screenshot({path:path.join(root,'failure.png')}).catch(()=>{});console.log(JSON.stringify({root,errors,csp,diagnostic:await p.evaluate(()=>({label:document.querySelector('.mc-map-infobar')?.textContent,metrics:window.ridMap?.metrics()})).catch(()=>null)}));}}await browser.close();}await stop();for(const socket of sockets)socket.destroy();const closed=new Promise(r=>proxy.close(r));proxy.closeAllConnections();await closed;await writeFile(path.join(root,'server.log'),output);await writeFile(path.join(root,'maps-report.json'),JSON.stringify({...report,errors,csp},null,2));}
+25 -5
View File
@@ -24,6 +24,23 @@ async function ready(){for(let i=0;i<150;i++){if(child.exitCode!==null)throw Err
async function stop(){if(child&&child.exitCode===null){const done=new Promise(r=>child.once('exit',r));child.kill();await done;}}
async function preferences(){return (await fetch(base+'/api/appearance')).json();}
async function waitPref(predicate){for(let i=0;i<80;i++){const p=await preferences();if(predicate(p))return p;await new Promise(r=>setTimeout(r,100));}throw Error('preferences timeout');}
async function setLegacyTheme(page, theme) {
const screen = await page.locator("body").getAttribute("data-screen");
const query = await page.locator("#history-query").count() ? await page.locator("#history-query").inputValue() : "";
const current = await preferences();
const response = await fetch(base+'/api/appearance', {method:'PATCH', headers:{'content-type':'application/json'}, body:JSON.stringify({...current, theme})});
assert.equal(response.status, 200);
await page.reload();
await page.waitForFunction(t => document.body.dataset.theme === t, theme);
if (screen !== await page.locator("body").getAttribute("data-screen")) {
if (await page.locator("body").getAttribute("data-screen") !== "home") await page.getByRole("button",{name:"返回应用总览",exact:true}).click();
await page.locator("#home-app-"+screen).click();
}
if (query) { await page.locator("#history-query").fill(query); const total=(await (await fetch(base+"/api/records?page=1&q="+encodeURIComponent(query))).json()).total; await page.locator("#page-status").filter({hasText:"共 "+total+" 条"}).waitFor(); }
assert.equal(await page.locator('.theme-quick, .theme-cards').count(), 0);
assert.equal(await page.locator('body').evaluate(e => getComputedStyle(e).getPropertyValue('--work-panel').trim()), 'rgba(6, 18, 33, .40)');
}
try {
await new Promise((resolve,reject)=>{proxy.once('error',reject);proxy.listen(frontendPort,'127.0.0.1',resolve)});
@@ -67,6 +84,9 @@ try {
console.log('STAGE submit');
// Failure restores all controls and keeps draft + photos; busy navigation is blocked.
await page.locator('#serial-no').fill('B-NEW-001');await page.locator('#model-name').fill('验收新机');await page.locator('#owner-name').fill('原始快照');await choose('#photo-1','snapshot.png');await readyPhoto(0,'snapshot.png');
const draftPhoto=await page.locator('#slot-preview-0').getAttribute('src');
await page.getByRole('button',{name:'返回应用总览',exact:true}).click();await page.locator('#home-app-settings').click();await page.getByRole('button',{name:'返回应用总览',exact:true}).click();await page.locator('#home-app-register').click();
assert.equal(await page.locator('#serial-no').inputValue(),'B-NEW-001');assert.equal(await page.locator('#owner-name').inputValue(),'原始快照');assert.equal(await page.locator('#slot-preview-0').getAttribute('src'),draftPhoto);assert.equal(await page.evaluate(()=>window.ridPhotoUrls.size),1);
let requests=0;
await page.route('**/api/records',async route=>{if(route.request().method()==='POST'){requests++;assert.equal(route.request().postDataJSON().ownerName,'原始快照');await new Promise(r=>setTimeout(r,450));await route.fulfill({status:500,contentType:'application/json',body:JSON.stringify({error:'隔离验收失败'})})}else await route.continue()});
const sent=page.waitForRequest(r=>r.url().endsWith('/api/records')&&r.method()==='POST');await page.locator('#register-button').click();await sent;assert.equal(await page.locator('#serial-no').isDisabled(),true);assert.equal(await page.locator('#new-registration').isDisabled(),true);await page.getByRole('button',{name:'返回应用总览',exact:true}).click();assert.equal(await page.locator('body').getAttribute('data-screen'),'register');await page.locator('#register-form').evaluate(f=>{f.dispatchEvent(new Event('submit',{bubbles:true,cancelable:true}));f.dispatchEvent(new Event('submit',{bubbles:true,cancelable:true}))});
@@ -89,17 +109,17 @@ try {
await page.locator('#edit-owner').fill('不得保存');await page.locator('#edit-photo-1').setInputFiles({name:'bad.png',mimeType:'image/png',buffer:Buffer.from('bad')});await page.locator('#slot-status-2.error').waitFor();await page.locator('#edit-save').click();await page.locator('#edit-message').filter({hasText:'照片内容与格式不符'}).waitFor();assert.equal((await(await fetch(base+'/api/records?q=B-NEW-001')).json()).records[0].ownerName,'更新登记人');await page.locator('#edit-cancel').click();
await edit();await page.locator('#edit-owner').fill('修改后');await page.locator('#edit-delete-1').check();await choose('#edit-photo-2','replacement.png');await readyPhoto(3,'replacement.png');await page.locator('#edit-save').click();await page.locator('#edit-dialog').waitFor({state:'hidden'});await page.locator('#history-message').filter({hasText:'档案修改已保存'}).waitFor();records=(await(await fetch(base+'/api/records?q=B-NEW-001')).json()).records;assert.equal(records[0].photo1Url,null);assert.ok(records[0].photo2Url);assert.equal(records[0].ownerName,'修改后');
console.log('STAGE geometry');
// Three themes and viewport/zoom geometry, including the final helper and save button.
// Legacy theme preferences share one material; verify viewport/zoom geometry.
const cases=[];await page.locator('#new-registration').click();
for(const theme of ['graphite','blue','white']){await page.locator('.theme-quick [data-theme='+theme+']').click();await waitPref(p=>p.theme===theme);
for(const [width,height]of [[1600,1000],[1366,768],[1080,900],[390,844],[1366,600]]){await page.setViewportSize({width,height});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.locator('.registration-photos').scrollIntoViewIfNeeded();await page.locator('#register-button').scrollIntoViewIfNeeded();const box=await page.locator('#register-button').boundingBox();assert.ok(box.x>=0&&box.x+box.width<=width&&box.y>=48&&box.y+box.height<=height+1);await page.locator('#register-form>.registry-group:last-of-type>.registry-help').scrollIntoViewIfNeeded();const overlap=await page.evaluate(()=>{const a=document.querySelector('#register-form>.registry-group:last-of-type>.registry-help').getBoundingClientRect(),b=document.querySelector('.registration-savebar').getBoundingClientRect();return a.bottom>b.top&&a.top<b.bottom});assert.equal(overlap,false);cases.push({theme,width,height});if(width===1600){await page.locator('.registration-heading').scrollIntoViewIfNeeded();await page.screenshot({path:path.join(root,'register-'+theme+'.png')})}}
for(const theme of ['graphite','blue','white']){await setLegacyTheme(page,theme);
for(const [width,height]of [[1600,1000],[1366,768],[1080,900],[390,844],[1366,600]]){await page.setViewportSize({width,height});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.locator('.registration-photos').scrollIntoViewIfNeeded();await page.locator('#register-button').scrollIntoViewIfNeeded();const box=await page.locator('#register-button').boundingBox();assert.ok(box.x>=0&&box.x+box.width<=width&&box.y>=48&&box.y+box.height<=height+1);await page.locator('#register-form .registration-fields-scroll>.registry-group:last-of-type>.registry-help').scrollIntoViewIfNeeded();const overlap=await page.evaluate(()=>{const a=document.querySelector('#register-form .registration-fields-scroll>.registry-group:last-of-type>.registry-help').getBoundingClientRect(),b=document.querySelector('.registration-savebar').getBoundingClientRect();return a.bottom>b.top&&a.top<b.bottom});assert.equal(overlap,false);cases.push({theme,width,height});if(width===1600){await page.locator('.registration-heading').scrollIntoViewIfNeeded();await page.screenshot({path:path.join(root,'register-'+theme+'.png')})}}
}
await page.setViewportSize({width:1600,height:1000});await page.evaluate(()=>document.documentElement.style.zoom='2');assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.locator('#register-button').scrollIntoViewIfNeeded();await page.screenshot({path:path.join(root,'register-zoom200.png')});await page.evaluate(()=>document.documentElement.style.zoom='');
await page.setViewportSize({width:390,height:844});await page.locator('#history-title').scrollIntoViewIfNeeded();const mobileBar=await page.locator('.registration-savebar').boundingBox();const mobileHistory=await page.locator('#history-title').boundingBox();assert.ok(mobileBar.y+mobileBar.height<=mobileHistory.y);await page.setViewportSize({width:1600,height:1000});
await page.setViewportSize({width:390,height:844});await page.locator('#history-title').scrollIntoViewIfNeeded();const mobileHistory=await page.locator('.history-panel').boundingBox();const mobileEditor=await page.locator('.registration-editor').boundingBox();assert.ok(mobileHistory.height<=280.5);assert.ok(mobileHistory.y+mobileHistory.height<=mobileEditor.y);await page.setViewportSize({width:1600,height:1000});
console.log('STAGE delete');
// Delete current result and preserve unrelated records.
await own.getByRole('button',{name:'查看档案 →',exact:true}).click();await own.locator('.archive-more').click();page.once('dialog',d=>d.accept());await own.getByRole('button',{name:'删除档案',exact:true}).click();await page.locator('#empty-result').waitFor();await page.locator('#page-status').filter({hasText:'共 0 条'}).waitFor();assert.equal((await(await fetch(base+'/api/records?page=1')).json()).total,21);
await page.locator('#history-query').fill('');await page.locator('#page-status').filter({hasText:'共 21 条'}).waitFor();await page.locator('#next-page').click();await page.locator('#page-status').filter({hasText:'第 2 / 2 页'}).waitFor();assert.equal(await page.locator('.archive-card').count(),1);
assert.deepEqual(errors,[]);assert.deepEqual(csp,[]);
await writeFile(path.join(root,'report.json'),JSON.stringify({status:'PASS',root,errors,csp,cases,scenarios:['real Rust/Wasm registration B','validated photo preservation, cancel, replacement, reset, stale decode','immutable submit, failed save, duplicate suppression, busy navigation','draft/result separation, new confirmation','menu focus, selection redraw, current-page Excel and ZIP','duplicate SN, edit atomicity and delete current result','QR PNG and clipboard/archive links','three themes, 15 viewport cases, 200% zoom, mobile save boundary']},null,2));console.log(JSON.stringify({status:'PASS',root}));
await writeFile(path.join(root,'report.json'),JSON.stringify({status:'PASS',root,errors,csp,cases,scenarios:['real Rust/Wasm registration B','validated photo preservation, cancel, replacement, reset, stale decode','immutable submit, failed save, duplicate suppression, busy navigation','draft/result separation, new confirmation','menu focus, selection redraw, current-page Excel and ZIP','duplicate SN, edit atomicity and delete current result','QR PNG and clipboard/archive links','three legacy theme values, 15 viewport cases, 200% zoom, mobile save boundary']},null,2));console.log(JSON.stringify({status:'PASS',root}));
}catch(e){console.log('FAILED ROOT',root,e.stack);if(browser){const pages=browser.contexts().flatMap(c=>c.pages());if(pages[0])await pages[0].screenshot({path:path.join(root,'failed.png')}).catch(()=>{});}throw e;}finally{if(browser)await browser.close();await stop();for(const socket of sockets)socket.destroy();await new Promise(r=>proxy.close(r));await writeFile(path.join(root,'server.log'),output)}
+118 -15
View File
@@ -1,5 +1,5 @@
// Real Rust/Wasm acceptance in an isolated database. Never opens receiver transports.
import {mkdtemp,writeFile} from 'node:fs/promises';
import {mkdtemp,writeFile,readFile} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import path from 'node:path';
import {spawn} from 'node:child_process';
@@ -8,6 +8,14 @@ import assert from 'node:assert/strict';
import http from 'node:http';
import net from 'node:net';
const {chromium}=createRequire(import.meta.url)('playwright');
const {PNG}=createRequire(import.meta.url)('pngjs');
const contrastCases=[];
async function contrast(page, label, selectors, required=true) {
const samples=await page.evaluate(selectors=>selectors.map(selector=>{const e=document.querySelector(selector),r=e.getBoundingClientRect();return {selector,color:getComputedStyle(e).color,x:Math.round(r.left+2),y:Math.round(r.top-2)}}),selectors);
const png=PNG.sync.read(await page.screenshot());
const lum=rgb=>rgb.map(v=>v/255).map(v=>v<=.04045?v/12.92:((v+.055)/1.055)**2.4).reduce((s,v,i)=>s+v*[.2126,.7152,.0722][i],0);
for(const sample of samples){const offset=(sample.y*png.width+sample.x)*4;const a=lum(sample.color.match(/[\d.]+/g).slice(0,3).map(Number)),b=lum([...png.data.subarray(offset,offset+3)]);const ratio=(Math.max(a,b)+.05)/(Math.min(a,b)+.05);contrastCases.push({label,selector:sample.selector,ratio});if(required)assert.ok(ratio>=4.5,JSON.stringify({label,...sample,ratio}));}
}
const root=await mkdtemp(path.join(tmpdir(),'RID-workspace-'));
const exe=process.argv[2]||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry-fullstack.exe';
const frontendPort=Number(process.env.RID_BROWSER_TEST_PORT||18787),backendPort=Number(process.env.RID_BACKEND_TEST_PORT||18788);
@@ -24,16 +32,35 @@ async function ready(){for(let i=0;i<150;i++){if(child.exitCode!==null)throw Err
async function stop(){if(child&&child.exitCode===null){const done=new Promise(r=>child.once('exit',r));child.kill();await done;}}
async function preferences(){return (await fetch(base+'/api/appearance')).json();}
async function waitPref(predicate){for(let i=0;i<80;i++){const p=await preferences();if(predicate(p))return p;await new Promise(r=>setTimeout(r,100));}throw Error('preferences timeout');}
async function setLegacyTheme(page, theme) {
const screen = await page.locator("body").getAttribute("data-screen");
const query = await page.locator("#history-query").count() ? await page.locator("#history-query").inputValue() : "";
const current = await preferences();
const response = await fetch(base+'/api/appearance', {method:'PATCH', headers:{'content-type':'application/json'}, body:JSON.stringify({...current, theme})});
assert.equal(response.status, 200);
await page.reload();
await page.waitForFunction(t => document.body.dataset.theme === t, theme);
if (screen !== await page.locator("body").getAttribute("data-screen")) {
if (await page.locator("body").getAttribute("data-screen") !== "home") await page.getByRole("button",{name:"返回应用总览",exact:true}).click();
await page.locator("#home-app-"+screen).click();
}
if (query) { await page.locator("#history-query").fill(query); const total=(await (await fetch(base+"/api/records?page=1&q="+encodeURIComponent(query))).json()).total; await page.locator("#page-status").filter({hasText:"共 "+total+" 条"}).waitFor(); }
assert.equal(await page.locator('.theme-quick, .theme-cards').count(), 0);
assert.equal(await page.locator('body').evaluate(e => getComputedStyle(e).getPropertyValue('--work-panel').trim()), 'rgba(6, 18, 33, .40)');
}
try{
await new Promise((resolve,reject)=>{proxy.once('error',reject);proxy.listen(frontendPort,'127.0.0.1',resolve)});start();await ready();browser=await chromium.launch({headless:true,executablePath:process.env.RID_BROWSER_PATH||'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'});
const context=await browser.newContext({viewport:{width:1600,height:1000},acceptDownloads:true});const page=await context.newPage();page.on('pageerror',e=>errors.push(e.message));page.on('console',m=>{if(/violates.*Content Security|Refused.*policy/i.test(m.text()))csp.push(m.text());});
for(const asset of ['glass.css','workbench.css'])assert.equal(await (await fetch(base+'/'+asset)).text(), await readFile('crates/web-ui/public/'+asset,'utf8'));
await page.goto(base);await page.locator('body[data-screen=home]').waitFor();
assert.equal((await preferences()).wallpaper,'B4');
assert.equal(await page.locator('.home-card').count(),3);
assert.equal(await page.locator('.reference-rail').isVisible(),false);
assert.equal(await page.locator('#toggle-menu').isVisible(),false);
assert.equal(await page.locator('#home-top').isVisible(),true);
await page.keyboard.press('Tab');assert.equal(await page.evaluate(()=>document.activeElement.id),'home-app-register');
assert.equal(await page.locator('.reference-rail').isVisible(),true);
assert.equal(await page.locator('#toggle-menu').isVisible(),true);
assert.equal(await page.locator('#home-top').count(),0);
await page.keyboard.press('Tab');assert.equal(await page.evaluate(()=>document.activeElement.id),'toggle-menu');
await page.locator('#home-app-register').focus();
await page.keyboard.press('Enter');await page.locator('body[data-screen=register]').waitFor();
assert.equal(await page.locator('.reference-rail').isVisible(),true);
await page.locator('#toggle-menu').click();assert.equal(await page.locator('.reference-rail').isVisible(),false);
@@ -44,37 +71,113 @@ try{
await page.keyboard.press('Space');await preferenceLoaded;await page.locator('#appearance-view').waitFor();
assert.equal(await page.locator('.reference-rail').isVisible(),false); // home did not reset the user's collapsed navigation.
await page.locator('#toggle-menu').click();assert.equal(await page.locator('.reference-rail').isVisible(),true);
const homeCases=[];
const homeCases=[],workbenchCases=[];
for(const theme of ['blue','white','graphite']){
await page.locator('.theme-quick [data-theme='+theme+']').click();await waitPref(p=>p.theme===theme);assert.equal(await page.locator('body').getAttribute('data-theme'),theme);await page.screenshot({path:path.join(root,'settings-'+theme+'.png')});
await setLegacyTheme(page,theme);assert.equal(await page.locator('body').getAttribute('data-theme'),theme);await page.screenshot({path:path.join(root,'settings-'+theme+'.png')});
await page.getByRole('button',{name:'返回应用总览',exact:true}).click();
assert.equal(await page.evaluate(()=>document.activeElement.id),'home-app-settings');
await page.waitForFunction(()=>[...document.querySelectorAll('.home-app-icon')].every(i=>i.complete&&i.naturalWidth>0));
for(const [width,height] of [[1600,1000],[1366,768],[1080,900],[390,844],[1366,600]]){
await page.setViewportSize({width,height});
assert.equal(await page.locator('.reference-rail').isVisible(),false);
const dimensions=await page.locator('.home-launcher').boundingBox();assert.equal(Math.round(dimensions.x),0);assert.equal(Math.round(dimensions.y),48);assert.equal(Math.round(dimensions.width),width);assert.equal(Math.round(dimensions.y+dimensions.height),height);
assert.equal(await page.locator('.reference-rail').isVisible(),true);
const dimensions=await page.locator('.home-launcher').boundingBox();const railWidth=width<=760?56:68;assert.equal(Math.round(dimensions.x),railWidth);assert.equal(Math.round(dimensions.y),48);assert.equal(Math.round(dimensions.width),width-railWidth);assert.equal(Math.round(dimensions.y+dimensions.height),height);
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
await page.locator('#home-app-settings').scrollIntoViewIfNeeded();
assert.equal(await page.locator('#home-app-settings').isVisible(),true);
homeCases.push({theme,width,height});
if(width===1600){await page.mouse.move(1550,20);await page.screenshot({path:path.join(root,'home-'+theme+'.png')});}
if(width===1600){await page.mouse.move(1550,20);await page.screenshot({path:path.join(root,'home-'+theme+'.png')});await contrast(page,'home-'+theme,['.home-heading p','.home-card-desc']);}
}
await page.setViewportSize({width:1600,height:1000});await page.locator('#home-app-settings').click();await page.locator('#appearance-view').waitFor();
}
await writeFile(path.join(root,'home-viewport-cases.json'),JSON.stringify(homeCases,null,2));
// Verify materials on both built-in reference wallpapers and a bright custom image.
for (const wall of ['B4','B1']) {
await page.locator('[data-wall='+wall+']').click();await waitPref(p=>p.wallpaper===wall);
await page.waitForFunction(w=>document.getElementById('appearance-wallpaper').src.includes(w+'-wallpaper'),wall);
for (const [width,height] of [[1600,1000],[1366,768],[390,844]]) {
await page.setViewportSize({width,height});
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
await page.screenshot({path:path.join(root,`settings-${wall}-${width}.png`)});
}
}
await page.setViewportSize({width:1600,height:1000});
// Verify the A workbench columns and all three panels at every breakpoint.
for(const [width,height] of [[1600,1000],[1366,600],[1080,900],[820,900],[390,844]]){
await page.setViewportSize({width,height});
for(const screen of ['settings','register']){
if(screen==='register')await page.locator('.reference-rail [data-open=register]').click();
const layoutRoot=page.locator(screen==='settings'?'.settings-layout':'.registry-workspace');
const available=await page.locator(screen==='settings'?'#appearance-view':'#workspace-content').evaluate(e=>e.clientWidth);
const columns=available>=1200?3:available>=768?2:1;
const actual=await layoutRoot.evaluate(e=>getComputedStyle(e).display==='flex'?1:getComputedStyle(e).gridTemplateColumns.split(' ').length);
assert.equal(actual,columns,JSON.stringify({screen,width,available,actual}));
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
if(screen==='settings'){
assert.equal(await page.locator('.settings-preview').isVisible(),true);
const sample=await page.locator('#desktop-sample').boundingBox();assert.equal(Math.round(sample.height),180);
await page.locator('#appearance-view').evaluate(e=>e.scrollTop=0);
}else{
assert.equal(await page.locator('#registration-result').isVisible(),true);
await page.locator('#register-button').scrollIntoViewIfNeeded();
const save=await page.locator('#register-button').boundingBox();assert.ok(save.y>=48&&save.y+save.height<=height+1);
await page.locator('#workspace-content').evaluate(e=>e.scrollTop=0);
}
await page.screenshot({path:path.join(root,`workbench-${screen}-${width}.png`)});
workbenchCases.push({screen,width,height,columns});
}
await page.locator('.reference-rail [data-open=settings]').click();
}
await page.setViewportSize({width:1600,height:1000});
const savedBeforeSection=await preferences();
await page.locator('[data-setting-section=appearance-display]').click();
assert.equal(await page.evaluate(()=>document.activeElement.id),'appearance-display');
assert.equal((await preferences()).revision,savedBeforeSection.revision);
await page.locator('[data-setting-section=appearance-wallpapers]').click();
let failAppearance=true;
await page.route('**/api/appearance',route=>{if(route.request().method()==='PATCH'&&failAppearance){failAppearance=false;return route.fulfill({status:503,contentType:'application/json',body:JSON.stringify({error:'隔离外观保存失败'})})}return route.continue()});
await page.locator('#dim').fill('35');await page.locator('#dim').dispatchEvent('input');
await page.locator('#wall-message.error').filter({hasText:'隔离外观保存失败'}).waitFor();
assert.equal((await preferences()).dim,savedBeforeSection.dim);
assert.equal(await page.locator('#appearance-dim-value').innerText(),savedBeforeSection.dim+'%');
await page.unroute('**/api/appearance');
await page.locator('[data-wall=B2]').click();await waitPref(p=>p.wallpaper==='B2');await page.locator('#dim').fill('28');await page.locator('#dim').dispatchEvent('input');await waitPref(p=>p.dim===28);
assert.equal(await page.locator('#appearance-dim-value').innerText(),'28%');
await page.locator('#blur').fill('3');await page.locator('#blur').dispatchEvent('input');await waitPref(p=>p.blur===3);
assert.equal(await page.locator('#appearance-blur-value').innerText(),'3 px');
assert.equal(await page.locator('#desktop-sample').evaluate(e=>e.style.getPropertyValue('--preview-blur')),'3px');
assert.equal(await page.locator('#desktop-sample').evaluate(e=>e.style.getPropertyValue('--preview-shade')),'0.28');
await page.locator('#fit').selectOption('contain');await waitPref(p=>p.fit==='contain');assert.equal(await page.locator('#appearance-fit-value').innerText(),'完整显示');
assert.equal(await page.locator('#appearance-wallpaper').evaluate(e=>getComputedStyle(e).objectFit),'contain');
await page.locator('#fit').selectOption('cover');await waitPref(p=>p.fit==='cover');
await page.locator('#blur').fill('0');await page.locator('#blur').dispatchEvent('input');await waitPref(p=>p.blur===0);
const picture=await page.screenshot();await page.locator('#custom-wallpaper').setInputFiles({name:'wallpaper.png',mimeType:'image/png',buffer:picture});const uploaded=await waitPref(p=>p.image?.startsWith('data:image/jpeg'));
const second=await browser.newContext();const other=await second.newPage();await other.goto(base);await other.waitForFunction(()=>document.querySelector('#workspace-wallpaper').src.startsWith('data:image/jpeg'));assert.equal(await other.locator('body').getAttribute('data-theme'),'graphite');await second.close();
const stale=await fetch(base+'/api/appearance',{method:'PATCH',headers:{'content-type':'application/json'},body:JSON.stringify({...uploaded,revision:0})});assert.equal(stale.status,400);
const invalid=await fetch(base+'/api/appearance',{method:'PATCH',headers:{'content-type':'application/json'},body:JSON.stringify({...uploaded,image:'data:image/png;base64,bm90LWEtcG5n'})});assert.equal(invalid.status,400);assert.equal((await preferences()).revision,uploaded.revision);
await page.locator('#custom-wallpaper').setInputFiles({name:'bad.txt',mimeType:'text/plain',buffer:Buffer.from('bad')});await page.locator('#wall-message.error').waitFor();assert.equal((await preferences()).revision,uploaded.revision);
const brightImage=Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4//8/AAX+Av4N70a4AAAAAElFTkSuQmCC','base64');
await page.locator('#custom-wallpaper').setInputFiles({name:'bright.png',mimeType:'image/png',buffer:brightImage});
await waitPref(p=>p.image!==uploaded.image&&p.image?.startsWith('data:image/jpeg'));
await page.locator('#dim').fill('0');await page.locator('#dim').dispatchEvent('input');await waitPref(p=>p.dim===0);
await page.waitForFunction(()=>{const i=document.getElementById('workspace-wallpaper');return i.complete&&i.naturalWidth>0&&i.clientWidth===innerWidth&&i.clientHeight===innerHeight});
await page.screenshot({path:path.join(root,'settings-bright.png')});
await contrast(page,'white-wallpaper-dim0',['.micro','.section-caption span','.reference-local'],false);
await page.locator('#dim').fill('28');await page.locator('#dim').dispatchEvent('input');await waitPref(p=>p.dim===28);
await contrast(page,'white-wallpaper-dim28',['.micro','.section-caption span','.reference-local']);
await page.screenshot({path:path.join(root,'settings-bright-dim28.png')});
await page.getByRole('button',{name:'返回应用总览',exact:true}).click();
await page.screenshot({path:path.join(root,'home-bright.png')});
await contrast(page,'white-wallpaper-home-dim28',['.home-heading p','.home-card-desc']);
await page.locator('#home-app-register').click();
await page.screenshot({path:path.join(root,'registry-bright.png')});
await page.getByRole('button',{name:'返回应用总览',exact:true}).click();
await page.locator('#home-app-settings').click();
await page.locator('#reset-wallpaper').click();await waitPref(p=>p.image===null&&p.dim===14&&p.wallpaper==='B4');
await page.locator('.reference-rail [data-open=register]').click();await page.locator('#serial-no').fill('LIVE-UI-0001');await page.locator('#model-name').fill('验收机型');await page.locator('#owner-name').fill('隔离数据');await page.locator('#register-button').click();await page.locator('#form-message').filter({hasText:'登记成功'}).waitFor();await page.locator('#qr-stage svg').waitFor();assert.equal((await (await fetch(base+'/api/records?q=LIVE-UI-0001')).json()).records.length,1);
const card=page.locator('.archive-card').filter({has:page.getByRole('heading',{name:'LIVE-UI-0001',exact:true})});await card.locator('.archive-more').click();await card.getByRole('button',{name:'编辑资料 / 照片'}).click();await page.locator('#edit-owner').fill('已修改');await page.locator('#edit-save').click();await page.locator('#edit-dialog').waitFor({state:'hidden'});assert.equal((await (await fetch(base+'/api/records?q=LIVE-UI-0001')).json()).records[0].ownerName,'已修改');await page.locator('#new-registration').click();assert.equal(await page.locator('#serial-no').inputValue(),'');
await page.locator('.reference-rail [data-open=register]').click();await page.locator('#serial-no').fill('LIVE-UI-0001');await page.locator('#model-name').fill('验收机型');await page.getByRole('button',{name:'返回应用总览',exact:true}).click();await page.locator('#home-app-settings').click();await page.getByRole('button',{name:'返回应用总览',exact:true}).click();await page.locator('#home-app-register').click();assert.equal(await page.locator('#serial-no').inputValue(),'LIVE-UI-0001');assert.equal(await page.locator('#model-name').inputValue(),'验收机型');await page.locator('#owner-name').fill('隔离数据');await page.locator('#register-button').click();await page.locator('#form-message').filter({hasText:'登记成功'}).waitFor();await page.locator('#qr-stage svg').waitFor();assert.equal((await (await fetch(base+'/api/records?q=LIVE-UI-0001')).json()).records.length,1);
const card=page.locator('.archive-card').filter({has:page.getByRole('heading',{name:'LIVE-UI-0001',exact:true})});await card.locator('.archive-more').click();await card.getByRole('button',{name:'编辑资料 / 照片'}).click();await page.screenshot({path:path.join(root,'edit-dialog.png')});await page.locator('#edit-owner').fill('已修改');await page.locator('#edit-save').click();await page.locator('#edit-dialog').waitFor({state:'hidden'});assert.equal((await (await fetch(base+'/api/records?q=LIVE-UI-0001')).json()).records[0].ownerName,'已修改');await page.screenshot({path:path.join(root,'registry-saved.png')});await page.locator('#new-registration').click();assert.equal(await page.locator('#serial-no').inputValue(),'');
await page.locator('#selection-toggle').click();await page.check('#select-all');const download=page.waitForEvent('download');await page.locator('#export-toggle').click();await page.locator('#export-excel').click();await (await download).saveAs(path.join(root,'records.xlsx'));
await page.screenshot({path:path.join(root,'registry.png')});
await page.locator('.reference-rail [data-open=realtime]').click();await page.waitForURL('**/realtime');await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();assert.equal(await page.locator('.rt-target').count(),0);assert.ok(await page.locator('.maplibregl-canvas').count());
await page.locator('.reference-rail [data-open=realtime]').click();await page.waitForURL('**/realtime');await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();assert.equal(await page.locator('.mc-map-toolstrip').count(),0);await page.waitForFunction(()=>window.ridMap?.metrics().mapReady);assert.equal(await page.evaluate(()=>window.ridMap.metrics().camera.pitch),0);assert.equal(await page.evaluate(()=>window.ridMap.metrics().camera.bearing),0);assert.equal(await page.locator('.rt-target').count(),0);assert.ok(await page.locator('.maplibregl-canvas').count());
const frames=Array.from({length:3},(_,i)=>({target_id:i===0?'LIVE-UI-0001':'LIVE-TARGET-'+i,receiver_id:'TEST',source_epoch:1,sequence:1,longitude:120+i*.001,latitude:30+i*.001,altitude_m:45+i,heading_deg:85}));const response=await fetch(base+'/api/realtime/ingest',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(frames)});assert.equal(response.status,200);await page.locator('.rt-target').filter({hasText:'LIVE-UI-0001'}).click();await page.locator('.rt-details').filter({hasText:'已匹配本地登记档案'}).waitFor();await page.locator('.rt-details').filter({hasText:'120.000000'}).waitFor();
await page.getByTitle('收起目标目录',{exact:true}).click();assert.equal(await page.locator('.live-targets').isVisible(),false);await page.getByTitle('显示目标目录',{exact:true}).click();assert.equal(await page.locator('.live-targets').isVisible(),true);await page.getByRole('button',{name:'接收器与解码',exact:true}).click();await page.locator('.rt-receiver-body').waitFor();await page.getByRole('button',{name:'目标快照与事件',exact:true}).click();
await page.waitForFunction(()=>window.ridMap?.metrics().mapReady&&window.ridMap.metrics().targets===3).catch(async e=>{console.log('MAP_DIAGNOSTIC',await page.evaluate(()=>window.ridMap?.metrics()));await page.screenshot({path:path.join(root,'map-failed.png')});throw e});
@@ -84,8 +187,8 @@ try{
await writeFile(path.join(root,'map-metrics.json'),JSON.stringify(mapMetrics,null,2));
await page.screenshot({path:path.join(root,'realtime-B.png')});
await page.locator('.live-detail a').click();await page.waitForURL('**/?app=register&q=LIVE-UI-0001');await page.locator('#page-status').filter({hasText:'共 1 条'}).waitFor();assert.equal(await page.locator('#history-query').inputValue(),'LIVE-UI-0001');await page.locator('.reference-rail [data-open=realtime]').click();await page.waitForURL('**/realtime');await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();
for(const[width,height]of [[1600,1000],[1366,768],[1080,900],[390,844]]){await page.setViewportSize({width,height});for(const theme of ['graphite','blue','white']){await page.locator('.theme-quick [data-theme='+theme+']').click();await waitPref(p=>p.theme===theme);const box=await page.locator('#workspace-content').boundingBox();assert.equal(Math.round(box.y),48);assert.equal(Math.round(box.x+box.width),width);assert.equal(Math.round(box.y+box.height),height);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);}await page.screenshot({path:path.join(root,`realtime-${width}.png`)});}
for(const[width,height]of [[1600,1000],[1366,768],[1080,900],[390,844]]){await page.setViewportSize({width,height});for(const theme of ['graphite','blue','white']){await setLegacyTheme(page,theme);const box=await page.locator('#workspace-content').boundingBox();assert.equal(Math.round(box.y),48);assert.equal(Math.round(box.x+box.width),width);assert.equal(Math.round(box.y+box.height),height);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);}await page.screenshot({path:path.join(root,`realtime-${width}.png`)});}
await page.setViewportSize({width:1600,height:1000});await page.locator('.reference-rail [data-open=settings]').click();await page.locator('[data-wall=B1]').click();await waitPref(p=>p.wallpaper==='B1');await stop();start();await ready();assert.equal((await preferences()).wallpaper,'B1');await page.reload();await page.waitForFunction(()=>document.getElementById('workspace-wallpaper').src.includes('B1-wallpaper'));
assert.deepEqual(errors,[]);assert.deepEqual(csp,[]);
await writeFile(path.join(root,'report.json'),JSON.stringify({status:'PASS',root,errors,csp,scenarios:['B1 home: three accessible cards, keyboard activation and return focus','home hides navigation and preserves module collapse state','15 home viewport/theme cases','B4 first-use and reset default','real Rust/Wasm','three themes','application DB preferences across independent browser contexts and server restart','custom wallpaper and invalid file rollback','stale settings update rejected','register/edit/QR/XLSX','actual Worker websocket and synthetic ingress','no fabricated empty targets','real local registration matching','overlay collapse','receiver controls','four viewport sizes']},null,2));console.log(JSON.stringify({status:'PASS',root}));
await writeFile(path.join(root,'report.json'),JSON.stringify({status:'PASS',root,errors,csp,contrastCases,workbenchCases,scenarios:['B1 home: three accessible cards, keyboard activation and return focus','shared home navigation preserves menu state and return focus','15 home viewport/theme cases','B4 first-use and reset default','real Rust/Wasm','three legacy values share A+C material','application DB preferences across independent browser contexts and server restart','custom wallpaper and invalid file rollback','stale settings update rejected','register/edit/QR/XLSX','actual Worker websocket and synthetic ingress','no fabricated empty targets','real local registration matching','overlay collapse','receiver controls','four viewport sizes']},null,2));console.log(JSON.stringify({status:'PASS',root}));
}finally{if(browser)await browser.close();await stop();for(const socket of sockets)socket.destroy();await new Promise(r=>proxy.close(r));await writeFile(path.join(root,'server.log'),output);}
+18 -1
View File
@@ -112,7 +112,7 @@ async fn handle(State(worker): State<Worker>, req: Request) -> Response {
Ok(q) => q.0,
Err(_) => return error("查询参数无效".into()),
};
let body = if method == "POST" || method == "PATCH" {
let body = if method == "POST" || method == "PATCH" || method == "PUT" {
match axum::body::to_bytes(req.into_body(), 16 * 1024 * 1024).await {
Ok(b) => {
if path == "/api/archive/retry" && b.is_empty() {
@@ -135,6 +135,23 @@ async fn handle(State(worker): State<Worker>, req: Request) -> Response {
return binary(bytes.to_vec(), mime, None, None);
}
let result=worker.run(move|s|{
if method=="GET"&&path=="/api/target-lists"{
if let Some(known)=params.get("revision") {
let known=known.parse::<u64>().map_err(|_|AppError::Validation("名单版本无效".into()))?;
if crate::target_lists::revision(&s.db)?==known{return Ok(StatusCode::NOT_MODIFIED.into_response())}
}
return Ok(json_response(StatusCode::OK,serde_json::to_value(crate::target_lists::load(&s.db)?).map_err(|e|AppError::Internal(e.to_string()))?));
}
if let Some(id)=path.strip_prefix("/api/target-lists/") {
let snapshot=if method=="PUT"{
let mutation=serde_json::from_value(body).map_err(|_|AppError::Validation("名单类型、备注或版本无效".into()))?;
crate::target_lists::save(&mut s.db,id,mutation)?
}else if method=="DELETE"{
let expected=params.get("revision").and_then(|v|v.parse::<u64>().ok()).ok_or(AppError::Validation("请提供有效的名单版本".into()))?;
crate::target_lists::remove(&mut s.db,id,expected)?
}else{return Err(AppError::NotFound("名单接口不存在"))};
return Ok(json_response(StatusCode::OK,serde_json::to_value(snapshot).map_err(|e|AppError::Internal(e.to_string()))?));
}
if path=="/api/appearance" && (method=="GET" || method=="PATCH") {
let value=if method=="GET" { crate::appearance::load(&s.db)? } else { crate::appearance::save(&mut s.db,body)? };
return Ok(json_response(StatusCode::OK,serde_json::to_value(value).map_err(|e|AppError::Internal(e.to_string()))?));
+1
View File
@@ -6,6 +6,7 @@ mod maps;
mod realtime;
mod receiver;
mod store;
mod target_lists;
mod web_assets {
include!(concat!(env!("OUT_DIR"), "/web_assets.rs"));
}
+1
View File
@@ -133,6 +133,7 @@ impl Store {
std::fs::create_dir_all(root.join("registry/data"))?;
let mut db = Connection::open(root.join("registry/data/registry.sqlite"))?;
db.busy_timeout(std::time::Duration::from_secs(5))?;
crate::target_lists::init(&mut db)?;
db.execute_batch(
"CREATE TABLE IF NOT EXISTS app_settings(key TEXT PRIMARY KEY,value TEXT NOT NULL);",
)?;
+305
View File
@@ -0,0 +1,305 @@
//! SQLite-backed manual lists. Target identity is exact and never inferred from registration.
use crate::error::{AppError, Result};
use rid_shared::target_lists::{
Entry, ListKind, MAX_ENTRIES, MAX_NOTE_CHARS, Mutation, Snapshot, valid_target_id,
};
use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
pub fn init(db: &mut Connection) -> Result<()> {
let tx = db.transaction()?;
tx.execute_batch(
"CREATE TABLE IF NOT EXISTS target_list_entries(
target_id TEXT PRIMARY KEY COLLATE BINARY,
list_kind TEXT NOT NULL CHECK(list_kind IN ('white','black')),
note TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS target_list_state(
id INTEGER PRIMARY KEY CHECK(id=1), revision INTEGER NOT NULL CHECK(revision>=0)
);
INSERT OR IGNORE INTO target_list_state(id,revision) VALUES(1,0);",
)?;
tx.commit()?;
Ok(())
}
pub fn revision(db: &Connection) -> Result<u64> {
let value: i64 = db.query_row(
"SELECT revision FROM target_list_state WHERE id=1",
[],
|row| row.get(0),
)?;
u64::try_from(value).map_err(|_| AppError::Internal("名单版本损坏".into()))
}
pub fn load(db: &Connection) -> Result<Snapshot> {
let mut statement = db.prepare("SELECT target_id,list_kind,note,updated_at FROM target_list_entries ORDER BY target_id COLLATE BINARY")?;
let entries = statement
.query_map([], |row| {
let kind: String = row.get(1)?;
let list_kind = match kind.as_str() {
"white" => ListKind::White,
"black" => ListKind::Black,
_ => return Err(rusqlite::Error::InvalidQuery),
};
Ok(Entry {
target_id: row.get(0)?,
list_kind,
note: row.get(2)?,
updated_at: row.get(3)?,
})
})?
.collect::<rusqlite::Result<Vec<_>>>()?;
Ok(Snapshot {
revision: revision(db)?,
entries,
})
}
fn validate_id(id: &str) -> Result<()> {
if !valid_target_id(id) {
return Err(AppError::Validation(
"目标标识须为 1–64 位字母、数字、短横线或下划线".into(),
));
}
Ok(())
}
fn check_revision(db: &Connection, expected: u64) -> Result<()> {
if revision(db)? != expected {
return Err(AppError::Validation(
"名单已被其他页面修改,请刷新后重试".into(),
));
}
Ok(())
}
pub fn save(db: &mut Connection, id: &str, mutation: Mutation) -> Result<Snapshot> {
validate_id(id)?;
let note = mutation.note.trim();
if note.chars().count() > MAX_NOTE_CHARS {
return Err(AppError::Validation("名单备注最多 200 字".into()));
}
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
check_revision(&tx, mutation.expected_revision)?;
let old: Option<(String, String)> = tx
.query_row(
"SELECT list_kind,note FROM target_list_entries WHERE target_id=?1",
[id],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()?;
let kind = match mutation.list_kind {
ListKind::White => "white",
ListKind::Black => "black",
};
if old.is_none() {
let count: i64 =
tx.query_row("SELECT COUNT(*) FROM target_list_entries", [], |r| r.get(0))?;
if count >= MAX_ENTRIES as i64 {
return Err(AppError::Validation(
"名单已达到 5000 条上限,请先移除不再使用的条目".into(),
));
}
}
if old
.as_ref()
.is_none_or(|(old_kind, old_note)| old_kind != kind || old_note != note)
{
let updated_at = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
tx.execute("INSERT INTO target_list_entries(target_id,list_kind,note,updated_at) VALUES(?1,?2,?3,?4) ON CONFLICT(target_id) DO UPDATE SET list_kind=excluded.list_kind,note=excluded.note,updated_at=excluded.updated_at", params![id,kind,note,updated_at])?;
tx.execute(
"UPDATE target_list_state SET revision=revision+1 WHERE id=1",
[],
)?;
}
let snapshot = load(&tx)?;
tx.commit()?;
Ok(snapshot)
}
pub fn remove(db: &mut Connection, id: &str, expected: u64) -> Result<Snapshot> {
validate_id(id)?;
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
check_revision(&tx, expected)?;
if tx.execute("DELETE FROM target_list_entries WHERE target_id=?1", [id])? > 0 {
tx.execute(
"UPDATE target_list_state SET revision=revision+1 WHERE id=1",
[],
)?;
}
let snapshot = load(&tx)?;
tx.commit()?;
Ok(snapshot)
}
#[cfg(test)]
mod tests {
use super::*;
fn mutation(kind: ListKind, revision: u64) -> Mutation {
Mutation {
list_kind: kind,
note: " 作业备注 ".into(),
expected_revision: revision,
}
}
#[test]
fn exact_membership_is_exclusive_persistent_and_independent() {
let dir = tempfile::tempdir().unwrap();
let mut store = crate::store::Store::open(dir.path().to_owned()).unwrap();
let first = save(&mut store.db, "DRONE-1", mutation(ListKind::Black, 0)).unwrap();
assert_eq!(first.revision, 1);
assert_eq!(first.entries[0].note, "作业备注");
let second = save(&mut store.db, "DRONE-1", mutation(ListKind::White, 1)).unwrap();
assert_eq!(second.entries.len(), 1);
assert_eq!(second.entries[0].list_kind, ListKind::White);
save(&mut store.db, "drone-1", mutation(ListKind::Black, 2)).unwrap();
assert_eq!(store.list("").unwrap().len(), 0);
drop(store);
let mut store = crate::store::Store::open(dir.path().to_owned()).unwrap();
assert_eq!(load(&store.db).unwrap().entries.len(), 2);
assert_eq!(
remove(&mut store.db, "DRONE-1", 3).unwrap().entries[0].target_id,
"drone-1"
);
}
#[test]
fn invalid_stale_and_repeated_updates_do_not_corrupt_state() {
let mut db = Connection::open_in_memory().unwrap();
init(&mut db).unwrap();
save(&mut db, "A", mutation(ListKind::Black, 0)).unwrap();
assert!(save(&mut db, "A", mutation(ListKind::White, 0)).is_err());
assert!(remove(&mut db, "A", 0).is_err());
for id in ["", "A B", "../A", &"A".repeat(65)] {
assert!(save(&mut db, id, mutation(ListKind::White, 1)).is_err());
}
let mut long = mutation(ListKind::White, 1);
long.note = "注".repeat(201);
assert!(save(&mut db, "A", long).is_err());
assert_eq!(
save(&mut db, "A", mutation(ListKind::Black, 1))
.unwrap()
.revision,
1
);
assert_eq!(remove(&mut db, "absent", 1).unwrap().revision, 1);
assert_eq!(remove(&mut db, "A", 1).unwrap().revision, 2);
assert!(load(&db).unwrap().entries.is_empty());
}
#[test]
fn capacity_and_revision_failures_preserve_existing_entries() {
let mut db = Connection::open_in_memory().unwrap();
init(&mut db).unwrap();
let tx = db.transaction().unwrap();
for index in 0..MAX_ENTRIES {
tx.execute(
"INSERT INTO target_list_entries VALUES(?1,'white','','time')",
[format!("ID-{index}")],
)
.unwrap();
}
tx.commit().unwrap();
assert!(save(&mut db, "ONE-MORE", mutation(ListKind::Black, 0)).is_err());
assert_eq!(
save(&mut db, "ID-0", mutation(ListKind::Black, 0))
.unwrap()
.revision,
1
);
db.execute_batch("CREATE TRIGGER fail_list_revision BEFORE UPDATE ON target_list_state BEGIN SELECT RAISE(ABORT,'test failure'); END;").unwrap();
assert!(save(&mut db, "ID-0", mutation(ListKind::White, 1)).is_err());
let snapshot = load(&db).unwrap();
assert_eq!(snapshot.revision, 1);
assert_eq!(
snapshot
.entries
.iter()
.find(|e| e.target_id == "ID-0")
.unwrap()
.list_kind,
ListKind::Black
);
assert_eq!(snapshot.entries.len(), MAX_ENTRIES);
}
#[tokio::test]
async fn http_crud_conditional_read_validation_and_origin_checks() {
use axum::{body::Body, http::Request};
use tower::ServiceExt;
let dir = tempfile::tempdir().unwrap();
let mut store = crate::store::Store::open(dir.path().to_owned()).unwrap();
let (tx, mut rx) = tokio::sync::mpsc::channel::<crate::Job>(16);
std::thread::spawn(move || {
while let Some(job) = rx.blocking_recv() {
match job {
crate::Job::Execute(job) => job(&mut store),
crate::Job::Shutdown => break,
}
}
});
let app = crate::http::router(crate::Worker(tx));
let body = serde_json::json!({"list_kind":"black","note":"关注","expected_revision":0});
let response = app
.clone()
.oneshot(
Request::builder()
.method("PUT")
.uri("/api/target-lists/HTTP_001")
.body(Body::from(body.to_string()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), 200);
let value: serde_json::Value = serde_json::from_slice(
&axum::body::to_bytes(response.into_body(), 65536)
.await
.unwrap(),
)
.unwrap();
assert_eq!(value["revision"], 1);
assert_eq!(value["entries"][0]["target_id"], "HTTP_001");
let body_text = body.to_string();
for (method, url, origin, payload, expected) in [
("GET", "/api/target-lists?revision=1", None, "", 304),
("GET", "/api/target-lists?revision=bad", None, "", 400),
(
"PUT",
"/api/target-lists/HTTP_001",
None,
body_text.as_str(),
400,
),
(
"PUT",
"/api/target-lists/HTTP_002",
Some("https://example.com"),
body_text.as_str(),
403,
),
("PUT", "/api/target-lists/HTTP_002", None, "not JSON", 400),
("DELETE", "/api/target-lists/HTTP_001", None, "", 400),
(
"DELETE",
"/api/target-lists/HTTP_001?revision=1",
None,
"",
200,
),
] {
let mut builder = Request::builder().method(method).uri(url);
if let Some(origin) = origin {
builder = builder.header("origin", origin)
}
let response = app
.clone()
.oneshot(builder.body(Body::from(payload.to_owned())).unwrap())
.await
.unwrap();
assert_eq!(response.status().as_u16(), expected, "{method} {url}");
}
}
}