```
feat(geofences): 新增地理围栏模块并优化地图瓦片缓存 在 rid-shared 中实现二维 WGS84 地理围栏核心逻辑,支持圆形与多边形 两种几何体,包含坐标合法性校验、边界包含判断及自相交检测。 realtime-core 的 Store 新增观察者回调,在观测数据接受后按到达顺序 通知监听器。 前端方面,新增 geofence-map-adapter.js 提供基于 MapLibre 的围栏绘制 与编辑能力,配套 geofences.css 完成响应式布局样式。map-loader.js 增加懒加载入口,仅在实时工作区按需引入围栏地图模块。 同时引入 map-tile-buffer 瓦片缓冲机制,改善地图切换与刷新时的加载 体验;将默认缩放级别从 11 调整为 15,使初始视图更贴近实际监测场景。 ```
This commit is contained in:
@@ -2,6 +2,8 @@
|
||||
use rid_shared::{Frame, Metrics, Observation, PROTOCOL_VERSION, Target};
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
|
||||
type ObservationListener = Box<dyn Fn(&Observation, u64) + Send + Sync>;
|
||||
|
||||
struct Track {
|
||||
target: Target,
|
||||
sources: HashMap<String, (u64, u64)>,
|
||||
@@ -9,6 +11,7 @@ struct Track {
|
||||
|
||||
pub struct Store {
|
||||
tracks: HashMap<String, Track>,
|
||||
observer: Option<ObservationListener>,
|
||||
changes: VecDeque<(u64, String)>,
|
||||
journal_capacity: usize,
|
||||
epoch: u64,
|
||||
@@ -21,6 +24,7 @@ impl Store {
|
||||
assert!(capacity > 0 && journal_capacity > 0 && ttl_ms > 0);
|
||||
Self {
|
||||
tracks: HashMap::new(),
|
||||
observer: None,
|
||||
changes: VecDeque::new(),
|
||||
journal_capacity,
|
||||
epoch,
|
||||
@@ -32,6 +36,11 @@ impl Store {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs after acceptance, in arrival order. The listener must never block.
|
||||
pub fn observe(&mut self, listener: impl Fn(&Observation, u64) + Send + Sync + 'static) {
|
||||
self.observer = Some(Box::new(listener));
|
||||
}
|
||||
|
||||
fn changed(&mut self, id: String) {
|
||||
self.metrics.sequence += 1;
|
||||
if self.changes.len() == self.journal_capacity {
|
||||
@@ -87,6 +96,9 @@ impl Store {
|
||||
},
|
||||
);
|
||||
}
|
||||
if let Some(observer) = &self.observer {
|
||||
observer(&self.tracks[&id].target.observation, now_ms);
|
||||
}
|
||||
self.metrics.accepted += 1;
|
||||
self.changed(id);
|
||||
true
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
//! Two-dimensional WGS84 monitoring areas. No flight-control semantics.
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum Geometry {
|
||||
Circle { center: [f64; 2], radius_m: f64 },
|
||||
Polygon { vertices: Vec<[f64; 2]> },
|
||||
}
|
||||
fn coordinate(p: &[f64; 2]) -> bool {
|
||||
p[0].is_finite()
|
||||
&& p[1].is_finite()
|
||||
&& (-180.0..=180.0).contains(&p[0])
|
||||
&& (-90.0..=90.0).contains(&p[1])
|
||||
}
|
||||
fn cross(a: [f64; 2], b: [f64; 2], c: [f64; 2]) -> f64 {
|
||||
(b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
|
||||
}
|
||||
fn segment(a: [f64; 2], b: [f64; 2], p: [f64; 2]) -> bool {
|
||||
cross(a, b, p).abs() <= 1e-10
|
||||
&& p[0] >= a[0].min(b[0]) - 1e-10
|
||||
&& p[0] <= a[0].max(b[0]) + 1e-10
|
||||
&& p[1] >= a[1].min(b[1]) - 1e-10
|
||||
&& p[1] <= a[1].max(b[1]) + 1e-10
|
||||
}
|
||||
fn intersects(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> bool {
|
||||
segment(a, b, c)
|
||||
|| segment(a, b, d)
|
||||
|| segment(c, d, a)
|
||||
|| segment(c, d, b)
|
||||
|| (cross(a, b, c) * cross(a, b, d) < 0.0 && cross(c, d, a) * cross(c, d, b) < 0.0)
|
||||
}
|
||||
impl Geometry {
|
||||
pub fn valid(&self) -> bool {
|
||||
match self {
|
||||
Self::Circle { center, radius_m } => {
|
||||
coordinate(center) && radius_m.is_finite() && (1.0..=1_000_000.0).contains(radius_m)
|
||||
}
|
||||
Self::Polygon { vertices: v } => {
|
||||
if !(3..=128).contains(&v.len()) || !v.iter().all(coordinate) {
|
||||
return false;
|
||||
}
|
||||
let min = v.iter().map(|p| p[0]).fold(f64::INFINITY, f64::min);
|
||||
let max = v.iter().map(|p| p[0]).fold(f64::NEG_INFINITY, f64::max);
|
||||
// Reject ambiguous dateline polygons rather than drawing the opposite hemisphere.
|
||||
if max - min >= 180.0 {
|
||||
return false;
|
||||
}
|
||||
let mut area = 0.0;
|
||||
for i in 0..v.len() {
|
||||
let j = (i + 1) % v.len();
|
||||
if v[i] == v[j] {
|
||||
return false;
|
||||
}
|
||||
area += v[i][0] * v[j][1] - v[j][0] * v[i][1];
|
||||
for k in i + 1..v.len() {
|
||||
let l = (k + 1) % v.len();
|
||||
if j != k && l != i && intersects(v[i], v[j], v[k], v[l]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
area.abs() > 1e-10
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Boundaries are inside. Invalid coordinates never match.
|
||||
pub fn contains(&self, point: [f64; 2]) -> bool {
|
||||
if !coordinate(&point) {
|
||||
return false;
|
||||
}
|
||||
match self {
|
||||
Self::Circle { center, radius_m } => {
|
||||
let a = center[1].to_radians();
|
||||
let b = point[1].to_radians();
|
||||
let h = ((b - a) / 2.0).sin().powi(2)
|
||||
+ a.cos() * b.cos() * ((point[0] - center[0]).to_radians() / 2.0).sin().powi(2);
|
||||
6_371_008.8 * 2.0 * h.clamp(0.0, 1.0).sqrt().asin() <= *radius_m + 1e-6
|
||||
}
|
||||
Self::Polygon { vertices: v } => {
|
||||
let mut inside = false;
|
||||
for i in 0..v.len() {
|
||||
let a = v[i];
|
||||
let b = v[(i + 1) % v.len()];
|
||||
if segment(a, b, point) {
|
||||
return true;
|
||||
}
|
||||
if (a[1] > point[1]) != (b[1] > point[1])
|
||||
&& point[0] < (b[0] - a[0]) * (point[1] - a[1]) / (b[1] - a[1]) + a[0]
|
||||
{
|
||||
inside = !inside;
|
||||
}
|
||||
}
|
||||
inside
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Fence {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub enabled: bool,
|
||||
pub geometry: Geometry,
|
||||
}
|
||||
impl Fence {
|
||||
pub fn valid(&self) -> bool {
|
||||
crate::target_lists::valid_target_id(&self.id)
|
||||
&& !self.name.trim().is_empty()
|
||||
&& self.name.chars().count() <= 40
|
||||
&& !self.name.chars().any(char::is_control)
|
||||
&& self.geometry.valid()
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct Snapshot {
|
||||
pub revision: u64,
|
||||
pub entries: Vec<Fence>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Mutation {
|
||||
pub fence: Fence,
|
||||
pub expected_revision: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Alert {
|
||||
pub id: u64,
|
||||
pub occurred_at_ms: u64,
|
||||
pub event_type: String,
|
||||
pub target_id: String,
|
||||
pub fence_id: Option<String>,
|
||||
pub fence_name: Option<String>,
|
||||
pub longitude: f64,
|
||||
pub latitude: f64,
|
||||
pub list_kind: String,
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn circle_uses_metres_and_handles_dateline() {
|
||||
let g = Geometry::Circle {
|
||||
center: [179.999, 0.0],
|
||||
radius_m: 300.0,
|
||||
};
|
||||
assert!(g.valid());
|
||||
assert!(g.contains([-179.999, 0.0]));
|
||||
assert!(!g.contains([179.99, 0.0]));
|
||||
assert!(!g.contains([f64::NAN, 0.0]));
|
||||
}
|
||||
#[test]
|
||||
fn polygon_boundary_concavity_and_validation() {
|
||||
let g = Geometry::Polygon {
|
||||
vertices: vec![[0.0, 0.0], [2.0, 0.0], [1.0, 1.0], [2.0, 2.0], [0.0, 2.0]],
|
||||
};
|
||||
assert!(g.valid());
|
||||
assert!(g.contains([0.0, 1.0]));
|
||||
assert!(g.contains([0.5, 1.0]));
|
||||
assert!(!g.contains([1.8, 1.0]));
|
||||
for vertices in [
|
||||
vec![[0.0, 0.0]; 3],
|
||||
vec![[0.0, 0.0], [2.0, 2.0], [0.0, 2.0], [2.0, 0.0]],
|
||||
vec![[179.0, 0.0], [-179.0, 0.0], [179.0, 1.0]],
|
||||
] {
|
||||
assert!(!Geometry::Polygon { vertices }.valid());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Versioned synthetic telemetry contract. This is not a device wire protocol.
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub mod geofences;
|
||||
pub mod map_settings;
|
||||
pub mod target_lists;
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ impl Default for Preferences {
|
||||
basemap: "imagery".into(),
|
||||
longitude: 120.1538,
|
||||
latitude: 30.2874,
|
||||
zoom: 11.0,
|
||||
zoom: 15.0,
|
||||
regions: vec![],
|
||||
revision: 0,
|
||||
}
|
||||
|
||||
@@ -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="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"><link data-trunk rel="copy-file" href="public/map-settings.css"><link rel="stylesheet" href="/map-settings.css"><link data-trunk rel="copy-file" href="public/map-settings-adapter.js"></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"><link data-trunk rel="copy-file" href="public/map-settings.css"><link rel="stylesheet" href="/map-settings.css"><link data-trunk rel="copy-file" href="public/map-settings-adapter.js"><link data-trunk rel="copy-file" href="public/map-tile-buffer.js"><link data-trunk rel="copy-file" href="public/geofences.css"><link rel="stylesheet" href="/geofences.css"><link data-trunk rel="copy-file" href="public/geofence-map-adapter.js"></head><body></body></html>
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
// MapLibre drawing only. Persistence, validation and monitoring remain in Rust.
|
||||
import * as ml from './vendor/maplibre-gl.mjs';
|
||||
import {attachTileBuffer} from './map-tile-buffer.js';
|
||||
ml.setWorkerUrl('/vendor/maplibre-gl-worker.mjs');
|
||||
let map,buffer,observer,markers=[],data={entries:[],draft:null},mode='',vertices=[],kind='imagery',renderedDraft=null,latestTargets=[];
|
||||
const layers={imagery:['img_w','cia_w'],road:['vec_w','cva_w']};
|
||||
const url=i=>`/api/maps/tile/${layers[kind][i]}/{z}/{x}/{y}`;
|
||||
const emit=(type,detail)=>window.dispatchEvent(new CustomEvent(type,{detail}));
|
||||
function ring(g){if(g.type==='polygon')return [...g.vertices,g.vertices[0]];
|
||||
const [lon,lat]=g.center,delta=g.radius_m/6371008.8,a=lat*Math.PI/180,b=lon*Math.PI/180,points=[];
|
||||
for(let i=0;i<=96;i++){const bearing=i/96*2*Math.PI,p=Math.asin(Math.sin(a)*Math.cos(delta)+Math.cos(a)*Math.sin(delta)*Math.cos(bearing));const q=b+Math.atan2(Math.sin(bearing)*Math.sin(delta)*Math.cos(a),Math.cos(delta)-Math.sin(a)*Math.sin(p));points.push([q*180/Math.PI,p*180/Math.PI]);}return points;
|
||||
}
|
||||
function feature(f,draft=false){return {type:'Feature',properties:{id:f.id,enabled:f.enabled,draft},geometry:{type:'Polygon',coordinates:[ring(f.geometry)]}};}
|
||||
function handles(){for(const m of markers)m.remove();markers=[];if(!map||mode||!data.draft)return;
|
||||
const g=data.draft.geometry,points=g.type==='circle'?[g.center]:g.vertices;
|
||||
points.forEach((point,index)=>{const element=document.createElement('div');element.className='gf-handle';element.setAttribute('aria-label',g.type==='circle'?'拖动围栏圆心':`拖动围栏顶点 ${index+1}`);const marker=new ml.Marker({element,draggable:true}).setLngLat(point).addTo(map);marker.on('dragend',()=>{const p=marker.getLngLat(),geometry=structuredClone(g);marker.setLngLat(point);if(g.type==='circle')geometry.center=[p.lng,p.lat];else geometry.vertices[index]=[p.lng,p.lat];emit('rid-fence-geometry',geometry);});markers.push(marker);});
|
||||
}
|
||||
export function render(value){data=value||data;if(!map?.getSource('fences'))return;
|
||||
const features=data.entries.filter(f=>f.id!==data.draft?.id).map(f=>feature(f));if(data.draft)features.push(feature(data.draft,true));
|
||||
map.getSource('fences').setData({type:'FeatureCollection',features});const key=JSON.stringify([data.draft?.id,data.draft?.geometry]);if(key!==renderedDraft){renderedDraft=key;handles();}
|
||||
}
|
||||
export function targets(items){latestTargets=items||[];map?.getSource('targets')?.setData({type:'FeatureCollection',features:latestTargets.map(t=>({type:'Feature',properties:t,geometry:{type:'Point',coordinates:[t.longitude,t.latitude]}}))});}
|
||||
export function open(p){if(map){map.resize();return;}kind=p.basemap==='road'?'road':'imagery';
|
||||
try{map=new ml.Map({container:'geofence-map',center:[p.longitude,p.latitude],zoom:p.zoom??15,pitch:0,bearing:0,maxZoom:18,maxTileCacheSize:1024,style:{version:8,sources:{base:{type:'raster',tiles:[url(0)],tileSize:256,maxzoom:18},labels:{type:'raster',tiles:[url(1)],tileSize:256,maxzoom:18},targets:{type:'geojson',data:{type:'FeatureCollection',features:[]}},fences:{type:'geojson',data:{type:'FeatureCollection',features:[]}}},layers:[{id:'background',type:'background',paint:{'background-color':'#020b18'}},{id:'base',type:'raster',source:'base'},{id:'labels',type:'raster',source:'labels'},{id:'fence-fill',type:'fill',source:'fences',paint:{'fill-color':['case',['get','enabled'],'#5ba6ed','#8192a5'],'fill-opacity':['case',['get','draft'],.22,.10]}},{id:'fence-line',type:'line',source:'fences',paint:{'line-color':['case',['get','draft'],'#c5e3ff',['get','enabled'],'#7ec6ff','#8192a5'],'line-width':['case',['get','draft'],2.5,1.5]}},{id:'target-dots',type:'circle',source:'targets',paint:{'circle-radius':6,'circle-color':['match',['get','list_kind'],'white','#83dcb9','black','#ff938b','#91c9ff'],'circle-stroke-color':'#020b18','circle-stroke-width':2}}]}});
|
||||
buffer=attachTileBuffer(map,()=>kind);observer=new ResizeObserver(()=>map?.resize());observer.observe(document.getElementById('geofence-map'));map.addControl(new ml.NavigationControl({showCompass:false}),'bottom-left');map.addControl(new ml.AttributionControl({customAttribution:'天地图 © 自然资源部 · 本地监测围栏',compact:true}),'bottom-right');
|
||||
map.on('load',()=>{render(data);targets(latestTargets);});map.on('error',e=>{if(!['base','labels'].includes(e.sourceId))emit('rid-fence-map-error',{message:'围栏地图操作失败,请使用坐标编辑并检查 WebGL。'});});
|
||||
map.on('click',e=>{if(mode==='circle'){const radius=data.draft?.geometry?.radius_m||500;emit('rid-fence-geometry',{type:'circle',center:[e.lngLat.lng,e.lngLat.lat],radius_m:radius});tool('');}
|
||||
else if(mode==='polygon'){vertices.push([e.lngLat.lng,e.lngLat.lat]);map.getSource('drawing').setData({type:'Feature',properties:{},geometry:{type:'LineString',coordinates:vertices.length>1?vertices:[vertices[0],vertices[0]]}});emit('rid-fence-progress',{count:vertices.length});}
|
||||
else{const target=map.queryRenderedFeatures(e.point,{layers:['target-dots']})[0];if(target){const t=target.properties;new ml.Popup().setLngLat(e.lngLat).setText(`${t.target_id} · ${t.list_kind==='white'?'白名单(免告警)':t.list_kind==='black'?'黑名单':'未分类'} · ${t.inside||'区域外'}`).addTo(map);return;}const f=map.queryRenderedFeatures(e.point,{layers:['fence-fill']})[0];if(f)emit('rid-fence-select',{id:f.properties.id});}});
|
||||
map.on('load',()=>{map.addSource('drawing',{type:'geojson',data:{type:'FeatureCollection',features:[]}});map.addLayer({id:'drawing',type:'line',source:'drawing',paint:{'line-color':'#b6dbff','line-width':2,'line-dasharray':[2,2]}});});
|
||||
map.getCanvas().addEventListener('keydown',e=>{if(e.key==='Escape'){tool('');emit('rid-fence-progress',{cancelled:true});}});
|
||||
}catch{close();emit('rid-fence-map-error',{message:'无法创建地图;仍可通过坐标编辑围栏。'});}
|
||||
}
|
||||
export function tool(value){if(!map)return;if(value==='finish'){if(vertices.length<3){emit('rid-fence-map-error',{message:'多边形至少需要3个顶点'});return;}emit('rid-fence-geometry',{type:'polygon',vertices:[...vertices]});value='';}
|
||||
mode=value;vertices=[];map.getCanvas().style.cursor=mode?'crosshair':'';
|
||||
map.getSource('drawing')?.setData({type:'FeatureCollection',features:[]});handles();if(mode)map.getCanvas().focus();emit('rid-fence-mode',{mode});
|
||||
}
|
||||
export function locate(){if(!map||!data.draft)return;const points=ring(data.draft.geometry),bounds=new ml.LngLatBounds();for(const p of points)bounds.extend(p);const narrow=map.getCanvas().clientWidth<900;map.fitBounds(bounds,{padding:{top:160,bottom:70,left:50,right:narrow?50:400},maxZoom:17,duration:400});}
|
||||
export function setBasemap(value){const next=value==='road'?'road':'imagery';if(next===kind||!map)return;kind=next;for(const [i,id]of ['base','labels'].entries())map.getSource(id)?.setTiles([url(i)]);buffer?.schedule();}
|
||||
export function metrics(){return map?{camera:{zoom:map.getZoom(),pitch:map.getPitch(),bearing:map.getBearing()},ready:map.loaded(),mode,buffer:buffer?.metrics()}:null;}
|
||||
export function close(){buffer?.destroy();buffer=null;observer?.disconnect();observer=null;for(const m of markers)m.remove();markers=[];map?.remove();map=null;mode='';vertices=[];renderedDraft=null;}
|
||||
@@ -0,0 +1,4 @@
|
||||
#geofence-view{background:#020b18;backdrop-filter:none;overflow:hidden}[hidden]{display:none!important}.gf-stage{position:relative;height:100%;min-height:480px}.gf-stage #geofence-map{position:absolute;inset:0}.gf-heading{position:absolute;left:24px;top:22px;right:405px;pointer-events:none}.gf-heading{padding:14px 16px;border-radius:12px;max-width:600px;background:linear-gradient(90deg,#061221ed,#061221bb)}.gf-heading h1{font-size:23px;margin:0 0 8px}.gf-heading p{font-size:12px;color:#b5c6d9;line-height:1.7}.gf-tools{display:flex;flex-wrap:wrap;gap:7px;pointer-events:auto;margin-top:16px}.gf-tools button{background:rgba(6,18,33,.85);font-size:12px}.gf-drawer{position:absolute;right:20px;top:20px;bottom:45px;width:350px;display:flex;flex-direction:column;overflow:hidden;border:1px solid rgba(179,213,255,.32);border-radius:14px;background:rgba(6,18,33,.40);backdrop-filter:blur(7px) brightness(.55);box-shadow:0 16px 45px #0005}.gf-drawer-heading{display:flex;align-items:center;justify-content:space-between;padding:16px 18px;border-bottom:1px solid #b3d5ff32}.gf-drawer h2{font-size:17px;margin:0}.gf-scroll{padding:0 18px 18px;overflow:auto;flex:1;min-height:0;scrollbar-width:thin}.gf-section-title{display:flex;align-items:center;justify-content:space-between;margin:20px 0 12px;color:#b5c6d9;font-size:12px}.gf-section-title button{padding:5px 9px;font-size:11px}.gf-section-title h3{font-size:13px;margin:0}.gf-entry{display:flex;width:100%;align-items:center;justify-content:space-between;text-align:left;gap:12px;margin:8px 0;padding:13px;background:rgba(2,11,24,.6);font-size:13px}.gf-entry small{font-size:10px;color:#b5c6d9;white-space:nowrap}.gf-entry[aria-pressed=true]{border-color:#94caff;background:#245d9d40}.gf-entry span{overflow-wrap:anywhere}#gf-list{max-height:220px;overflow:auto}.gf-drawer label{display:block;font-size:12px;color:#b5c6d9;margin:14px 0 7px}.gf-drawer :is(input:not([type=checkbox]),select,textarea){width:100%;min-width:0;padding:10px;background:rgba(2,11,24,.72);border:1px solid #b3d5ff45;border-radius:7px;color:#e9f0fa;font:inherit;font-size:12px;box-sizing:border-box}.gf-drawer input[type=checkbox]{width:auto;margin-right:8px}.gf-drawer select option{background:#061221}.gf-drawer textarea{resize:vertical}.gf-field-row{display:grid;grid-template-columns:1fr 1fr;gap:12px}.gf-field-row input{margin-top:7px}.gf-explain,#gf-vertices-help{font-size:11px;line-height:1.8;color:#b5c6d9}.gf-editor-actions{display:flex;gap:8px;position:sticky;bottom:-18px;background:#061221ee;padding:12px 0;z-index:1}.gf-editor-actions button{font-size:12px;padding:9px 12px}.gf-editor-actions .primary{flex:1;background:#245d9d}.gf-footer{padding:10px 18px;background:#061221d9;border-top:1px solid #b3d5ff32}.gf-footer p{margin:0;line-height:1.8;font-size:12px;color:#b5c6d9}.gf-footer p[data-error=true]{color:#ffb8b1}#gf-events{padding:0;list-style:none;margin:0}#gf-events li{padding:12px 0;border-bottom:1px solid #b3d5ff25;font-size:12px;line-height:1.8;overflow-wrap:anywhere}#gf-events time{display:block;color:#b5c6d9;font-size:10px}.gf-map-status{position:absolute;bottom:8px;left:16px;right:16px;margin:0;pointer-events:none;font-size:11px;color:#b5c6d9;background:#061221c9;padding:7px 12px;border-radius:7px;width:fit-content;max-width:calc(100% - 32px)}.gf-stage .maplibregl-ctrl-group{background:#061221d9;border:1px solid #b3d5ff52}.gf-stage .maplibregl-ctrl-icon{filter:invert(1)}.gf-stage .maplibregl-ctrl-attrib{background:#061221d9;color:#b5c6d9}.gf-stage .maplibregl-ctrl-attrib a{color:#b5c6d9}.gf-handle{width:14px;height:14px;border-radius:50%;border:2px solid #e9f0fa;background:#245d9d;cursor:grab}.gf-stage button:focus-visible,.gf-stage input:focus-visible,.gf-stage textarea:focus-visible,.gf-stage select:focus-visible{outline:2px solid #9cceff;outline-offset:3px}.gf-stage button:disabled{opacity:.45;cursor:not-allowed}@supports not (backdrop-filter:blur(7px)){.gf-drawer{background:#061221f5}}@media(max-width:1000px){.gf-drawer{width:320px;right:14px}.gf-heading{right:355px;left:18px}.gf-heading h1{font-size:20px}}@media(max-width:767px),(max-height:570px){#geofence-view{overflow:auto}.gf-stage{height:auto;min-height:100%;padding-top:390px}.gf-stage #geofence-map{height:390px;bottom:auto}.gf-heading{top:18px;left:16px;right:16px}.gf-heading h1{font-size:19px}.gf-heading>p{max-width:100%;font-size:11px}.gf-tools{gap:5px;margin-top:12px}.gf-tools button{font-size:11px;padding:7px 9px}.gf-drawer{position:relative;inset:auto;width:auto;margin:14px;max-height:none;background:rgba(6,18,33,.7)}.gf-scroll{overflow:visible}.gf-map-status{position:relative;bottom:auto;left:auto;margin:14px;width:auto;max-width:none}.gf-editor-actions{position:static;background:none}.gf-stage .maplibregl-ctrl-bottom-right{bottom:auto;top:355px}.gf-field-row{gap:10px}}
|
||||
.gf-stage .maplibregl-popup-content{background:#061221;color:#e9f0fa;border:1px solid #b3d5ff52;padding:16px 28px 16px 16px;line-height:1.8;max-width:280px}.gf-stage .maplibregl-popup-close-button{color:#e9f0fa}.gf-stage .maplibregl-popup-tip{border-top-color:#061221}
|
||||
|
||||
.gf-drawer .gf-switch{display:flex;align-items:center;gap:8px}.gf-drawer .gf-switch input{margin:0;flex:0 0 auto}
|
||||
@@ -1,13 +1,15 @@
|
||||
// MapLibre/WebGL interoperability only. Telemetry decoding and UI state are Rust.
|
||||
import {attachTileBuffer} from './map-tile-buffer.js';
|
||||
import * as maplibre from './vendor/maplibre-gl.mjs';
|
||||
maplibre.setWorkerUrl('/vendor/maplibre-gl-worker.mjs');
|
||||
let tileBuffer;
|
||||
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="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}`;}
|
||||
function tileUrl(index){return `/api/maps/tile/${basemapLayers[basemap][index]}/{z}/{x}/{y}${tileRevision?`?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;}
|
||||
@@ -19,10 +21,13 @@ function shader(gl, type, source) {
|
||||
}
|
||||
function create(container,initialBasemap="imagery",preferences=null) {
|
||||
basemap=initialBasemap==="road"?"road":"imagery";mapCreations++;
|
||||
tileBuffer?.destroy();
|
||||
if (map) map.remove();
|
||||
const initialCenter=preferences&&Number.isFinite(preferences.longitude)&&Number.isFinite(preferences.latitude)?[preferences.longitude,preferences.latitude]:[120.1538,30.2874];
|
||||
const initialZoom=Number.isFinite(preferences?.zoom)?Math.max(0,Math.min(18,preferences.zoom)):11;
|
||||
map=new maplibre.Map({container,center:initialCenter,zoom:initialZoom,pitch:0,bearing:0,attributionControl:false,
|
||||
// A configured startup camera takes precedence over the legacy first-target fallback.
|
||||
centered=!!(preferences&&Number.isFinite(preferences.longitude)&&Number.isFinite(preferences.latitude));
|
||||
const initialZoom=Number.isFinite(preferences?.zoom)?Math.max(0,Math.min(18,preferences.zoom)):15;
|
||||
map=new maplibre.Map({container,center:initialCenter,zoom:initialZoom,pitch:0,bearing:0,maxZoom:18,maxTileCacheSize:1024,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}
|
||||
@@ -31,6 +36,7 @@ function create(container,initialBasemap="imagery",preferences=null) {
|
||||
{id:'tdt-base',type:'raster',source:'tdt-base'},
|
||||
{id:'tdt-labels',type:'raster',source:'tdt-labels'}
|
||||
]}});
|
||||
tileBuffer=attachTileBuffer(map,()=>basemap,()=>tileRevision);
|
||||
resizeObserver?.disconnect(); resizeObserver=new ResizeObserver(()=>map?.resize());resizeObserver.observe(document.getElementById(container));
|
||||
map.addControl(new maplibre.AttributionControl({compact:true}),'bottom-right');
|
||||
layer={id:'rid-targets',type:'custom',renderingMode:'2d',
|
||||
@@ -109,10 +115,10 @@ function flush(){
|
||||
}
|
||||
function update(positions,newIds){latest=positions;if(newIds)ids=Array.from(newIds);if(!centered&&latest.length>=4){centered=true;focusCoordinate([latest[0],latest[1]], false);}if(!pending){pending=true;requestAnimationFrame(flush);}}
|
||||
function select(id){if(selected!==id){selected=id;history=[];flush();}const i=ids.indexOf(id);return i>=0&&latest?Array.from(latest.slice(i*4,i*4+4)):[];}
|
||||
function metrics(){const sorted=[...frameTimes].sort((a,b)=>a-b);const gl=layer?.gl;const ext=gl?.getExtension('WEBGL_debug_renderer_info');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 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 {tileBuffer:tileBuffer?.metrics(),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==='road'?'road':'imagery';if(next!==basemap){basemap=next;refresh();}}
|
||||
function refresh(){tileRevision++;tileBuffer?.schedule();for(const [i,id]of ['tdt-base','tdt-labels'].entries())map?.getSource(id)?.setTiles([tileUrl(i)]);}
|
||||
function setBasemap(value){const next=value==='road'?'road':'imagery';if(next!==basemap){basemap=next;for(const [i,id]of ['tdt-base','tdt-labels'].entries())map?.getSource(id)?.setTiles([tileUrl(i)]);tileBuffer?.schedule();}}
|
||||
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]));
|
||||
@@ -138,4 +144,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,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};}};
|
||||
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(){tileBuffer?.destroy();tileBuffer=null;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};}};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Load the map engine only for the approved realtime workspace.
|
||||
if (location.pathname === '/realtime') await import('./map-adapter.js');
|
||||
|
||||
// A separate, lazy map keeps configuration independent of the live receiver map.
|
||||
let settings, generation=0;
|
||||
window.ridMapSettings={
|
||||
@@ -8,3 +8,11 @@ window.ridMapSettings={
|
||||
configure(p){settings?.configure(p);},setBasemap(v){settings?.setBasemap(v);},
|
||||
tool(v){settings?.tool(v);},bounds(v){settings?.bounds(v);},current(){settings?.current();},metrics(){return settings?.metrics();}
|
||||
};
|
||||
|
||||
let fences,fenceGeneration=0;
|
||||
window.ridGeofences={
|
||||
async open(p){const token=++fenceGeneration;try{fences??=await import('./geofence-map-adapter.js');if(token===fenceGeneration){fences.open(p);window.dispatchEvent(new Event('rid-fence-map-ready'));}}catch{window.dispatchEvent(new CustomEvent('rid-fence-map-error',{detail:{message:'围栏地图模块加载失败,可继续使用坐标编辑。'}}));}},
|
||||
close(){fenceGeneration++;fences?.close();},render(p){fences?.render(p);},targets(p){fences?.targets(p);},tool(v){fences?.tool(v);},locate(){fences?.locate();},setBasemap(v){fences?.setBasemap(v);},metrics(){return fences?.metrics();}
|
||||
};
|
||||
|
||||
if (location.pathname === '/realtime') await import('./map-adapter.js');
|
||||
|
||||
@@ -1,19 +1,25 @@
|
||||
import {attachTileBuffer} from './map-tile-buffer.js';
|
||||
// MapLibre interop only. Preferences, download state and API requests live in Rust.
|
||||
import * as ml from './vendor/maplibre-gl.mjs';
|
||||
ml.setWorkerUrl('/vendor/maplibre-gl-worker.mjs');
|
||||
let tileBuffer;
|
||||
let map,kind='imagery',mode='',marker,observer,start,box,boxElement,revision=0;
|
||||
const pairs={imagery:['img_w','cia_w'],road:['vec_w','cva_w']};
|
||||
function urls(i){return `/api/maps/tile/${pairs[kind][i]}/{z}/{x}/{y}?v=${revision}`;}
|
||||
function urls(i){return `/api/maps/tile/${pairs[kind][i]}/{z}/{x}/{y}${revision?`?v=${revision}`:''}`;}
|
||||
function emit(type,detail){window.dispatchEvent(new CustomEvent(type,{detail}));}
|
||||
export function open(p){
|
||||
if(map){configure(p);map.resize();return;}
|
||||
kind=p.basemap==='road'?'road':'imagery';
|
||||
try{
|
||||
map=new ml.Map({container:'settings-map',center:[p.longitude,p.latitude],zoom:p.zoom,pitch:0,bearing:0,maxZoom:18,style:{version:8,sources:{base:{type:'raster',tiles:[urls(0)],tileSize:256,maxzoom:18},labels:{type:'raster',tiles:[urls(1)],tileSize:256,maxzoom:18}},layers:[{id:'background',type:'background',paint:{'background-color':'#061221'}},{id:'base',type:'raster',source:'base'},{id:'labels',type:'raster',source:'labels'}]}});
|
||||
map=new ml.Map({container:'settings-map',center:[p.longitude,p.latitude],zoom:p.zoom??15,pitch:0,bearing:0,maxZoom:18,maxTileCacheSize:1024,style:{version:8,sources:{base:{type:'raster',tiles:[urls(0)],tileSize:256,maxzoom:18},labels:{type:'raster',tiles:[urls(1)],tileSize:256,maxzoom:18}},layers:[{id:'background',type:'background',paint:{'background-color':'#061221'}},{id:'base',type:'raster',source:'base'},{id:'labels',type:'raster',source:'labels'}]}});
|
||||
map.on('load',()=>{for(const [i,k]of ['base','labels'].entries())map.getSource(k)?.setTiles([urls(i)]);});
|
||||
tileBuffer=attachTileBuffer(map,()=>kind,()=>revision);
|
||||
map.addControl(new ml.NavigationControl({visualizePitch:false}),'bottom-left');
|
||||
map.addControl(new ml.AttributionControl({customAttribution:'天地图 © 自然资源部 · 本机在线缓存 / 离线资源',compact:true}),'bottom-right');
|
||||
marker=new ml.Marker({color:'#9bcaff'}).setLngLat([p.longitude,p.latitude]).addTo(map);
|
||||
observer=new ResizeObserver(()=>map?.resize());observer.observe(document.getElementById('settings-map'));
|
||||
|
||||
map.on('movestart',()=>{start=null;box=null;if(boxElement)boxElement.hidden=true;});
|
||||
map.on('click',e=>{if(mode!=='point')return;marker.setLngLat(e.lngLat);emit('rid-map-point',{longitude:e.lngLat.lng,latitude:e.lngLat.lat,zoom:map.getZoom()});tool('');});
|
||||
map.on('error',e=>{if(e.sourceId?.match(/base|labels/))return;emit('rid-map-error',{message:'地图引擎加载失败,请检查浏览器 WebGL 支持。'});});
|
||||
boxElement=document.createElement('div');boxElement.className='map-download-selection';boxElement.hidden=true;document.getElementById('settings-map').appendChild(boxElement);
|
||||
@@ -23,13 +29,13 @@ export function open(p){
|
||||
canvas.addEventListener('pointerup',()=>{if(!start)return;start=null;if(box&&box[2]-box[0]>6&&box[3]-box[1]>6){const a=map.unproject([box[0],box[3]]),b=map.unproject([box[2],box[1]]);emit('rid-map-bounds',{west:Math.max(-180,a.lng),south:Math.max(-85.051128,a.lat),east:Math.min(180,b.lng),north:Math.min(85.051128,b.lat)});}tool('');});
|
||||
canvas.addEventListener('pointercancel',()=>{start=null;box=null;tool('');});
|
||||
map.getCanvas().addEventListener('keydown',e=>{if(e.key==='Escape'){start=null;box=null;boxElement.hidden=true;tool('');emit('rid-map-error',{message:'已退出地图选择模式。'});}});
|
||||
}catch{map?.remove();map=null;emit('rid-map-error',{message:'无法创建地图。仍可输入坐标、下载范围并保存配置。'});}
|
||||
}catch{close();emit('rid-map-error',{message:'无法创建地图。仍可输入坐标、下载范围并保存配置。'});}
|
||||
}
|
||||
export function configure(p){if(!map)return;setBasemap(p.basemap);map.jumpTo({center:[p.longitude,p.latitude],zoom:p.zoom});marker?.setLngLat([p.longitude,p.latitude]);}
|
||||
export function setBasemap(value){if(!map)return;kind=value==='road'?'road':'imagery';for(const [i,k]of ['base','labels'].entries())map.getSource(k)?.setTiles([urls(i)]);}
|
||||
export function refresh(){revision++;setBasemap(kind);}
|
||||
export function tool(value){mode=value;start=null;box=null;if(!map)return;if(mode==='box')map.dragPan.disable();else map.dragPan.enable();map.getCanvas().style.cursor=mode?'crosshair':'';}
|
||||
export function setBasemap(value){if(!map)return;const next=value==='road'?'road':'imagery';if(next===kind)return;kind=next;for(const [i,k]of ['base','labels'].entries())map.getSource(k)?.setTiles([urls(i)]);}
|
||||
export function refresh(){revision++;for(const [i,k]of ['base','labels'].entries())map?.getSource(k)?.setTiles([urls(i)]);tileBuffer?.schedule();}
|
||||
export function tool(value){mode=value;start=null;box=null;if(!map)return;if(mode==='box')map.dragPan.disable();else map.dragPan.enable();map.getCanvas().style.cursor=mode?'crosshair':'';if(mode)map.getCanvas().focus();}
|
||||
export function bounds(value){if(!map)return;map.fitBounds([[value.west,value.south],[value.east,value.north]],{padding:{left:60,right:Math.min(430,map.getContainer().clientWidth/2),top:70,bottom:60},duration:400});}
|
||||
export function current(){if(!map)return;const p=map.getCenter();emit('rid-map-point',{longitude:p.lng,latitude:p.lat,zoom:map.getZoom()});marker?.setLngLat(p);}
|
||||
export function metrics(){return map?{ready:map.loaded(),camera:{longitude:map.getCenter().lng,latitude:map.getCenter().lat,zoom:map.getZoom()},basemap:kind}:null;}
|
||||
export function close(){observer?.disconnect();observer=null;map?.remove();map=null;marker=null;boxElement=null;mode='';}
|
||||
export function metrics(){return map?{tileBuffer:tileBuffer?.metrics(),ready:map.loaded(),camera:{longitude:map.getCenter().lng,latitude:map.getCenter().lat,zoom:map.getZoom()},basemap:kind}:null;}
|
||||
export function close(){tileBuffer?.destroy();tileBuffer=null;observer?.disconnect();observer=null;map?.remove();map=null;marker=null;boxElement=null;mode='';start=null;box=null;}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
.map-settings-layout{height:100%;min-height:0;display:grid;grid-template-columns:210px minmax(0,1fr);gap:18px;padding:24px}.map-settings-stage{position:relative;overflow:hidden;min-height:0}.map-settings-head{height:68px;display:flex;align-items:center;justify-content:space-between;padding:0 20px;gap:14px;border-bottom:1px solid var(--work-line)}.map-settings-head h2{font-size:16px}.map-settings-head p{font-size:11px;color:var(--work-muted);margin-top:5px}.map-settings-head button{font-size:12px;padding:8px 12px;border-radius:7px}#settings-map{position:absolute;inset:68px 0 0;background:#061221}.map-settings-hint{position:absolute;left:16px;bottom:32px;right:430px;font-size:11px;color:var(--work-text);background:var(--glass-solid);border:1px solid var(--work-line);border-radius:7px;padding:10px 12px;pointer-events:none;z-index:3;line-height:1.8}.map-settings-drawer{position:absolute;right:16px;top:84px;bottom:16px;width:390px;display:flex;flex-direction:column;background:var(--glass-solid);z-index:4;overflow:hidden}.map-settings-drawer .setting-panel-head button{padding:4px 10px;border:0;background:none;box-shadow:none}.map-settings-scroll{flex:1;min-height:0;overflow:auto;padding:16px;scrollbar-width:thin;scroll-padding-block:18px}.map-settings-caption{display:flex;align-items:center;justify-content:space-between;gap:8px;border-top:1px solid var(--work-line);padding-top:18px;margin:20px 0 16px;font-size:13px;font-weight:600}.map-settings-caption span{color:var(--work-muted);font-size:10px;font-weight:400}.map-settings-label{display:block;color:var(--work-muted);font-size:12px;min-width:0}.map-settings-scroll :is(input:not([type=checkbox]),select){display:block;width:100%;min-width:0;box-shadow:none;font:inherit;color:var(--work-text);background:var(--work-input);border:1px solid var(--work-line);border-radius:7px;padding:10px;margin-top:8px;height:39px;font-size:12px}.map-settings-fields{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin:16px 0}.map-settings-actions{display:flex;gap:9px;align-items:center;flex-wrap:wrap;margin:18px 0 12px}.map-settings-actions button,.map-region-name button{font-size:12px;padding:8px 10px;border-radius:7px}.map-settings-message{font-size:11px;line-height:1.9;color:#bdd9ff;overflow-wrap:anywhere;min-height:22px}.map-settings-message.error{color:var(--mc-danger,#ffaaa4)}.map-settings-small{font-size:11px;line-height:1.9;color:var(--work-muted);margin:10px 0}.map-network-note{padding:12px;border:1px solid var(--work-line);border-radius:8px;font-size:11px;line-height:1.9;background:#8bbdff0a;overflow-wrap:anywhere}.map-network-note.warning{border-color:#ffd08a66;color:#ffd08a;background:#ffd08a0a}.map-layer-choices{display:flex;flex-wrap:wrap;gap:15px;font-size:11px;margin:16px 0}.map-layer-choices label{display:flex;align-items:center;gap:8px}.map-layer-choices input{width:14px;height:14px;margin:0;padding:0;box-shadow:none}.map-region-name{display:flex;gap:6px;align-items:center}.map-region-name input{flex:1;margin:0!important}.map-region-name button{flex:none}#map-download-progress{width:100%;height:7px;accent-color:#8bbdff;margin:8px 0}.map-reload{font-size:11px;padding:5px 0;border:0;background:none;box-shadow:none;color:var(--work-muted)}.map-settings-layout button:disabled{opacity:.45;cursor:not-allowed}.map-download-selection{position:absolute;border:2px dashed #b3d5ff;background:#8bbdff26;pointer-events:none;z-index:2}.map-settings-layout .maplibregl-ctrl-attrib{font-size:9px}.map-settings-stage:has(.map-settings-drawer[hidden]) .map-settings-hint{right:16px}body[data-menu-hidden=true] #map-settings-view{left:0}
|
||||
.map-settings-layout{height:100%;min-height:0;display:grid;grid-template-columns:210px minmax(0,1fr);gap:18px;padding:24px}.map-settings-stage{position:relative;overflow:hidden;min-height:0}.map-settings-head{height:68px;display:flex;align-items:center;justify-content:space-between;padding:0 20px;gap:14px;border-bottom:1px solid var(--work-line)}.map-settings-head h2{font-size:16px}.map-settings-head p{font-size:11px;color:var(--work-muted);margin-top:5px}.map-settings-head button{font-size:12px;padding:8px 12px;border-radius:7px}#settings-map{position:absolute;inset:68px 0 0;background:#061221}.map-settings-hint{position:absolute;left:70px;bottom:32px;right:430px;font-size:11px;color:var(--work-text);background:var(--glass-solid);border:1px solid var(--work-line);border-radius:7px;padding:10px 12px;pointer-events:none;z-index:3;line-height:1.8}.map-settings-drawer{position:absolute;right:16px;top:84px;bottom:16px;width:390px;display:flex;flex-direction:column;background:var(--glass-solid);z-index:4;overflow:hidden}.map-settings-drawer .setting-panel-head button{padding:4px 10px;border:0;background:none;box-shadow:none}.map-settings-scroll{flex:1;min-height:0;overflow:auto;padding:16px;scrollbar-width:thin;scroll-padding-block:18px}.map-settings-caption{display:flex;align-items:center;justify-content:space-between;gap:8px;border-top:1px solid var(--work-line);padding-top:18px;margin:20px 0 16px;font-size:13px;font-weight:600}.map-settings-caption span{color:var(--work-muted);font-size:10px;font-weight:400}.map-settings-label{display:block;color:var(--work-muted);font-size:12px;min-width:0}.map-settings-scroll :is(input:not([type=checkbox]),select){display:block;width:100%;min-width:0;box-shadow:none;font:inherit;color:var(--work-text);background:var(--work-input);border:1px solid var(--work-line);border-radius:7px;padding:10px;margin-top:8px;height:39px;font-size:12px}.map-settings-fields{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin:16px 0}.map-settings-actions{display:flex;gap:9px;align-items:center;flex-wrap:wrap;margin:18px 0 12px}.map-settings-actions button,.map-region-name button{font-size:12px;padding:8px 10px;border-radius:7px}.map-settings-message{font-size:11px;line-height:1.9;color:#bdd9ff;overflow-wrap:anywhere;min-height:22px}.map-settings-message.error{color:var(--mc-danger,#ffaaa4)}.map-settings-small{font-size:11px;line-height:1.9;color:var(--work-muted);margin:10px 0}.map-network-note{padding:12px;border:1px solid var(--work-line);border-radius:8px;font-size:11px;line-height:1.9;background:#8bbdff0a;overflow-wrap:anywhere}.map-network-note.warning{border-color:#ffd08a66;color:#ffd08a;background:#ffd08a0a}.map-layer-choices{display:flex;flex-wrap:wrap;gap:15px;font-size:11px;margin:16px 0}.map-layer-choices label{display:flex;align-items:center;gap:8px}.map-layer-choices input{width:14px;height:14px;margin:0;padding:0;box-shadow:none}.map-region-name{display:flex;gap:6px;align-items:center}.map-region-name input{flex:1;margin:0!important}.map-region-name button{flex:none}#map-download-progress{width:100%;height:7px;accent-color:#8bbdff;margin:8px 0}.map-reload{font-size:11px;padding:5px 0;border:0;background:none;box-shadow:none;color:var(--work-muted)}.map-settings-layout button:disabled{opacity:.45;cursor:not-allowed}.map-download-selection{position:absolute;border:2px dashed #b3d5ff;background:#8bbdff26;pointer-events:none;z-index:2}.map-settings-layout .maplibregl-ctrl-attrib{font-size:9px}.map-settings-stage:has(.map-settings-drawer[hidden]) .map-settings-hint{right:16px}body[data-menu-hidden=true] #map-settings-view{left:0}
|
||||
@media(max-width:1200px){.map-settings-layout{grid-template-columns:180px minmax(0,1fr);padding:18px;gap:14px}.map-settings-drawer{width:360px;right:12px}.map-settings-hint{right:390px}}
|
||||
@media(max-width:900px){.map-settings-layout{display:flex;flex-direction:column;height:auto;padding:14px;gap:14px}.map-settings-layout>.settings-sidebar{display:flex;flex-wrap:wrap;padding:8px;gap:5px}.map-settings-layout>.settings-sidebar :is(h2,.micro){display:none}.map-settings-layout .setting-link{width:auto;font-size:11px}.map-settings-stage{min-height:700px;overflow:visible}.map-settings-head{height:auto;min-height:68px;padding:14px;flex-wrap:wrap}.map-settings-head .row{flex-wrap:wrap;gap:6px}.map-settings-head button{padding:6px 9px;font-size:11px}#settings-map{position:relative;inset:auto;height:360px}.map-settings-drawer{position:relative;inset:auto;width:auto;margin:12px;max-height:650px;min-height:300px}.map-settings-hint{position:relative;inset:auto;margin:12px}.map-settings-stage:has(.map-settings-drawer[hidden]) .map-settings-hint{right:auto}.map-settings-caption{flex-wrap:wrap}}
|
||||
|
||||
.map-settings-layout .maplibregl-ctrl-group{background:var(--glass-solid);border:1px solid var(--work-line)}.map-settings-layout .maplibregl-ctrl-group button{border-radius:0;color:var(--work-text);border-color:var(--work-line);background:transparent}.map-settings-layout .maplibregl-ctrl button .maplibregl-ctrl-icon{filter:invert(1)}.map-settings-layout .maplibregl-ctrl-attrib{background:var(--glass-solid);color:var(--work-muted)}.map-settings-layout .maplibregl-ctrl-attrib a{color:var(--work-muted)}.map-settings-layout .maplibregl-ctrl-attrib-button{filter:invert(1)}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// Shared, bounded viewport warming. Visible MapLibre requests always run first.
|
||||
const pairs={imagery:['img_w','cia_w'],road:['vec_w','cva_w']};
|
||||
export function attachTileBuffer(map,getKind,getRevision=()=>0){
|
||||
let generation=0,closed=false,timer,cooldownUntil=0,controllers=new Set(),queue=[],running=0,lastSignature='',lastPrepared=0;
|
||||
const warmed=new Map();
|
||||
const metrics={requested:0,hits:0,cancelled:0,failed:0};
|
||||
const url=(layer,z,x,y)=>`/api/maps/tile/${layer}/${z}/${x}/${y}${getRevision()?`?v=${getRevision()}`:''}`;
|
||||
function cancel(){generation++;lastSignature='';clearTimeout(timer);timer=null;queue=[];for(const c of controllers)c.abort();controllers.clear();}
|
||||
function pump(token){
|
||||
if(closed||token!==generation||Date.now()<cooldownUntil)return;
|
||||
while(running<4&&queue.length){
|
||||
const item=queue.shift(),controller=new AbortController();controllers.add(controller);running++;metrics.requested++;
|
||||
fetch(item,{signal:controller.signal,cache:'default',headers:{'x-rid-prefetch':'1'}}).then(async response=>{
|
||||
if(response.status===429){if(token===generation){queue.unshift(item);cooldownUntil=Date.now()+500;setTimeout(()=>pump(token),550);}return;}
|
||||
if(!response.ok){if(token===generation){cooldownUntil=Date.now()+30000;queue=[];}throw Error('tile unavailable');}await response.arrayBuffer();
|
||||
warmed.delete(item);warmed.set(item,Date.now());while(warmed.size>4096)warmed.delete(warmed.keys().next().value);
|
||||
}).catch(error=>{if(error.name==='AbortError')metrics.cancelled++;else {metrics.failed++;if(token===generation){cooldownUntil=Date.now()+30000;queue=[];}}}).finally(()=>{
|
||||
controllers.delete(controller);running--;pump(generation);
|
||||
});
|
||||
}
|
||||
}
|
||||
function prepare(){
|
||||
if(closed||running||queue.length||Date.now()<cooldownUntil||map.isMoving()||!map.isStyleLoaded())return;
|
||||
const w=map.getCanvas().clientWidth,h=map.getCanvas().clientHeight;
|
||||
if(!w||!h)return;
|
||||
const c=map.getCenter(),signature=[c.lng,c.lat,map.getZoom(),map.getPitch(),map.getBearing(),w,h,getKind(),getRevision()].join('/');
|
||||
if(signature===lastSignature&&Date.now()-lastPrepared<60000)return;
|
||||
cancel();const token=generation;lastSignature=signature;lastPrepared=Date.now();
|
||||
// A 256px raster source uses one level above the 512px MapLibre camera scale.
|
||||
const detail=Math.min(18,Math.max(0,Math.round(map.getZoom()+1)));
|
||||
const kind=getKind(),groups=[pairs[kind],pairs[kind==='road'?'imagery':'road']],unique=new Set();
|
||||
// Warm the immediate parent too: raster fades can request it during a pan.
|
||||
for(const layers of groups)for(const z of new Set([detail,Math.max(0,detail-1)])){
|
||||
const n=2**z;
|
||||
const tile=p=>{const c=map.unproject(p),lat=Math.max(-85.051128,Math.min(85.051128,c.lat))*Math.PI/180;return [(c.lng+180)/360*n,(1-Math.asinh(Math.tan(lat))/Math.PI)/2*n];};
|
||||
const corners=[tile([-w,-h]),tile([2*w,-h]),tile([-w,2*h]),tile([2*w,2*h])],center=tile([w/2,h/2]);
|
||||
const x0=Math.floor(Math.min(...corners.map(p=>p[0]))),x1=Math.floor(Math.max(...corners.map(p=>p[0])));
|
||||
const y0=Math.max(0,Math.floor(Math.min(...corners.map(p=>p[1])))),y1=Math.min(n-1,Math.floor(Math.max(...corners.map(p=>p[1]))));
|
||||
const cells=[];for(let x=x0;x<=Math.min(x1,x0+n-1);x++)for(let y=y0;y<=y1;y++)cells.push([x,y,(x-center[0])**2+(y-center[1])**2]);
|
||||
cells.sort((a,b)=>a[2]-b[2]);
|
||||
for(const [x,y]of cells.slice(0,4096))for(const layer of layers){
|
||||
const key=url(layer,z,((x%n)+n)%n,y);if(unique.has(key))continue;unique.add(key);
|
||||
if(Date.now()-(warmed.get(key)||0)<240000){metrics.hits++;continue;}queue.push(key);
|
||||
}
|
||||
}
|
||||
pump(token);
|
||||
}
|
||||
const schedule=()=>{if(timer)return;timer=setTimeout(()=>{timer=null;prepare();},200);};
|
||||
const sourcedata=e=>{if(/^(tdt-base|tdt-labels|base|labels)$/.test(e.sourceId)&&e.isSourceLoaded&&!running&&!queue.length)schedule();};
|
||||
map.on('movestart',cancel);map.on('moveend',schedule);map.on('idle',schedule);map.on('load',schedule);map.on('sourcedata',sourcedata);
|
||||
return {schedule(){cancel();cooldownUntil=0;lastSignature='';schedule();},metrics:()=>({...metrics,queued:queue.length,running,warmed:warmed.size}),destroy(){closed=true;cancel();map.off('movestart',cancel);map.off('moveend',schedule);map.off('idle',schedule);map.off('load',schedule);map.off('sourcedata',sourcedata);warmed.clear();}};
|
||||
}
|
||||
@@ -63,8 +63,7 @@ body[data-menu-hidden=true] .workspace-pane{left:0}body[data-menu-hidden=true] .
|
||||
.mc-layout-b .mc-btn-row .primary{background:#356ba6;color:#fff;border-color:#8bbdff55}
|
||||
.mc-layout-b .mc-map-toolstrip{right:16px;top:16px;left:auto!important;width:auto;max-width:calc(100% - 32px);display:flex;flex-direction:row;gap:2px;padding:4px;background:var(--work-panel);border:1px solid var(--work-line);border-radius:9px;z-index:6;box-shadow:0 5px 18px #0002}
|
||||
.mc-layout-b .mc-map-toolstrip button{background:none;border:0;min-width:34px;padding:6px 8px;font-size:14px}
|
||||
.mc-layout-b .mc-map-infobar{left:16px;right:auto;bottom:calc(var(--dock-space) - 28px);max-width:min(420px,calc(100% - 32px));background:var(--work-panel);border:1px solid var(--work-line);border-radius:7px;padding:5px 9px;font-size:11px;line-height:1.5;white-space:normal;pointer-events:none;z-index:4;transform:translateY(-4px)}
|
||||
.mc-layout-b:not(.compact) .mc-map-infobar{left:var(--left-space);max-width:calc(100% - var(--left-space) - var(--right-space) - 16px)}
|
||||
.mc-layout-b .mc-map-infobar{left:auto;right:16px;bottom:16px;max-width:min(420px,calc(100% - 32px));background:var(--work-panel);border:1px solid var(--work-line);border-radius:7px;padding:5px 9px;font-size:11px;line-height:1.5;white-space:normal;pointer-events:none;z-index:40;transform:none}
|
||||
.mc-layout-b .mc-hud-dock{position:absolute;left:16px;right:16px;bottom:16px;height:var(--dock-height);flex:none;min-height:0;max-height:none;border:1px solid var(--work-line);border-radius:12px;background:var(--work-panel);backdrop-filter:blur(24px);z-index:7;box-shadow:0 7px 25px #0002}
|
||||
.mc-layout-b .live-resizer{height:10px;min-height:10px;display:grid;place-items:center;cursor:ns-resize;touch-action:none;user-select:none}
|
||||
.mc-layout-b .live-resizer:after{content:'';width:40px;height:3px;background:var(--work-muted);opacity:.65;border-radius:3px}
|
||||
@@ -101,9 +100,8 @@ body[data-menu-hidden=true] .workspace-pane{left:0}body[data-menu-hidden=true] .
|
||||
.mc-layout-b.compact .mc-dock-tab{font-size:11px}
|
||||
.mc-layout-b.compact .live-dock-actions{gap:3px;margin-left:auto}
|
||||
.mc-layout-b.compact .live-dock-actions button{font-size:11px;padding:4px 6px}
|
||||
.mc-layout-b.compact .mc-map-infobar{bottom:var(--dock-space)}
|
||||
.mc-layout-b #rt-map .maplibregl-ctrl-bottom-right{bottom:calc(var(--dock-space) - 28px);right:16px;max-width:calc(100% - 32px)}
|
||||
@container(max-width:1199px){.mc-layout-b .live-targets{width:230px}.mc-layout-b .live-detail{width:280px!important}.mc-layout-b:not(.list-hidden):not(.compact) .mc-map-infobar{left:258px}}
|
||||
@container(max-width:1199px){.mc-layout-b .live-targets{width:230px}.mc-layout-b .live-detail{width:280px!important}}
|
||||
.theme-white .mc-layout-b .mc-tag{color:#38604e}
|
||||
@media(max-width:1400px){}
|
||||
@media(max-width:1100px){.settings-layout{padding:24px;max-width:100%;overflow:auto}}
|
||||
@@ -115,3 +113,7 @@ body[data-menu-hidden=true] .workspace-pane{left:0}body[data-menu-hidden=true] .
|
||||
.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)}
|
||||
.theme-white .mc-layout-b .live-basemap option{background:#f4f8ff;color:#243b57}
|
||||
|
||||
/* Realtime owns one business menu; other applications retain their navigation. */
|
||||
body[data-screen=realtime] .reference-rail button:not(#rt-blacklist-menu):not(#geofence-menu),body[data-screen=realtime] .reference-rail .rail-rule{display:none!important}
|
||||
.reference-rail #rt-blacklist-menu[aria-expanded=true]{background:#8bbdff24;color:var(--work-text)}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<div class="gf-stage"><div id="geofence-map" aria-label="电子围栏地图"></div><header class="gf-heading"><h1>电子围栏工作台</h1><p>二维本地监测 · 白名单免告警 · 不控制无人机</p><div class="gf-tools"><button type="button" id="gf-circle">+ 圆形</button><button type="button" id="gf-polygon">⌁ 多边形</button><button type="button" id="gf-finish" hidden>完成绘制</button><button type="button" id="gf-cancel" hidden>取消绘制</button><button type="button" id="gf-imagery">影像</button><button type="button" id="gf-road">路网</button></div><p id="gf-map-hint" role="status">选择围栏,或新建一个监测区域。</p></header><aside class="gf-drawer" aria-label="围栏管理"><header class="gf-drawer-heading"><h2>围栏管理</h2><button type="button" id="gf-new" disabled>+ 新建</button></header><div class="gf-scroll"><div class="gf-section-title"><span>已保存围栏</span><button type="button" id="gf-refresh">刷新</button></div><div id="gf-list" role="group" aria-label="围栏目录"><p>正在读取围栏…</p></div><form id="gf-form" hidden><div class="gf-section-title">编辑围栏</div><label for="gf-name">围栏名称</label><input id="gf-name" maxlength="40" required placeholder="例如:园区核心区"><label class="gf-switch"><input id="gf-enabled" type="checkbox" checked>启用监测</label><label for="gf-shape">范围形状</label><select id="gf-shape"><option value="circle">圆形</option><option value="polygon">多边形</option></select><div id="gf-circle-fields"><div class="gf-field-row"><label>中心经度<input id="gf-longitude" type="number" step="any" min="-180" max="180" required></label><label>中心纬度<input id="gf-latitude" type="number" step="any" min="-90" max="90" required></label></div><label for="gf-radius">半径(米)</label><input id="gf-radius" type="number" min="1" max="1000000" step="any" required></div><div id="gf-polygon-fields" hidden><label for="gf-vertices">顶点坐标(JSON 数组)</label><textarea id="gf-vertices" rows="4" spellcheck="false" aria-describedby="gf-vertices-help"></textarea><p id="gf-vertices-help">格式:[[经度,纬度],…],3–128点,不重复首点;也可在地图逐点绘制或拖动顶点。</p></div><p class="gf-explain">边界视为内部;首次观测已在区域内会告警。离开后再次进入可重新触发。停用只影响后续事件,历史记录保留。</p><div class="gf-editor-actions"><button type="submit" id="gf-save" class="primary">保存围栏</button><button type="button" id="gf-locate">定位</button><button type="button" id="gf-delete">删除</button></div></form><div class="gf-section-title"><h3>进入告警</h3><button type="button" id="gf-events-refresh">刷新</button></div><p class="gf-explain" id="gf-events-scope">显示全部围栏事件;选择围栏后仅显示该围栏。</p><ol id="gf-events"><li>正在读取历史事件…</li></ol><button type="button" id="gf-events-more" hidden>加载更早记录</button></div><footer class="gf-footer"><p id="gf-message" role="status">围栏及告警保存在本机服务端。</p></footer></aside><p class="gf-map-status" id="gf-map-status" role="status">正在读取地图状态…</p></div>
|
||||
@@ -0,0 +1,829 @@
|
||||
//! A floating manager. Browser drawing is interop; validated state stays in Rust.
|
||||
use gloo_net::http::Request;
|
||||
use gloo_timers::future::TimeoutFuture;
|
||||
use rid_shared::geofences::{Alert, Fence, Geometry, Snapshot};
|
||||
use serde_json::{Value, json};
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
use wasm_bindgen::{JsCast, closure::Closure};
|
||||
use wasm_bindgen_futures::spawn_local;
|
||||
use web_sys::{Element, HtmlInputElement, HtmlSelectElement, HtmlTextAreaElement};
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
snapshot: Option<Snapshot>,
|
||||
draft: Option<Fence>,
|
||||
draft_revision: u64,
|
||||
dirty: bool,
|
||||
busy: bool,
|
||||
center: [f64; 2],
|
||||
before: Option<u64>,
|
||||
events: Vec<Alert>,
|
||||
drawing: bool,
|
||||
}
|
||||
type Shared = Rc<RefCell<State>>;
|
||||
thread_local! {static STATE:RefCell<Option<Shared>>=const{RefCell::new(None)};}
|
||||
fn doc() -> web_sys::Document {
|
||||
web_sys::window()
|
||||
.expect("browser")
|
||||
.document()
|
||||
.expect("document")
|
||||
}
|
||||
fn el(id: &str) -> Option<Element> {
|
||||
doc().get_element_by_id(id)
|
||||
}
|
||||
fn text(id: &str, value: &str) {
|
||||
if let Some(e) = el(id) {
|
||||
e.set_text_content(Some(value));
|
||||
}
|
||||
}
|
||||
fn hidden(id: &str, value: bool) {
|
||||
if let Some(e) = el(id) {
|
||||
if value {
|
||||
let _ = e.set_attribute("hidden", "");
|
||||
} else {
|
||||
let _ = e.remove_attribute("hidden");
|
||||
}
|
||||
}
|
||||
}
|
||||
fn disabled(id: &str, value: bool) {
|
||||
if let Some(e) = el(id) {
|
||||
if value {
|
||||
let _ = e.set_attribute("disabled", "");
|
||||
} else {
|
||||
let _ = e.remove_attribute("disabled");
|
||||
}
|
||||
}
|
||||
}
|
||||
fn value(id: &str) -> String {
|
||||
let Some(e) = el(id) else {
|
||||
return String::new();
|
||||
};
|
||||
if let Some(i) = e.dyn_ref::<HtmlInputElement>() {
|
||||
i.value()
|
||||
} else if let Some(i) = e.dyn_ref::<HtmlSelectElement>() {
|
||||
i.value()
|
||||
} else if let Some(i) = e.dyn_ref::<HtmlTextAreaElement>() {
|
||||
i.value()
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
fn set(id: &str, value: &str) {
|
||||
if let Some(e) = el(id) {
|
||||
if let Some(i) = e.dyn_ref::<HtmlInputElement>() {
|
||||
i.set_value(value)
|
||||
} else if let Some(i) = e.dyn_ref::<HtmlSelectElement>() {
|
||||
i.set_value(value)
|
||||
} else if let Some(i) = e.dyn_ref::<HtmlTextAreaElement>() {
|
||||
i.set_value(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
fn visible() -> bool {
|
||||
doc()
|
||||
.body()
|
||||
.is_some_and(|b| b.get_attribute("data-screen").as_deref() == Some("geofences"))
|
||||
}
|
||||
fn message(value: &str, error: bool) {
|
||||
text("gf-message", value);
|
||||
if let Some(e) = el("gf-message") {
|
||||
let _ = e.set_attribute("data-error", if error { "true" } else { "false" });
|
||||
}
|
||||
}
|
||||
fn map(method: &str, arg: Value) {
|
||||
let Ok(api) = js_sys::Reflect::get(&js_sys::global(), &"ridGeofences".into()) else {
|
||||
return;
|
||||
};
|
||||
let Ok(f) =
|
||||
js_sys::Reflect::get(&api, &method.into()).and_then(|v| v.dyn_into::<js_sys::Function>())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if let Ok(v) = js_sys::JSON::parse(&arg.to_string()) {
|
||||
let _ = f.call1(&api, &v);
|
||||
}
|
||||
}
|
||||
fn confirm() -> bool {
|
||||
web_sys::window().is_some_and(|w| {
|
||||
w.confirm_with_message("当前围栏有未保存修改,放弃草稿继续?")
|
||||
.unwrap_or(false)
|
||||
})
|
||||
}
|
||||
fn buttons(s: &Shared) {
|
||||
let s = s.borrow();
|
||||
for id in ["gf-new", "gf-circle", "gf-polygon"] {
|
||||
disabled(id, s.busy || s.snapshot.is_none());
|
||||
}
|
||||
for id in ["gf-save", "gf-delete", "gf-locate"] {
|
||||
disabled(
|
||||
id,
|
||||
s.busy || s.draft.is_none() || s.snapshot.is_none() || (id == "gf-save" && s.drawing),
|
||||
);
|
||||
}
|
||||
for id in ["gf-name", "gf-enabled", "gf-shape", "gf-vertices"] {
|
||||
disabled(id, s.busy);
|
||||
}
|
||||
for id in ["gf-longitude", "gf-latitude", "gf-radius"] {
|
||||
disabled(
|
||||
id,
|
||||
s.busy
|
||||
|| s.draft
|
||||
.as_ref()
|
||||
.is_some_and(|f| matches!(f.geometry, Geometry::Polygon { .. })),
|
||||
);
|
||||
}
|
||||
disabled("gf-refresh", s.busy);
|
||||
text(
|
||||
"gf-save",
|
||||
if s.busy {
|
||||
"正在保存…"
|
||||
} else {
|
||||
"保存围栏"
|
||||
},
|
||||
);
|
||||
}
|
||||
fn render_map(s: &Shared) {
|
||||
let s = s.borrow();
|
||||
map(
|
||||
"render",
|
||||
json!({"entries":s.snapshot.as_ref().map(|v|v.entries.clone()).unwrap_or_default(),"draft":s.draft}),
|
||||
);
|
||||
}
|
||||
fn fields(s: &Shared) {
|
||||
let s = s.borrow();
|
||||
hidden("gf-form", s.draft.is_none());
|
||||
if let Some(f) = &s.draft {
|
||||
set("gf-name", &f.name);
|
||||
if let Some(i) = el("gf-enabled").and_then(|e| e.dyn_into::<HtmlInputElement>().ok()) {
|
||||
i.set_checked(f.enabled);
|
||||
}
|
||||
let circle = matches!(f.geometry, Geometry::Circle { .. });
|
||||
hidden("gf-circle-fields", !circle);
|
||||
hidden("gf-polygon-fields", circle);
|
||||
for id in ["gf-longitude", "gf-latitude", "gf-radius"] {
|
||||
disabled(id, !circle);
|
||||
}
|
||||
match &f.geometry {
|
||||
Geometry::Circle { center, radius_m } => {
|
||||
set("gf-shape", "circle");
|
||||
set("gf-longitude", ¢er[0].to_string());
|
||||
set("gf-latitude", ¢er[1].to_string());
|
||||
set("gf-radius", &radius_m.to_string());
|
||||
}
|
||||
Geometry::Polygon { vertices } => {
|
||||
set("gf-shape", "polygon");
|
||||
set(
|
||||
"gf-vertices",
|
||||
&serde_json::to_string(vertices).unwrap_or_default(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn paint_list(s: &Shared) {
|
||||
let Some(root) = el("gf-list") else { return };
|
||||
root.set_text_content(None);
|
||||
let state = s.borrow();
|
||||
let Some(snapshot) = &state.snapshot else {
|
||||
text("gf-list", "名单读取失败,请刷新重试。");
|
||||
return;
|
||||
};
|
||||
if snapshot.entries.is_empty() {
|
||||
root.set_text_content(Some("暂无围栏,点击新建开始。"));
|
||||
}
|
||||
for f in &snapshot.entries {
|
||||
let Ok(button) = doc().create_element("button") else {
|
||||
continue;
|
||||
};
|
||||
button.set_class_name("gf-entry");
|
||||
let _ = button.set_attribute("type", "button");
|
||||
let _ = button.set_attribute("data-fence-id", &f.id);
|
||||
let _ = button.set_attribute(
|
||||
"aria-pressed",
|
||||
if state.draft.as_ref().is_some_and(|d| d.id == f.id) {
|
||||
"true"
|
||||
} else {
|
||||
"false"
|
||||
},
|
||||
);
|
||||
let Ok(name) = doc().create_element("span") else {
|
||||
continue;
|
||||
};
|
||||
name.set_text_content(Some(&f.name));
|
||||
let Ok(status) = doc().create_element("small") else {
|
||||
continue;
|
||||
};
|
||||
status.set_text_content(Some(if f.enabled {
|
||||
"● 启用"
|
||||
} else {
|
||||
"○ 停用"
|
||||
}));
|
||||
let _ = button.append_child(&name);
|
||||
let _ = button.append_child(&status);
|
||||
let _ = root.append_child(&button);
|
||||
}
|
||||
}
|
||||
async fn request(url: &str, method: &str, body: Option<Value>) -> Result<Value, String> {
|
||||
let builder = match method {
|
||||
"PUT" => Request::put(url),
|
||||
"DELETE" => Request::delete(url),
|
||||
_ => Request::get(url),
|
||||
};
|
||||
let response = if let Some(body) = body {
|
||||
builder.json(&body).map_err(|e| e.to_string())?.send().await
|
||||
} else {
|
||||
builder.send().await
|
||||
}
|
||||
.map_err(|_| "本机服务连接失败,请重试".to_owned())?;
|
||||
let ok = response.ok();
|
||||
let value = response
|
||||
.json::<Value>()
|
||||
.await
|
||||
.map_err(|_| "服务响应无效".to_owned())?;
|
||||
if !ok {
|
||||
return Err(value["error"].as_str().unwrap_or("操作失败").to_owned());
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
async fn refresh(s: Shared) {
|
||||
if s.borrow().busy {
|
||||
return;
|
||||
}
|
||||
match request("/api/geofences", "GET", None)
|
||||
.await
|
||||
.and_then(|v| serde_json::from_value::<Snapshot>(v).map_err(|_| "围栏响应无效".into()))
|
||||
{
|
||||
Ok(snapshot) => {
|
||||
if s.borrow().busy
|
||||
|| s.borrow()
|
||||
.snapshot
|
||||
.as_ref()
|
||||
.is_some_and(|p| p.revision > snapshot.revision)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let changed = {
|
||||
let state = s.borrow();
|
||||
state.dirty && state.draft_revision != snapshot.revision
|
||||
};
|
||||
s.borrow_mut().snapshot = Some(snapshot);
|
||||
paint_list(&s);
|
||||
render_map(&s);
|
||||
buttons(&s);
|
||||
if changed {
|
||||
message("围栏已有远端更新;草稿保留,保存时将校验版本。", true);
|
||||
}
|
||||
}
|
||||
Err(e) => message(&e, true),
|
||||
}
|
||||
}
|
||||
fn paint_events(s: &Shared) {
|
||||
let Some(root) = el("gf-events") else { return };
|
||||
root.set_text_content(None);
|
||||
let state = s.borrow();
|
||||
if state.events.is_empty() {
|
||||
root.set_text_content(Some("暂无进入告警。"));
|
||||
}
|
||||
for e in &state.events {
|
||||
let Ok(row) = doc().create_element("li") else {
|
||||
continue;
|
||||
};
|
||||
row.set_text_content(Some(&format!(
|
||||
"{} 进入 {} · {}",
|
||||
e.target_id,
|
||||
e.fence_name.as_deref().unwrap_or("已删除围栏"),
|
||||
if e.list_kind == "black" {
|
||||
"黑名单"
|
||||
} else {
|
||||
"未分类"
|
||||
}
|
||||
)));
|
||||
let Ok(time) = doc().create_element("time") else {
|
||||
continue;
|
||||
};
|
||||
let date = js_sys::Date::new(&wasm_bindgen::JsValue::from_f64(e.occurred_at_ms as f64));
|
||||
time.set_text_content(Some(
|
||||
&date
|
||||
.to_locale_string("zh-CN", &wasm_bindgen::JsValue::UNDEFINED)
|
||||
.as_string()
|
||||
.unwrap_or_default(),
|
||||
));
|
||||
let _ = row.append_child(&time);
|
||||
let _ = root.append_child(&row);
|
||||
}
|
||||
hidden(
|
||||
"gf-events-more",
|
||||
state.before.is_none() || state.events.len() >= 200,
|
||||
);
|
||||
}
|
||||
async fn events(s: Shared, more: bool) {
|
||||
let (id, before) = {
|
||||
let state = s.borrow();
|
||||
(
|
||||
state.draft.as_ref().map(|f| f.id.clone()),
|
||||
if more { state.before } else { None },
|
||||
)
|
||||
};
|
||||
let mut url = "/api/monitoring/events?type=geofence_enter&limit=20".to_owned();
|
||||
if let Some(id) = &id {
|
||||
url.push_str(&format!("&fence_id={id}"));
|
||||
}
|
||||
if let Some(before) = before {
|
||||
url.push_str(&format!("&before={before}"));
|
||||
}
|
||||
match request(&url, "GET", None).await {
|
||||
Ok(v) => {
|
||||
let entries = serde_json::from_value::<Vec<Alert>>(v["entries"].clone());
|
||||
if let Ok(entries) = entries {
|
||||
let mut state = s.borrow_mut();
|
||||
if state.draft.as_ref().map(|f| &f.id) != id.as_ref() {
|
||||
return;
|
||||
}
|
||||
state.before = if entries.len() == 20 {
|
||||
entries.last().map(|e| e.id)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if !more {
|
||||
state.events.clear();
|
||||
}
|
||||
state.events.extend(entries);
|
||||
drop(state);
|
||||
paint_events(&s);
|
||||
}
|
||||
}
|
||||
Err(e) => message(&format!("告警读取失败:{e}"), true),
|
||||
}
|
||||
}
|
||||
fn pick(s: Shared, id: &str) {
|
||||
if s.borrow().busy {
|
||||
return;
|
||||
}
|
||||
if s.borrow().dirty && !confirm() {
|
||||
return;
|
||||
}
|
||||
let selected = s
|
||||
.borrow()
|
||||
.snapshot
|
||||
.as_ref()
|
||||
.and_then(|p| p.entries.iter().find(|f| f.id == id).cloned());
|
||||
if let Some(f) = selected {
|
||||
let mut state = s.borrow_mut();
|
||||
state.draft_revision = state.snapshot.as_ref().map_or(0, |p| p.revision);
|
||||
state.draft = Some(f);
|
||||
state.dirty = false;
|
||||
drop(state);
|
||||
map("tool", json!(""));
|
||||
fields(&s);
|
||||
paint_list(&s);
|
||||
render_map(&s);
|
||||
map("locate", Value::Null);
|
||||
buttons(&s);
|
||||
message("已载入围栏。修改后请保存。", false);
|
||||
spawn_local(events(s, false));
|
||||
}
|
||||
}
|
||||
fn new(s: &Shared) -> bool {
|
||||
if s.borrow().busy || s.borrow().snapshot.is_none() {
|
||||
return false;
|
||||
}
|
||||
if s.borrow().dirty && !confirm() {
|
||||
return false;
|
||||
}
|
||||
let mut state = s.borrow_mut();
|
||||
let center = state.center;
|
||||
let id = format!(
|
||||
"F-{:x}-{:x}",
|
||||
js_sys::Date::now() as u64,
|
||||
(js_sys::Math::random() * u32::MAX as f64) as u32
|
||||
);
|
||||
state.draft = Some(Fence {
|
||||
id,
|
||||
name: String::new(),
|
||||
enabled: true,
|
||||
geometry: Geometry::Circle {
|
||||
center,
|
||||
radius_m: 500.0,
|
||||
},
|
||||
});
|
||||
state.draft_revision = state.snapshot.as_ref().map_or(0, |p| p.revision);
|
||||
state.dirty = true;
|
||||
drop(state);
|
||||
map("tool", json!(""));
|
||||
fields(s);
|
||||
paint_list(s);
|
||||
render_map(s);
|
||||
buttons(s);
|
||||
message("新建草稿,绘制或输入范围后保存。", false);
|
||||
if let Some(e) = el("gf-name").and_then(|e| e.dyn_into::<web_sys::HtmlElement>().ok()) {
|
||||
let _ = e.focus();
|
||||
}
|
||||
true
|
||||
}
|
||||
fn read_fields(s: &Shared) -> Result<Fence, String> {
|
||||
let mut draft = s.borrow().draft.clone().ok_or("请先新建或选择围栏")?;
|
||||
draft.name = value("gf-name");
|
||||
draft.enabled = el("gf-enabled")
|
||||
.and_then(|e| e.dyn_into::<HtmlInputElement>().ok())
|
||||
.is_some_and(|i| i.checked());
|
||||
draft.geometry = if value("gf-shape") == "circle" {
|
||||
Geometry::Circle {
|
||||
center: [
|
||||
value("gf-longitude").parse().map_err(|_| "经度无效")?,
|
||||
value("gf-latitude").parse().map_err(|_| "纬度无效")?,
|
||||
],
|
||||
radius_m: value("gf-radius").parse().map_err(|_| "半径无效")?,
|
||||
}
|
||||
} else {
|
||||
Geometry::Polygon {
|
||||
vertices: serde_json::from_str(&value("gf-vertices"))
|
||||
.map_err(|_| "顶点格式无效,请输入坐标数组")?,
|
||||
}
|
||||
};
|
||||
if !draft.valid() {
|
||||
return Err("请输入有效名称和范围;多边形不能自交或跨越日期变更线。".into());
|
||||
}
|
||||
Ok(draft)
|
||||
}
|
||||
async fn save(s: Shared) {
|
||||
if s.borrow().busy {
|
||||
return;
|
||||
}
|
||||
let draft = match read_fields(&s) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
message(&e, true);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let revision = s.borrow().draft_revision;
|
||||
s.borrow_mut().busy = true;
|
||||
buttons(&s);
|
||||
let result = request(
|
||||
&format!("/api/geofences/{}", draft.id),
|
||||
"PUT",
|
||||
Some(json!({"fence":draft,"expected_revision":revision})),
|
||||
)
|
||||
.await;
|
||||
s.borrow_mut().busy = false;
|
||||
match result {
|
||||
Ok(v) => {
|
||||
if let Ok(snapshot) = serde_json::from_value::<Snapshot>(v) {
|
||||
let mut state = s.borrow_mut();
|
||||
state.draft_revision = snapshot.revision;
|
||||
state.snapshot = Some(snapshot);
|
||||
state.draft = Some(draft);
|
||||
state.dirty = false;
|
||||
drop(state);
|
||||
paint_list(&s);
|
||||
render_map(&s);
|
||||
message("围栏已保存,服务端监测已生效。", false);
|
||||
}
|
||||
}
|
||||
Err(e) => message(
|
||||
&format!("{e};草稿已保留。版本冲突时请重新选择围栏。"),
|
||||
true,
|
||||
),
|
||||
}
|
||||
buttons(&s);
|
||||
}
|
||||
async fn delete(s: Shared) {
|
||||
if s.borrow().busy {
|
||||
return;
|
||||
}
|
||||
let Some(f) = s.borrow().draft.clone() else {
|
||||
return;
|
||||
};
|
||||
if !web_sys::window().is_some_and(|w| {
|
||||
w.confirm_with_message(&format!("删除围栏“{}”?历史告警仍保留。", f.name))
|
||||
.unwrap_or(false)
|
||||
}) {
|
||||
return;
|
||||
}
|
||||
if !s
|
||||
.borrow()
|
||||
.snapshot
|
||||
.as_ref()
|
||||
.is_some_and(|p| p.entries.iter().any(|e| e.id == f.id))
|
||||
{
|
||||
s.borrow_mut().draft = None;
|
||||
s.borrow_mut().dirty = false;
|
||||
fields(&s);
|
||||
paint_list(&s);
|
||||
render_map(&s);
|
||||
buttons(&s);
|
||||
message("未保存草稿已放弃。", false);
|
||||
return;
|
||||
}
|
||||
let revision = s.borrow().draft_revision;
|
||||
s.borrow_mut().busy = true;
|
||||
buttons(&s);
|
||||
let result = request(
|
||||
&format!("/api/geofences/{}?revision={revision}", f.id),
|
||||
"DELETE",
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
s.borrow_mut().busy = false;
|
||||
match result {
|
||||
Ok(v) => {
|
||||
if let Ok(snapshot) = serde_json::from_value::<Snapshot>(v) {
|
||||
let mut state = s.borrow_mut();
|
||||
state.snapshot = Some(snapshot);
|
||||
state.draft = None;
|
||||
state.dirty = false;
|
||||
drop(state);
|
||||
fields(&s);
|
||||
paint_list(&s);
|
||||
render_map(&s);
|
||||
spawn_local(events(s.clone(), false));
|
||||
message("围栏已删除,历史告警保留。", false);
|
||||
}
|
||||
}
|
||||
Err(e) => message(&format!("{e};草稿已保留。"), true),
|
||||
}
|
||||
buttons(&s);
|
||||
}
|
||||
async fn poll_targets(s: Shared) {
|
||||
let result=async{
|
||||
let frame:rid_shared::Frame=serde_json::from_value(request("/api/realtime/snapshot","GET",None).await?).map_err(|_|"目标响应无效".to_owned())?;
|
||||
let lists:rid_shared::target_lists::Snapshot=serde_json::from_value(request("/api/target-lists","GET",None).await?).map_err(|_|"名单响应无效".to_owned())?;
|
||||
let fences=s.borrow().snapshot.as_ref().map(|p|p.entries.clone()).unwrap_or_default();
|
||||
let items=frame.targets.iter().filter(|t|frame.server_time_ms.saturating_sub(t.received_at_ms)<30000).map(|t|{
|
||||
let o=&t.observation;let kind=lists.entries.iter().find(|e|e.target_id==o.target_id).map(|e|e.list_kind);
|
||||
let inside=fences.iter().filter(|f|f.enabled&&f.geometry.contains([o.longitude,o.latitude])).map(|f|f.name.as_str()).collect::<Vec<_>>().join("、");
|
||||
json!({"target_id":o.target_id,"longitude":o.longitude,"latitude":o.latitude,"inside":inside,"list_kind":match kind{Some(rid_shared::target_lists::ListKind::White)=>"white",Some(rid_shared::target_lists::ListKind::Black)=>"black",None=>"unknown"}})
|
||||
}).collect::<Vec<_>>();map("targets",json!(items));Ok::<(),String>(())
|
||||
}.await;
|
||||
if let Err(e) = result {
|
||||
message(
|
||||
&format!("目标同步失败:{e};地图目标可能为上次状态。"),
|
||||
true,
|
||||
);
|
||||
}
|
||||
}
|
||||
pub fn open() {
|
||||
STATE.with(|cell| {
|
||||
let Some(s) = cell.borrow().clone() else {
|
||||
return;
|
||||
};
|
||||
spawn_local(async move {
|
||||
let p = request("/api/maps/preferences", "GET", None)
|
||||
.await
|
||||
.unwrap_or(
|
||||
json!({"longitude":120.1538,"latitude":30.2874,"zoom":15,"basemap":"imagery"}),
|
||||
);
|
||||
if !visible() {
|
||||
return;
|
||||
}
|
||||
s.borrow_mut().center = [
|
||||
p["longitude"].as_f64().unwrap_or(120.1538),
|
||||
p["latitude"].as_f64().unwrap_or(30.2874),
|
||||
];
|
||||
let mut available = false;
|
||||
for _ in 0..100 {
|
||||
if !visible() {
|
||||
return;
|
||||
}
|
||||
available = js_sys::Reflect::get(&js_sys::global(), &"ridGeofences".into())
|
||||
.ok()
|
||||
.and_then(|api| js_sys::Reflect::get(&api, &"open".into()).ok())
|
||||
.is_some_and(|v| v.is_function());
|
||||
if available {
|
||||
break;
|
||||
}
|
||||
TimeoutFuture::new(50).await;
|
||||
}
|
||||
if available {
|
||||
map("open", p);
|
||||
} else {
|
||||
message("地图模块未就绪,可继续输入坐标;请重新打开围栏页面。", true);
|
||||
}
|
||||
refresh(s.clone()).await;
|
||||
events(s.clone(), false).await;
|
||||
poll_targets(s).await;
|
||||
});
|
||||
});
|
||||
}
|
||||
pub fn close() {
|
||||
map("close", Value::Null);
|
||||
}
|
||||
pub fn init() {
|
||||
let state = Rc::new(RefCell::new(State::default()));
|
||||
STATE.with(|s| *s.borrow_mut() = Some(state.clone()));
|
||||
let s = state.clone();
|
||||
let click = Closure::<dyn FnMut(web_sys::Event)>::new(move |e: web_sys::Event| {
|
||||
if !visible() {
|
||||
return;
|
||||
}
|
||||
let Some(target) = e
|
||||
.target()
|
||||
.and_then(|t| t.dyn_into::<Element>().ok())
|
||||
.and_then(|e| e.closest("button").ok().flatten())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if target.has_attribute("disabled") {
|
||||
return;
|
||||
}
|
||||
if let Some(id) = target.get_attribute("data-fence-id") {
|
||||
pick(s.clone(), &id);
|
||||
return;
|
||||
}
|
||||
match target.id().as_str() {
|
||||
"gf-new" => {
|
||||
new(&s);
|
||||
}
|
||||
"gf-circle" | "gf-polygon" => {
|
||||
if s.borrow().draft.is_none() && !new(&s) {
|
||||
return;
|
||||
}
|
||||
map(
|
||||
"tool",
|
||||
json!(if target.id() == "gf-circle" {
|
||||
"circle"
|
||||
} else {
|
||||
"polygon"
|
||||
}),
|
||||
);
|
||||
}
|
||||
"gf-finish" => map("tool", json!("finish")),
|
||||
"gf-cancel" => map("tool", json!("")),
|
||||
"gf-locate" => map("locate", Value::Null),
|
||||
"gf-refresh" => spawn_local(refresh(s.clone())),
|
||||
"gf-events-refresh" => spawn_local(events(s.clone(), false)),
|
||||
"gf-events-more" => spawn_local(events(s.clone(), true)),
|
||||
"gf-delete" => spawn_local(delete(s.clone())),
|
||||
"gf-road" => map("setBasemap", json!("road")),
|
||||
"gf-imagery" => map("setBasemap", json!("imagery")),
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
let _ = doc().add_event_listener_with_callback("click", click.as_ref().unchecked_ref());
|
||||
click.forget();
|
||||
let s = state.clone();
|
||||
let submit = Closure::<dyn FnMut(web_sys::Event)>::new(move |e: web_sys::Event| {
|
||||
if e.target()
|
||||
.and_then(|t| t.dyn_into::<Element>().ok())
|
||||
.is_some_and(|e| e.id() == "gf-form")
|
||||
{
|
||||
e.prevent_default();
|
||||
spawn_local(save(s.clone()));
|
||||
}
|
||||
});
|
||||
let _ = doc().add_event_listener_with_callback("submit", submit.as_ref().unchecked_ref());
|
||||
submit.forget();
|
||||
for event in ["input", "change"] {
|
||||
let s = state.clone();
|
||||
let input = Closure::<dyn FnMut(web_sys::Event)>::new(move |e: web_sys::Event| {
|
||||
let Some(target) = e.target().and_then(|t| t.dyn_into::<Element>().ok()) else {
|
||||
return;
|
||||
};
|
||||
if target.closest("#gf-form").ok().flatten().is_none() {
|
||||
return;
|
||||
}
|
||||
s.borrow_mut().dirty = true;
|
||||
if let Some(f) = s.borrow_mut().draft.as_mut() {
|
||||
f.name = value("gf-name");
|
||||
f.enabled = el("gf-enabled")
|
||||
.and_then(|e| e.dyn_into::<HtmlInputElement>().ok())
|
||||
.is_some_and(|i| i.checked());
|
||||
}
|
||||
if target.id() == "gf-shape" {
|
||||
if let Some(f) = s.borrow_mut().draft.as_mut() {
|
||||
let center = match &f.geometry {
|
||||
Geometry::Circle { center, .. } => *center,
|
||||
Geometry::Polygon { vertices } => vertices[0],
|
||||
};
|
||||
f.geometry = if value("gf-shape") == "circle" {
|
||||
Geometry::Circle {
|
||||
center,
|
||||
radius_m: 500.0,
|
||||
}
|
||||
} else {
|
||||
Geometry::Polygon {
|
||||
vertices: vec![
|
||||
[center[0] - 0.005, center[1] - 0.003],
|
||||
[center[0] + 0.005, center[1] - 0.003],
|
||||
[center[0], center[1] + 0.005],
|
||||
],
|
||||
}
|
||||
};
|
||||
}
|
||||
fields(&s);
|
||||
}
|
||||
if let Ok(f) = read_fields(&s) {
|
||||
s.borrow_mut().draft = Some(f);
|
||||
render_map(&s);
|
||||
}
|
||||
message("有未保存修改,保存后生效。", false);
|
||||
});
|
||||
let _ = doc().add_event_listener_with_callback(event, input.as_ref().unchecked_ref());
|
||||
input.forget();
|
||||
}
|
||||
for event in [
|
||||
"rid-fence-geometry",
|
||||
"rid-fence-progress",
|
||||
"rid-fence-mode",
|
||||
"rid-fence-select",
|
||||
"rid-fence-map-error",
|
||||
"rid-fence-map-ready",
|
||||
] {
|
||||
let name = event.to_owned();
|
||||
let s = state.clone();
|
||||
let listener = Closure::<dyn FnMut(web_sys::Event)>::new(move |event: web_sys::Event| {
|
||||
if !visible() {
|
||||
return;
|
||||
}
|
||||
let v = event
|
||||
.dyn_ref::<web_sys::CustomEvent>()
|
||||
.and_then(|e| js_sys::JSON::stringify(&e.detail()).ok())
|
||||
.and_then(|v| v.as_string())
|
||||
.and_then(|v| serde_json::from_str::<Value>(&v).ok())
|
||||
.unwrap_or(Value::Null);
|
||||
match name.as_str() {
|
||||
"rid-fence-map-ready" => {
|
||||
render_map(&s);
|
||||
spawn_local(poll_targets(s.clone()));
|
||||
}
|
||||
"rid-fence-geometry" => {
|
||||
if let Ok(g) = serde_json::from_value::<Geometry>(v) {
|
||||
if !g.valid() {
|
||||
message("范围无效:请检查自交、顶点和半径。", true);
|
||||
return;
|
||||
}
|
||||
if let Some(f) = s.borrow_mut().draft.as_mut() {
|
||||
f.geometry = g;
|
||||
}
|
||||
s.borrow_mut().dirty = true;
|
||||
fields(&s);
|
||||
render_map(&s);
|
||||
message("范围已更新,保存后生效。", false);
|
||||
}
|
||||
}
|
||||
"rid-fence-mode" => {
|
||||
let active = v["mode"].as_str().is_some_and(|v| !v.is_empty());
|
||||
s.borrow_mut().drawing = active;
|
||||
hidden("gf-cancel", !active);
|
||||
hidden("gf-finish", v["mode"] != "polygon");
|
||||
text(
|
||||
"gf-map-hint",
|
||||
if v["mode"] == "circle" {
|
||||
"点击地图设置圆心;也可取消绘制。"
|
||||
} else if active {
|
||||
"逐点点击地图,至少3点后完成;Escape取消。"
|
||||
} else {
|
||||
"拖动圆心或顶点调整范围;保存后生效。"
|
||||
},
|
||||
);
|
||||
buttons(&s);
|
||||
}
|
||||
"rid-fence-select" => {
|
||||
if let Some(id) = v["id"].as_str() {
|
||||
pick(s.clone(), id)
|
||||
}
|
||||
}
|
||||
"rid-fence-progress" => {
|
||||
text(
|
||||
"gf-map-hint",
|
||||
&format!(
|
||||
"已添加 {} 个顶点,至少3点后完成。",
|
||||
v["count"].as_u64().unwrap_or(0)
|
||||
),
|
||||
);
|
||||
}
|
||||
_ => message(v["message"].as_str().unwrap_or("地图操作失败"), true),
|
||||
}
|
||||
});
|
||||
if let Some(w) = web_sys::window() {
|
||||
let _ = w.add_event_listener_with_callback(event, listener.as_ref().unchecked_ref());
|
||||
}
|
||||
listener.forget();
|
||||
}
|
||||
spawn_local(async move {
|
||||
loop {
|
||||
TimeoutFuture::new(3000).await;
|
||||
if visible() {
|
||||
refresh(state.clone()).await;
|
||||
poll_targets(state.clone()).await;
|
||||
if let Ok(v) = request("/api/maps/status", "GET", None).await {
|
||||
text(
|
||||
"gf-map-status",
|
||||
if v["keyConfigured"] == false {
|
||||
"天地图未配置密钥 · 使用已有本地缓存与离线资源"
|
||||
} else if v["mode"] == "offline" {
|
||||
"天地图暂不可用 · 已有缓存与离线资源继续显示"
|
||||
} else {
|
||||
"天地图 · 影像 / 路网 · 在线与本地缓存"
|
||||
},
|
||||
);
|
||||
}
|
||||
if let Ok(v) = request("/api/monitoring/status", "GET", None).await
|
||||
&& (v["error"].is_string()
|
||||
|| v["droppedObservations"].as_u64().unwrap_or(0) > 0)
|
||||
{
|
||||
message("告警监测异常:保存失败或接收队列溢出,请检查服务。", true);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
use leptos::prelude::*;
|
||||
mod geofences;
|
||||
mod map_settings;
|
||||
mod realtime_layout;
|
||||
mod realtime_ui;
|
||||
@@ -17,7 +18,8 @@ fn main() {
|
||||
mount_to_body(move || {
|
||||
view! {
|
||||
<div inner_html=include_str!("workspace.html")/>
|
||||
<section id="map-settings-view" class="workspace-pane" hidden inner_html=include_str!("map_settings.html")/>
|
||||
<section id="geofence-view" class="workspace-pane" tabindex="-1" aria-label="电子围栏" hidden inner_html=include_str!("geofences.html")/>
|
||||
<section id="map-settings-view" class="workspace-pane" tabindex="-1" aria-label="地图配置" hidden inner_html=include_str!("map_settings.html")/>
|
||||
<section id="workspace-content" class="workspace-pane">
|
||||
{if realtime { view! { <realtime_ui::Realtime/> }.into_any() }
|
||||
else { view! { <Registry/> }.into_any() }}
|
||||
@@ -25,6 +27,7 @@ fn main() {
|
||||
}
|
||||
});
|
||||
map_settings::init();
|
||||
geofences::init();
|
||||
workspace::init(realtime);
|
||||
if !realtime {
|
||||
registry::init();
|
||||
|
||||
@@ -125,6 +125,54 @@ fn update_buttons(s: &Shared) {
|
||||
state.estimate.is_none() || state.running || state.busy || !state.available,
|
||||
);
|
||||
disabled("map-download-cancel", !state.running);
|
||||
for id in [
|
||||
"map-west",
|
||||
"map-south",
|
||||
"map-east",
|
||||
"map-north",
|
||||
"map-min-zoom",
|
||||
"map-max-zoom",
|
||||
"map-region",
|
||||
"map-download-road",
|
||||
"map-download-imagery",
|
||||
] {
|
||||
disabled(id, state.running || state.busy);
|
||||
}
|
||||
for id in [
|
||||
"map-longitude",
|
||||
"map-latitude",
|
||||
"map-zoom",
|
||||
"map-basemap",
|
||||
"map-region-name",
|
||||
] {
|
||||
disabled(id, state.busy || state.prefs.is_none());
|
||||
}
|
||||
for action in [
|
||||
"reload",
|
||||
"region-save",
|
||||
"region-delete",
|
||||
"point",
|
||||
"current",
|
||||
"box",
|
||||
] {
|
||||
let lock = state.busy
|
||||
|| (state.prefs.is_none() && action != "reload")
|
||||
|| (action == "box" && state.running);
|
||||
if let Ok(buttons) = document().query_selector_all(&format!("[data-map-action={action}]")) {
|
||||
for i in 0..buttons.length() {
|
||||
if let Some(button) = buttons.item(i).and_then(|e| e.dyn_into::<Element>().ok()) {
|
||||
if lock {
|
||||
let _ = button.set_attribute("disabled", "");
|
||||
} else {
|
||||
let _ = button.remove_attribute("disabled");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if state.busy {
|
||||
map("tool", &json!(""));
|
||||
}
|
||||
}
|
||||
fn paint(s: &Shared) {
|
||||
let p = s.borrow().prefs.clone();
|
||||
@@ -325,6 +373,14 @@ async fn poll(s: Shared) {
|
||||
},
|
||||
);
|
||||
}
|
||||
} else {
|
||||
text(
|
||||
"map-network-note",
|
||||
"无法连接本机地图服务,请检查应用是否正在运行。连接恢复后会自动重试。",
|
||||
);
|
||||
if let Some(e) = el("map-network-note") {
|
||||
let _ = e.set_attribute("class", "map-network-note warning");
|
||||
}
|
||||
}
|
||||
match get("/api/maps/downloads").await {
|
||||
Ok(v) => {
|
||||
@@ -365,12 +421,17 @@ pub fn open() {
|
||||
if let Some(s) = slot.borrow().clone() {
|
||||
drawer(true);
|
||||
if s.borrow().prefs.is_none() {
|
||||
spawn_local(load(s));
|
||||
if !s.borrow().busy {
|
||||
s.borrow_mut().busy = true;
|
||||
update_buttons(&s);
|
||||
spawn_local(load(s));
|
||||
}
|
||||
} else {
|
||||
if !s.borrow().dirty {
|
||||
paint(&s);
|
||||
}
|
||||
if let Some(mut p) = s.borrow().prefs.clone() {
|
||||
let saved = p.clone();
|
||||
let candidate = (
|
||||
number("map-longitude"),
|
||||
number("map-latitude"),
|
||||
@@ -382,9 +443,14 @@ pub fn open() {
|
||||
p.latitude = candidate.1;
|
||||
p.zoom = candidate.2;
|
||||
}
|
||||
if p.valid() {
|
||||
map("open", &json!(p));
|
||||
if !p.valid() {
|
||||
p = saved;
|
||||
}
|
||||
let basemap = value("map-basemap");
|
||||
if matches!(basemap.as_str(), "road" | "imagery") {
|
||||
p.basemap = basemap;
|
||||
}
|
||||
map("open", &json!(p));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -420,6 +486,9 @@ pub fn init() {
|
||||
let Some(action) = b.get_attribute("data-map-action") else {
|
||||
return;
|
||||
};
|
||||
if b.has_attribute("disabled") {
|
||||
return;
|
||||
}
|
||||
let s = state.clone();
|
||||
match action.as_str() {
|
||||
"drawer" => {
|
||||
@@ -638,6 +707,12 @@ pub fn init() {
|
||||
let state = s.clone();
|
||||
let name = event.to_owned();
|
||||
let c = Closure::<dyn FnMut(web_sys::CustomEvent)>::new(move |e: web_sys::CustomEvent| {
|
||||
if name != "rid-map-error" && state.borrow().busy {
|
||||
return;
|
||||
}
|
||||
if name == "rid-map-bounds" && state.borrow().running {
|
||||
return;
|
||||
}
|
||||
let v = js_sys::JSON::stringify(&e.detail())
|
||||
.ok()
|
||||
.and_then(|s| s.as_string())
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
use super::target_lists::{Badge, Filter, Lists, Manager};
|
||||
use gloo_timers::future::TimeoutFuture;
|
||||
use leptos::prelude::*;
|
||||
use rid_shared::target_lists::{AlertTracker, ListKind};
|
||||
use rid_shared::target_lists::ListKind;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::{
|
||||
@@ -29,7 +29,13 @@ struct LiveEvent {
|
||||
message: String,
|
||||
}
|
||||
fn log_event(events: RwSignal<Vec<LiveEvent>>, message: String) {
|
||||
let time = js_sys::Date::new_0()
|
||||
log_event_at(events, message, None);
|
||||
}
|
||||
fn log_event_at(events: RwSignal<Vec<LiveEvent>>, message: String, occurred_at: Option<u64>) {
|
||||
let date = occurred_at
|
||||
.map(|ms| js_sys::Date::new(&JsValue::from_f64(ms as f64)))
|
||||
.unwrap_or_else(js_sys::Date::new_0);
|
||||
let time = date
|
||||
.to_time_string()
|
||||
.as_string()
|
||||
.unwrap_or_default()
|
||||
@@ -241,15 +247,8 @@ pub fn Realtime() -> impl IntoView {
|
||||
.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())
|
||||
@@ -273,6 +272,87 @@ pub fn Realtime() -> impl IntoView {
|
||||
gloo_timers::future::TimeoutFuture::new(5000).await;
|
||||
}
|
||||
});
|
||||
let alert_stop = stopped.clone();
|
||||
spawn_local(async move {
|
||||
let mut cursor = 0u64;
|
||||
let mut failed = false;
|
||||
let mut last_health = String::new();
|
||||
while !alert_stop.get() {
|
||||
let url = if cursor == 0 {
|
||||
"/api/monitoring/events?limit=64".into()
|
||||
} else {
|
||||
format!("/api/monitoring/events?after={cursor}&order=asc&limit=200")
|
||||
};
|
||||
let result = async {
|
||||
let response = gloo_net::http::Request::get(&url)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|_| ())?;
|
||||
if !response.ok() {
|
||||
return Err(());
|
||||
}
|
||||
response.json::<Value>().await.map_err(|_| ())
|
||||
}
|
||||
.await;
|
||||
match result {
|
||||
Ok(value) => {
|
||||
if let Some(entries) = value["entries"].as_array() {
|
||||
let mut entries = entries.clone();
|
||||
entries.sort_by_key(|e| e["id"].as_u64().unwrap_or(0));
|
||||
for entry in entries {
|
||||
let id = entry["id"].as_u64().unwrap_or(0);
|
||||
if id <= cursor {
|
||||
continue;
|
||||
}
|
||||
let target = entry["target_id"].as_str().unwrap_or("");
|
||||
let message = if entry["event_type"] == "blacklist" {
|
||||
format!("黑名单命中:{target}")
|
||||
} else {
|
||||
format!(
|
||||
"围栏进入:{target} · {}",
|
||||
entry["fence_name"].as_str().unwrap_or("")
|
||||
)
|
||||
};
|
||||
log_event_at(events, message, entry["occurred_at_ms"].as_u64());
|
||||
cursor = cursor.max(id);
|
||||
}
|
||||
failed = false;
|
||||
}
|
||||
}
|
||||
Err(()) => {
|
||||
if !failed {
|
||||
log_event(
|
||||
events,
|
||||
"告警读取失败,请检查本机服务;历史事件仍保留在服务端".into(),
|
||||
);
|
||||
failed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Ok(response) = gloo_net::http::Request::get("/api/monitoring/status")
|
||||
.send()
|
||||
.await
|
||||
&& let Ok(health) = response.json::<Value>().await
|
||||
{
|
||||
let warning = if health["error"].is_string()
|
||||
|| health["droppedObservations"].as_u64().unwrap_or(0) > 0
|
||||
{
|
||||
format!(
|
||||
"告警监测异常:{};累计丢失 {} 条告警输入,请检查服务。",
|
||||
health["error"].as_str().unwrap_or("接收队列溢出"),
|
||||
health["droppedObservations"].as_u64().unwrap_or(0)
|
||||
)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
if warning != last_health && !warning.is_empty() {
|
||||
log_event(events, warning.clone());
|
||||
}
|
||||
last_health = warning;
|
||||
}
|
||||
TimeoutFuture::new(1000).await;
|
||||
}
|
||||
});
|
||||
let worker_holder: Rc<RefCell<Option<web_sys::Worker>>> = Rc::new(RefCell::new(None));
|
||||
let stop = stopped.clone();
|
||||
let workers = worker_holder.clone();
|
||||
@@ -326,6 +406,15 @@ pub fn Realtime() -> impl IntoView {
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
// The module may load after the initial list effect has run.
|
||||
if let Ok(text) = serde_json::to_string(&classification.get_untracked())
|
||||
&& let Ok(value) = js_sys::JSON::parse(&text)
|
||||
{
|
||||
let _ = map_call(
|
||||
"setClassification",
|
||||
&[value, lists.filter.get_untracked().wire().into()],
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
TimeoutFuture::new(50).await;
|
||||
@@ -594,7 +683,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|{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>
|
||||
<ol class="live-events"><For each=move||events.get() key=|event|event.id children=move |event|{let alert=event.message.starts_with("黑名单命中:")||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>
|
||||
|
||||
@@ -5,6 +5,7 @@ use rid_shared::target_lists::{
|
||||
Entry, ListKind, MAX_NOTE_CHARS, Mutation, Snapshot, valid_target_id,
|
||||
};
|
||||
use serde_json::Value;
|
||||
use wasm_bindgen::JsCast;
|
||||
use wasm_bindgen_futures::spawn_local;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
@@ -62,6 +63,7 @@ pub(super) struct Lists {
|
||||
query: RwSignal<String>,
|
||||
manager_filter: RwSignal<Filter>,
|
||||
manager_page: RwSignal<usize>,
|
||||
return_focus: RwSignal<String>,
|
||||
draft_id: RwSignal<String>,
|
||||
draft_note: RwSignal<String>,
|
||||
draft_kind: RwSignal<ListKind>,
|
||||
@@ -82,6 +84,7 @@ impl Lists {
|
||||
query: RwSignal::new(String::new()),
|
||||
manager_filter: RwSignal::new(Filter::All),
|
||||
manager_page: RwSignal::new(0),
|
||||
return_focus: RwSignal::new(String::new()),
|
||||
draft_id: RwSignal::new(String::new()),
|
||||
draft_note: RwSignal::new(String::new()),
|
||||
draft_kind: RwSignal::new(ListKind::Black),
|
||||
@@ -144,9 +147,30 @@ impl Lists {
|
||||
})
|
||||
}
|
||||
pub fn show(self) {
|
||||
if !self.open.get_untracked() {
|
||||
let trigger = web_sys::window()
|
||||
.and_then(|w| w.document())
|
||||
.and_then(|d| d.active_element())
|
||||
.map(|e| e.id())
|
||||
.unwrap_or_default();
|
||||
self.return_focus.set(trigger);
|
||||
}
|
||||
self.open.set(true);
|
||||
super::realtime_layout::focus("rt-list-manager");
|
||||
}
|
||||
fn show_black(self) {
|
||||
self.manager_filter.set(Filter::Black);
|
||||
self.manager_page.set(0);
|
||||
self.query.set(String::new());
|
||||
if !self.editing.get_untracked()
|
||||
&& self.draft_id.get_untracked().is_empty()
|
||||
&& !self.busy.get_untracked()
|
||||
{
|
||||
self.draft_kind.set(ListKind::Black);
|
||||
}
|
||||
self.show();
|
||||
self.return_focus.set("rt-blacklist-menu".into());
|
||||
}
|
||||
pub fn close(self) {
|
||||
self.open.set(false);
|
||||
// Layout compactness is reconciled every 100 ms; choose a visible return
|
||||
@@ -165,7 +189,13 @@ impl Lists {
|
||||
}) {
|
||||
return;
|
||||
}
|
||||
for id in ["rt-list-manager-from-directory", "rt-list-manager-open"] {
|
||||
let preferred = self.return_focus.get_untracked();
|
||||
for id in [
|
||||
preferred.as_str(),
|
||||
"rt-list-manager-from-directory",
|
||||
"rt-list-manager-open",
|
||||
"rt-blacklist-menu",
|
||||
] {
|
||||
if let Some(element) = super::realtime_layout::element(id)
|
||||
.filter(|element| element.client_height() > 0)
|
||||
{
|
||||
@@ -338,6 +368,32 @@ pub(super) fn Manager(lists: Lists) -> impl IntoView {
|
||||
}
|
||||
});
|
||||
on_cleanup(move || escape.remove());
|
||||
let blacklist_menu = window_event_listener(leptos::ev::click, move |event| {
|
||||
let document = web_sys::window().and_then(|w| w.document());
|
||||
let realtime = document
|
||||
.as_ref()
|
||||
.and_then(|d| d.body())
|
||||
.is_some_and(|b| b.get_attribute("data-screen").as_deref() == Some("realtime"));
|
||||
if realtime
|
||||
&& event
|
||||
.target()
|
||||
.and_then(|e| e.dyn_into::<web_sys::Element>().ok())
|
||||
.and_then(|e| e.closest("#rt-blacklist-menu").ok().flatten())
|
||||
.is_some()
|
||||
{
|
||||
lists.show_black();
|
||||
}
|
||||
});
|
||||
on_cleanup(move || blacklist_menu.remove());
|
||||
Effect::new(move |_| {
|
||||
let expanded = lists.open.get();
|
||||
if let Some(button) = web_sys::window()
|
||||
.and_then(|w| w.document())
|
||||
.and_then(|d| d.get_element_by_id("rt-blacklist-menu"))
|
||||
{
|
||||
let _ = button.set_attribute("aria-expanded", &expanded.to_string());
|
||||
}
|
||||
});
|
||||
let rows = Memo::new(move |_| {
|
||||
let query = lists.query.get().to_lowercase();
|
||||
let filter = lists.manager_filter.get();
|
||||
@@ -361,8 +417,8 @@ pub(super) fn Manager(lists: Lists) -> impl IntoView {
|
||||
.min(rows.get().len().div_ceil(50).max(1) - 1)
|
||||
});
|
||||
view! {
|
||||
<aside id="rt-list-manager" tabindex="-1" class="rt-list-manager" aria-label="黑白名单管理" hidden=move||!lists.open.get()>
|
||||
<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>
|
||||
<aside id="rt-list-manager" tabindex="-1" class="rt-list-manager" aria-label=move||if lists.manager_filter.get()==Filter::Black{"黑名单管理"}else{"黑白名单管理"} hidden=move||!lists.open.get()>
|
||||
<header class="rt-list-manager-head"><h2>{move||if lists.manager_filter.get()==Filter::Black{"黑名单管理"}else{"黑白名单管理"}}</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||if lists.ready.get(){lists.snapshot.with(|s|s.entries.iter().filter(|entry|filter.matches(Some(entry.list_kind))).count()).to_string()}else{"—".into()}}</button>}).collect_view()}</div>
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -269,7 +269,7 @@ fn show(view: &str, realtime: bool) {
|
||||
.body()
|
||||
.and_then(|body| body.get_attribute("data-screen"));
|
||||
let view = match view {
|
||||
"register" | "realtime" | "settings" | "maps" => view,
|
||||
"register" | "realtime" | "settings" | "maps" | "geofences" => view,
|
||||
_ => "home",
|
||||
};
|
||||
if (view == "realtime" && !realtime) || (view == "register" && realtime) {
|
||||
@@ -285,12 +285,22 @@ fn show(view: &str, realtime: bool) {
|
||||
}
|
||||
hidden(
|
||||
"workspace-content",
|
||||
matches!(view, "home" | "settings" | "maps"),
|
||||
matches!(view, "home" | "settings" | "maps" | "geofences"),
|
||||
);
|
||||
hidden("geofence-view", view != "geofences");
|
||||
if view == "geofences" {
|
||||
crate::geofences::open();
|
||||
} else {
|
||||
crate::geofences::close();
|
||||
}
|
||||
hidden("appearance-view", view != "settings");
|
||||
hidden("map-settings-view", view != "maps");
|
||||
if view == "maps" {
|
||||
crate::map_settings::open();
|
||||
if let Some(region) = el("map-settings-view").and_then(|e| e.dyn_into::<HtmlElement>().ok())
|
||||
{
|
||||
let _ = region.focus();
|
||||
}
|
||||
} else {
|
||||
crate::map_settings::close();
|
||||
}
|
||||
@@ -312,6 +322,14 @@ fn show(view: &str, realtime: bool) {
|
||||
if let Some(body) = document().body() {
|
||||
let _ = body.set_attribute("data-screen", view);
|
||||
}
|
||||
hidden("rt-blacklist-menu", view != "realtime");
|
||||
if previous.as_deref() == Some("geofences")
|
||||
&& view == "realtime"
|
||||
&& let Some(region) = el("workspace-content").and_then(|e| e.dyn_into::<HtmlElement>().ok())
|
||||
{
|
||||
let _ = region.set_attribute("tabindex", "-1");
|
||||
let _ = region.focus();
|
||||
}
|
||||
text(
|
||||
"reference-title",
|
||||
match view {
|
||||
@@ -319,6 +337,7 @@ fn show(view: &str, realtime: bool) {
|
||||
"realtime" => "实时目标工作台",
|
||||
"settings" => "壁纸与外观",
|
||||
"maps" => "地图配置",
|
||||
"geofences" => "电子围栏",
|
||||
_ => "应用总览",
|
||||
},
|
||||
);
|
||||
@@ -340,7 +359,9 @@ fn show(view: &str, realtime: bool) {
|
||||
let _ = card.focus();
|
||||
}
|
||||
} else if previous.as_deref() == Some("home") {
|
||||
let region = if view == "settings" {
|
||||
let region = if view == "geofences" {
|
||||
"geofence-view"
|
||||
} else if view == "settings" {
|
||||
"appearance-view"
|
||||
} else {
|
||||
"workspace-content"
|
||||
@@ -470,6 +491,8 @@ pub fn init(realtime: bool) {
|
||||
show(
|
||||
if realtime {
|
||||
"realtime"
|
||||
} else if search.contains("app=geofences") {
|
||||
"geofences"
|
||||
} else if search.contains("app=register") {
|
||||
"register"
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user