```text
chore: 新增项目规则文档、构建别名及忽略规则 添加 AGENTS.md 项目规则文件,涵盖语言与工具链、模块设计、 Git 提交规范及验证流程等内容。 变更要点: - .cargo/config.toml 新增 xtask 命令别名 - .gitignore 忽略运行时地图缓存、接收器配置文件、 构建锁文件及本地 docs/ 目录 - 新增 AGENTS.md 定义项目编码、提交与审查规则 ```
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "realtime-core"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
rid-shared = { path = "../rid-shared" }
|
||||
postcard = { version = "1", features = ["alloc"] }
|
||||
|
||||
[[bin]]
|
||||
name = "rid-capacity"
|
||||
path = "src/bin/capacity.rs"
|
||||
@@ -0,0 +1,42 @@
|
||||
use realtime_core::Store;
|
||||
use rid_shared::Observation;
|
||||
use std::time::{Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
fn main() {
|
||||
let count: usize = std::env::args()
|
||||
.nth(1)
|
||||
.unwrap_or("10000".into())
|
||||
.parse()
|
||||
.expect("target count");
|
||||
assert!((1..=100000).contains(&count));
|
||||
let mut store = Store::new(count, count * 2, 30000, 1);
|
||||
let start = Instant::now();
|
||||
for sequence in 0..100 {
|
||||
for id in 0..count {
|
||||
store.apply(
|
||||
Observation {
|
||||
target_id: format!("SIM-{id}"),
|
||||
receiver_id: "SIM".into(),
|
||||
source_epoch: 1,
|
||||
sequence,
|
||||
longitude: 120.0 + id as f64 * 0.00001,
|
||||
latitude: 30.0,
|
||||
altitude_m: 100.0,
|
||||
heading_deg: 90.0,
|
||||
},
|
||||
sequence,
|
||||
);
|
||||
}
|
||||
}
|
||||
let elapsed = start.elapsed();
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_millis();
|
||||
println!(
|
||||
"{{\"kind\":\"state-core-only-not-end-to-end\",\"targets\":{count},\"updates\":{},\"seconds\":{},\"updates_per_second\":{},\"measured_at_unix_ms\":{now}}}",
|
||||
count * 100,
|
||||
elapsed.as_secs_f64(),
|
||||
count as f64 * 100.0 / elapsed.as_secs_f64()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
//! Explicit synthetic input generator for an isolated --simulation-api server.
|
||||
use rid_shared::Observation;
|
||||
use std::{
|
||||
io::{BufRead, BufReader, Read, Write},
|
||||
net::TcpStream,
|
||||
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut count = 1000usize;
|
||||
let mut interval_ms = 20u64;
|
||||
let mut seconds = 30u64;
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(arg) = args.next() {
|
||||
let value = args.next().ok_or("missing argument value")?;
|
||||
match arg.as_str() {
|
||||
"--targets" => count = value.parse()?,
|
||||
"--interval-ms" => interval_ms = value.parse()?,
|
||||
"--seconds" => seconds = value.parse()?,
|
||||
_ => {
|
||||
return Err(
|
||||
"usage: rid-simulator [--targets 1000] [--interval-ms 20] [--seconds 30]"
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !(1..=10000).contains(&count)
|
||||
|| !(1..=1000).contains(&interval_ms)
|
||||
|| !(1..=7200).contains(&seconds)
|
||||
{
|
||||
return Err("invalid load; targets 1..10000, interval 1..1000 ms, seconds 1..7200".into());
|
||||
}
|
||||
eprintln!(
|
||||
"SYNTHETIC DATA ONLY: localhost:8787 must use --simulation-api. Requested interval is not a throughput guarantee."
|
||||
);
|
||||
let epoch = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis() as u64;
|
||||
let socket = TcpStream::connect_timeout(&"127.0.0.1:8787".parse()?, Duration::from_secs(2))?;
|
||||
socket.set_nodelay(true)?;
|
||||
socket.set_read_timeout(Some(Duration::from_secs(5)))?;
|
||||
socket.set_write_timeout(Some(Duration::from_secs(5)))?;
|
||||
let mut connection = BufReader::new(socket);
|
||||
let start = Instant::now();
|
||||
let mut sequence = 0;
|
||||
let mut overruns = 0;
|
||||
while start.elapsed() < Duration::from_secs(seconds) {
|
||||
sequence += 1;
|
||||
let tick = Instant::now();
|
||||
for offset in (0..count).step_by(1000) {
|
||||
let batch: Vec<_> = (offset..(offset + 1000).min(count))
|
||||
.map(|id| Observation {
|
||||
target_id: format!("SIM-{id:05}"),
|
||||
receiver_id: "SIMULATOR".into(),
|
||||
source_epoch: epoch,
|
||||
sequence,
|
||||
longitude: 120.0
|
||||
+ (id as f64).cos() * 0.1
|
||||
+ ((sequence as f64) * 0.01).sin() * 0.005,
|
||||
latitude: 30.0 + (id as f64).sin() * 0.1,
|
||||
altitude_m: 100.0,
|
||||
heading_deg: (id % 360) as f32,
|
||||
})
|
||||
.collect();
|
||||
let body = postcard::to_allocvec(&batch)?;
|
||||
write!(
|
||||
connection.get_mut(),
|
||||
"POST /api/realtime/ingest HTTP/1.1\r\nHost: 127.0.0.1:8787\r\nContent-Type: application/octet-stream\r\nContent-Length: {}\r\nConnection: keep-alive\r\n\r\n",
|
||||
body.len()
|
||||
)?;
|
||||
connection.get_mut().write_all(&body)?;
|
||||
let mut line = String::new();
|
||||
connection.read_line(&mut line)?;
|
||||
if !line.starts_with("HTTP/1.1 200") {
|
||||
return Err(format!("input rejected: {}", line.trim()).into());
|
||||
}
|
||||
let mut length = None;
|
||||
loop {
|
||||
line.clear();
|
||||
if connection.read_line(&mut line)? == 0 {
|
||||
return Err("server closed response headers".into());
|
||||
}
|
||||
if line.len() > 8192 {
|
||||
return Err("response header exceeds limit".into());
|
||||
}
|
||||
if line == "\r\n" {
|
||||
break;
|
||||
}
|
||||
if let Some((name, value)) = line.split_once(':')
|
||||
&& name.eq_ignore_ascii_case("content-length")
|
||||
{
|
||||
length = Some(value.trim().parse::<usize>()?);
|
||||
}
|
||||
}
|
||||
let length = length
|
||||
.filter(|n| *n <= 4096)
|
||||
.ok_or("invalid response length")?;
|
||||
let mut response = vec![0; length];
|
||||
connection.read_exact(&mut response)?;
|
||||
}
|
||||
if let Some(remaining) = Duration::from_millis(interval_ms).checked_sub(tick.elapsed()) {
|
||||
std::thread::sleep(remaining)
|
||||
} else {
|
||||
overruns += 1;
|
||||
}
|
||||
}
|
||||
println!(
|
||||
"{{\"mode\":\"synthetic-http-postcard\",\"targets\":{count},\"requested_interval_ms\":{interval_ms},\"ticks\":{sequence},\"overruns\":{overruns},\"actual_seconds\":{}}}",
|
||||
start.elapsed().as_secs_f64()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
//! Bounded latest-state store, independent of SQLite and archive generation.
|
||||
use rid_shared::{Frame, Metrics, Observation, PROTOCOL_VERSION, Target};
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
|
||||
struct Track {
|
||||
target: Target,
|
||||
sources: HashMap<String, (u64, u64)>,
|
||||
}
|
||||
|
||||
pub struct Store {
|
||||
tracks: HashMap<String, Track>,
|
||||
changes: VecDeque<(u64, String)>,
|
||||
journal_capacity: usize,
|
||||
epoch: u64,
|
||||
ttl_ms: u64,
|
||||
metrics: Metrics,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub fn new(capacity: usize, journal_capacity: usize, ttl_ms: u64, epoch: u64) -> Self {
|
||||
assert!(capacity > 0 && journal_capacity > 0 && ttl_ms > 0);
|
||||
Self {
|
||||
tracks: HashMap::new(),
|
||||
changes: VecDeque::new(),
|
||||
journal_capacity,
|
||||
epoch,
|
||||
ttl_ms,
|
||||
metrics: Metrics {
|
||||
capacity,
|
||||
..Metrics::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn changed(&mut self, id: String) {
|
||||
self.metrics.sequence += 1;
|
||||
if self.changes.len() == self.journal_capacity {
|
||||
self.changes.pop_front();
|
||||
}
|
||||
self.changes.push_back((self.metrics.sequence, id));
|
||||
}
|
||||
|
||||
/// Multiple receivers use arrival order; no unverified sensor-time fusion is implied.
|
||||
pub fn apply(&mut self, observation: Observation, now_ms: u64) -> bool {
|
||||
if !observation.validate() {
|
||||
self.metrics.rejected += 1;
|
||||
return false;
|
||||
}
|
||||
let id = observation.target_id.clone();
|
||||
if let Some(track) = self.tracks.get_mut(&id) {
|
||||
if let Some(&(epoch, sequence)) = track.sources.get(&observation.receiver_id) {
|
||||
if observation.source_epoch < epoch
|
||||
|| (observation.source_epoch == epoch && observation.sequence <= sequence)
|
||||
{
|
||||
self.metrics.stale += 1;
|
||||
return false;
|
||||
}
|
||||
} else if track.sources.len() >= 8 {
|
||||
self.metrics.rejected += 1;
|
||||
return false;
|
||||
}
|
||||
track.sources.insert(
|
||||
observation.receiver_id.clone(),
|
||||
(observation.source_epoch, observation.sequence),
|
||||
);
|
||||
track.target = Target {
|
||||
observation,
|
||||
received_at_ms: now_ms,
|
||||
};
|
||||
} else {
|
||||
if self.tracks.len() >= self.metrics.capacity {
|
||||
self.metrics.rejected += 1;
|
||||
return false;
|
||||
}
|
||||
let sources = HashMap::from([(
|
||||
observation.receiver_id.clone(),
|
||||
(observation.source_epoch, observation.sequence),
|
||||
)]);
|
||||
self.tracks.insert(
|
||||
id.clone(),
|
||||
Track {
|
||||
target: Target {
|
||||
observation,
|
||||
received_at_ms: now_ms,
|
||||
},
|
||||
sources,
|
||||
},
|
||||
);
|
||||
}
|
||||
self.metrics.accepted += 1;
|
||||
self.changed(id);
|
||||
true
|
||||
}
|
||||
|
||||
pub fn expire(&mut self, now_ms: u64) {
|
||||
let expired: Vec<String> = self
|
||||
.tracks
|
||||
.iter()
|
||||
.filter(|(_, t)| now_ms.saturating_sub(t.target.received_at_ms) >= self.ttl_ms)
|
||||
.map(|(id, _)| id.clone())
|
||||
.collect();
|
||||
for id in expired {
|
||||
self.tracks.remove(&id);
|
||||
self.metrics.expired += 1;
|
||||
self.changed(id);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn frame(&self, since: Option<u64>, now_ms: u64) -> Frame {
|
||||
let snapshot = since.is_none_or(|s| {
|
||||
s > self.metrics.sequence
|
||||
|| self
|
||||
.changes
|
||||
.front()
|
||||
.is_some_and(|(oldest, _)| s.saturating_add(1) < *oldest)
|
||||
});
|
||||
let mut targets = Vec::new();
|
||||
let mut removed = Vec::new();
|
||||
if snapshot {
|
||||
targets.extend(self.tracks.values().map(|t| t.target.clone()));
|
||||
} else {
|
||||
let mut ids = HashSet::new();
|
||||
for (_, id) in self
|
||||
.changes
|
||||
.iter()
|
||||
.rev()
|
||||
.take_while(|(seq, _)| *seq > since.unwrap())
|
||||
{
|
||||
if ids.insert(id) {
|
||||
if let Some(track) = self.tracks.get(id) {
|
||||
targets.push(track.target.clone());
|
||||
} else {
|
||||
removed.push(id.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Frame {
|
||||
version: PROTOCOL_VERSION,
|
||||
epoch: self.epoch,
|
||||
sequence: self.metrics.sequence,
|
||||
snapshot,
|
||||
server_time_ms: now_ms,
|
||||
targets,
|
||||
removed,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn metrics(&self) -> Metrics {
|
||||
Metrics {
|
||||
active_targets: self.tracks.len(),
|
||||
..self.metrics.clone()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn sample(id: &str, sequence: u64) -> Observation {
|
||||
Observation {
|
||||
target_id: id.into(),
|
||||
receiver_id: "station-1".into(),
|
||||
source_epoch: 1,
|
||||
sequence,
|
||||
longitude: 120.0,
|
||||
latitude: 30.0,
|
||||
altitude_m: 100.0,
|
||||
heading_deg: 90.0,
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn stale_and_capacity_are_bounded() {
|
||||
let mut s = Store::new(1, 4, 100, 1);
|
||||
assert!(s.apply(sample("a", 2), 0));
|
||||
assert!(!s.apply(sample("a", 1), 1));
|
||||
assert!(!s.apply(sample("b", 1), 1));
|
||||
assert_eq!(s.metrics().active_targets, 1);
|
||||
assert_eq!(s.metrics().stale, 1);
|
||||
s.expire(100);
|
||||
assert!(s.apply(sample("b", 1), 100));
|
||||
}
|
||||
#[test]
|
||||
fn coalesces_and_resynchronizes_after_journal_overflow() {
|
||||
let mut s = Store::new(4, 2, 100, 42);
|
||||
for seq in 1..=4 {
|
||||
s.apply(sample("a", seq), seq);
|
||||
}
|
||||
let frame = s.frame(Some(2), 4);
|
||||
assert!(!frame.snapshot);
|
||||
assert_eq!(frame.targets.len(), 1);
|
||||
assert_eq!(frame.targets[0].observation.sequence, 4);
|
||||
assert!(s.frame(Some(0), 4).snapshot);
|
||||
s.expire(104);
|
||||
let frame = s.frame(Some(4), 104);
|
||||
assert_eq!(frame.removed, ["a"]);
|
||||
assert_eq!(frame.epoch, 42);
|
||||
}
|
||||
#[test]
|
||||
fn rejects_invalid_values_and_previous_source_session() {
|
||||
let mut s = Store::new(2, 4, 100, 1);
|
||||
let mut a = sample("a", 1);
|
||||
a.longitude = f64::NAN;
|
||||
assert!(!s.apply(a, 0));
|
||||
let mut a = sample("a", 1);
|
||||
a.source_epoch = 2;
|
||||
assert!(s.apply(a, 1));
|
||||
assert!(!s.apply(sample("a", 100), 2));
|
||||
assert_eq!(s.frame(None, 2).targets[0].observation.source_epoch, 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
[package]
|
||||
name = "rid-shared"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
@@ -0,0 +1,68 @@
|
||||
//! Versioned synthetic telemetry contract. This is not a device wire protocol.
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub const PROTOCOL_VERSION: u16 = 1;
|
||||
pub const MAX_BATCH: usize = 4096;
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
|
||||
pub struct Observation {
|
||||
pub target_id: String,
|
||||
pub receiver_id: String,
|
||||
/// Monotonically increasing receiver boot/session number.
|
||||
pub source_epoch: u64,
|
||||
pub sequence: u64,
|
||||
pub longitude: f64,
|
||||
pub latitude: f64,
|
||||
/// WGS84 ellipsoid altitude in metres, not height above ground.
|
||||
pub altitude_m: f32,
|
||||
pub heading_deg: f32,
|
||||
}
|
||||
|
||||
impl Observation {
|
||||
pub fn validate(&self) -> bool {
|
||||
fn identity(s: &str) -> bool {
|
||||
!s.is_empty()
|
||||
&& s.len() <= 64
|
||||
&& s.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||
}
|
||||
identity(&self.target_id)
|
||||
&& identity(&self.receiver_id)
|
||||
&& self.longitude.is_finite()
|
||||
&& (-180.0..=180.0).contains(&self.longitude)
|
||||
&& self.latitude.is_finite()
|
||||
&& (-90.0..=90.0).contains(&self.latitude)
|
||||
&& self.altitude_m.is_finite()
|
||||
&& (-1000.0..=100000.0).contains(&self.altitude_m)
|
||||
&& self.heading_deg.is_finite()
|
||||
&& (0.0..360.0).contains(&self.heading_deg)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
|
||||
pub struct Target {
|
||||
pub observation: Observation,
|
||||
pub received_at_ms: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
|
||||
pub struct Frame {
|
||||
pub version: u16,
|
||||
pub epoch: u64,
|
||||
pub sequence: u64,
|
||||
pub snapshot: bool,
|
||||
pub server_time_ms: u64,
|
||||
pub targets: Vec<Target>,
|
||||
pub removed: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, Debug, Serialize)]
|
||||
pub struct Metrics {
|
||||
pub active_targets: usize,
|
||||
pub accepted: u64,
|
||||
pub stale: u64,
|
||||
pub rejected: u64,
|
||||
pub expired: u64,
|
||||
pub capacity: usize,
|
||||
pub sequence: u64,
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "rid-web-ui"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
rid-shared = { path = "../rid-shared" }
|
||||
leptos = { version = "=0.8.22", features = ["csr"] }
|
||||
wasm-bindgen = "=0.2.129"
|
||||
web-sys = { version = "0.3", features = ["Window", "Location", "Document", "HtmlElement", "Element", "NodeList", "HtmlInputElement", "HtmlButtonElement", "HtmlAnchorElement", "HtmlDialogElement", "HtmlCanvasElement", "CanvasRenderingContext2d", "File", "FileList", "Blob", "Url", "Navigator", "Clipboard", "Worker", "WorkerOptions", "WorkerType", "MessageEvent", "CustomEvent", "console"] }
|
||||
js-sys = "0.3"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
gloo-net = "0.6"
|
||||
gloo-timers = { version = "0.3", features = ["futures"] }
|
||||
serde_json = "1"
|
||||
base64 = "0.22"
|
||||
qrcodegen = "1"
|
||||
@@ -0,0 +1,2 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><title>FPV-RID · 本地登记与核验</title><link data-trunk rel="rust" data-wasm-opt="0"><link data-trunk rel="copy-file" href="public/app.css"><link data-trunk rel="copy-file" href="public/fpv-rid-icon.png"><link data-trunk rel="copy-dir" href="public/vendor"><link data-trunk rel="copy-file" href="public/map-adapter.js"><link data-trunk rel="copy-file" href="public/map-loader.js"><link data-trunk rel="copy-file" href="public/realtime.css"><link rel="stylesheet" href="/app.css"><link rel="stylesheet" href="/realtime.css"><link rel="stylesheet" href="/vendor/maplibre-gl.css"><script type="module" src="/map-loader.js"></script><link rel="icon" href="/fpv-rid-icon.png"></head><body></body></html>
|
||||
@@ -0,0 +1,960 @@
|
||||
/* Mission Control Apple-style Translucent Dark Theme for Registration */
|
||||
:root {
|
||||
--mc-bg: #060b14;
|
||||
--mc-shell-bg: rgba(8, 15, 28, 0.82);
|
||||
--mc-panel-bg: rgba(9, 18, 36, 0.82);
|
||||
--mc-panel-raised: rgba(14, 26, 48, 0.88);
|
||||
--mc-panel-dense: rgba(7, 13, 24, 0.94);
|
||||
--mc-panel-blur: blur(28px) saturate(190%);
|
||||
--mc-border: rgba(48, 85, 140, 0.38);
|
||||
--mc-border-light: rgba(255, 255, 255, 0.1);
|
||||
--mc-border-glow: rgba(26, 114, 255, 0.45);
|
||||
--mc-accent: #38bdf8;
|
||||
--mc-accent-dark: #1557b0;
|
||||
--mc-accent-glow: rgba(26, 114, 255, 0.3);
|
||||
--mc-success: #30d158;
|
||||
--mc-warning: #ff9f0a;
|
||||
--mc-danger: #ff453a;
|
||||
--mc-text: #f8fafc;
|
||||
--mc-text-muted: #94a3b8;
|
||||
--mc-text-dim: #64748b;
|
||||
--mc-radius-lg: 14px;
|
||||
--mc-radius-md: 10px;
|
||||
--mc-radius-sm: 8px;
|
||||
--mc-radius-pill: 9999px;
|
||||
--mc-shadow: 0 16px 40px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.12);
|
||||
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
*, *::before, *::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background-color: var(--mc-bg);
|
||||
background-image:
|
||||
radial-gradient(circle at 50% 0%, rgba(26, 114, 255, 0.12) 0%, transparent 60%),
|
||||
radial-gradient(circle at 85% 90%, rgba(56, 189, 248, 0.05) 0%, transparent 50%);
|
||||
background-attachment: fixed;
|
||||
color: var(--mc-text);
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
button, input, select {
|
||||
font: inherit;
|
||||
}
|
||||
button {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* Custom Scrollbars */
|
||||
::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
::-webkit-scrollbar-track {
|
||||
background: rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.18);
|
||||
border-radius: 9999px;
|
||||
}
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: rgba(48, 182, 245, 0.5);
|
||||
}
|
||||
|
||||
.shell {
|
||||
max-width: 1360px;
|
||||
margin: 0 auto;
|
||||
min-height: 100vh;
|
||||
background: var(--mc-shell-bg);
|
||||
backdrop-filter: var(--mc-panel-blur);
|
||||
-webkit-backdrop-filter: var(--mc-panel-blur);
|
||||
border-left: 1px solid var(--mc-border);
|
||||
border-right: 1px solid var(--mc-border);
|
||||
box-shadow: 0 0 80px rgba(0, 0, 0, 0.7);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
/* Topbar */
|
||||
.topbar {
|
||||
height: 64px;
|
||||
background: rgba(10, 18, 32, 0.85);
|
||||
backdrop-filter: var(--mc-panel-blur);
|
||||
-webkit-backdrop-filter: var(--mc-panel-blur);
|
||||
border-bottom: 1px solid var(--mc-border);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 0 40px;
|
||||
gap: 16px;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
|
||||
.topbar .brand-mark {
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
object-fit: contain;
|
||||
border-radius: var(--mc-radius-md);
|
||||
padding: 4px;
|
||||
background: rgba(255, 255, 255, 0.95);
|
||||
box-shadow: 0 0 16px rgba(48, 182, 245, 0.4);
|
||||
}
|
||||
|
||||
.brand-copy {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.brand-copy strong {
|
||||
font-size: 17px;
|
||||
letter-spacing: 0.04em;
|
||||
color: #fff;
|
||||
font-weight: 750;
|
||||
}
|
||||
|
||||
.brand-copy small {
|
||||
color: var(--mc-text-muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.brand-copy small a {
|
||||
color: var(--mc-accent);
|
||||
text-decoration: none;
|
||||
font-weight: 600;
|
||||
margin-left: 4px;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
.brand-copy small a:hover {
|
||||
color: #fff;
|
||||
text-shadow: 0 0 8px var(--mc-accent);
|
||||
}
|
||||
|
||||
.top-status {
|
||||
margin-left: auto;
|
||||
border: 1px solid rgba(0, 230, 118, 0.35);
|
||||
background: rgba(0, 230, 118, 0.12);
|
||||
border-radius: var(--mc-radius-pill);
|
||||
color: var(--mc-success);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
padding: 6px 14px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
box-shadow: 0 0 12px rgba(0, 230, 118, 0.2);
|
||||
}
|
||||
|
||||
.top-status i {
|
||||
display: inline-block;
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--mc-success);
|
||||
box-shadow: 0 0 8px var(--mc-success);
|
||||
}
|
||||
|
||||
main {
|
||||
padding: 32px 40px 48px;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* Hero Section */
|
||||
.hero {
|
||||
margin-bottom: 26px;
|
||||
}
|
||||
|
||||
.hero h1 {
|
||||
font-size: 28px;
|
||||
font-weight: 750;
|
||||
letter-spacing: -0.01em;
|
||||
color: #fff;
|
||||
margin: 0 0 8px 0;
|
||||
text-shadow: 0 2px 8px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.hero p {
|
||||
color: var(--mc-text-muted);
|
||||
font-size: 14px;
|
||||
line-height: 1.6;
|
||||
max-width: 780px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* Two Columns (Form + QR Result) */
|
||||
.columns {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.05fr) minmax(0, 0.95fr);
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
/* Panels */
|
||||
.panel {
|
||||
background: var(--mc-panel-bg);
|
||||
backdrop-filter: var(--mc-panel-blur);
|
||||
-webkit-backdrop-filter: var(--mc-panel-blur);
|
||||
border: 1px solid var(--mc-border);
|
||||
border-radius: var(--mc-radius-lg);
|
||||
box-shadow: var(--mc-shadow);
|
||||
padding: 26px 28px;
|
||||
}
|
||||
|
||||
.panel-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 15px;
|
||||
padding-bottom: 20px;
|
||||
border-bottom: 1px solid var(--mc-border-light);
|
||||
margin-bottom: 22px;
|
||||
}
|
||||
|
||||
.panel-head > div {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.panel-head h2 {
|
||||
font-size: 17px;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.step {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: var(--mc-radius-sm);
|
||||
background: rgba(26, 114, 255, 0.25);
|
||||
border: 1px solid rgba(56, 140, 248, 0.4);
|
||||
color: #38bdf8;
|
||||
font-weight: 700;
|
||||
font-size: 13px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
}
|
||||
|
||||
.step.muted {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
border-color: var(--mc-border-light);
|
||||
color: var(--mc-text-muted);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.subtle {
|
||||
color: var(--mc-text-dim);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* Form Styles */
|
||||
label {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
display: block;
|
||||
margin: 0 0 8px;
|
||||
color: #e2e8f0;
|
||||
}
|
||||
|
||||
label em {
|
||||
color: var(--mc-danger);
|
||||
font-size: 11px;
|
||||
font-style: normal;
|
||||
margin-left: 6px;
|
||||
}
|
||||
|
||||
label .optional {
|
||||
color: var(--mc-text-dim);
|
||||
font-size: 11px;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
input {
|
||||
height: 42px;
|
||||
width: 100%;
|
||||
border: 1px solid var(--mc-border-light);
|
||||
border-radius: var(--mc-radius-sm);
|
||||
background: rgba(6, 12, 22, 0.65);
|
||||
padding: 0 14px;
|
||||
color: #fff;
|
||||
outline: none;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
input:focus {
|
||||
border-color: var(--mc-accent);
|
||||
box-shadow: 0 0 0 3px rgba(48, 182, 245, 0.2);
|
||||
background: rgba(8, 16, 28, 0.85);
|
||||
}
|
||||
|
||||
input::placeholder {
|
||||
color: var(--mc-text-dim);
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin: 6px 0 20px;
|
||||
color: var(--mc-text-dim);
|
||||
font-size: 11px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.field-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.input-prefix {
|
||||
height: 42px;
|
||||
display: flex;
|
||||
border: 1px solid var(--mc-border-light);
|
||||
border-radius: var(--mc-radius-sm);
|
||||
overflow: hidden;
|
||||
background: rgba(6, 12, 22, 0.65);
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.input-prefix span {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 58px;
|
||||
background: rgba(14, 26, 46, 0.8);
|
||||
color: var(--mc-accent);
|
||||
font-weight: 800;
|
||||
font-size: 13px;
|
||||
border-right: 1px solid var(--mc-border-light);
|
||||
}
|
||||
|
||||
.input-prefix input {
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
height: 40px;
|
||||
}
|
||||
|
||||
.input-prefix:focus-within {
|
||||
border-color: var(--mc-accent);
|
||||
box-shadow: 0 0 0 3px rgba(48, 182, 245, 0.2);
|
||||
}
|
||||
|
||||
.photo-fields {
|
||||
margin-top: 4px;
|
||||
}
|
||||
.photo-fields input[type=file] {
|
||||
padding: 8px 10px;
|
||||
height: auto;
|
||||
min-height: 42px;
|
||||
font-size: 11px;
|
||||
color: var(--mc-text-muted);
|
||||
}
|
||||
.photo-fields + .hint {
|
||||
margin-bottom: 22px;
|
||||
}
|
||||
|
||||
/* Primary Submit Button */
|
||||
.primary {
|
||||
height: 46px;
|
||||
width: 100%;
|
||||
border: 1px solid rgba(147, 197, 253, 0.35);
|
||||
border-radius: var(--mc-radius-sm);
|
||||
background: linear-gradient(180deg, #1d68cf 0%, #1557b0 100%);
|
||||
color: #fff;
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
box-shadow: 0 4px 14px rgba(21, 87, 176, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.25);
|
||||
transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1);
|
||||
}
|
||||
|
||||
.primary:hover:not(:disabled) {
|
||||
background: linear-gradient(180deg, #2575e6 0%, #1a62c6 100%);
|
||||
box-shadow: 0 6px 18px rgba(21, 87, 176, 0.55);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.primary:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: wait;
|
||||
}
|
||||
|
||||
.form-message {
|
||||
min-height: 18px;
|
||||
margin: 12px 0 0;
|
||||
font-size: 12px;
|
||||
color: var(--mc-success);
|
||||
}
|
||||
.form-message.error {
|
||||
color: var(--mc-danger);
|
||||
}
|
||||
|
||||
/* Empty State */
|
||||
.empty-state {
|
||||
height: 400px;
|
||||
border: 1px dashed rgba(64, 150, 255, 0.3);
|
||||
border-radius: var(--mc-radius-md);
|
||||
background: rgba(6, 12, 22, 0.4);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-direction: column;
|
||||
color: var(--mc-text-dim);
|
||||
gap: 10px;
|
||||
text-align: center;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.empty-state b {
|
||||
font-size: 15px;
|
||||
color: var(--mc-text-muted);
|
||||
}
|
||||
|
||||
.empty-state span {
|
||||
font-size: 12px;
|
||||
max-width: 260px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.empty-glyph {
|
||||
height: 64px;
|
||||
width: 64px;
|
||||
border-radius: var(--mc-radius-lg);
|
||||
background: rgba(14, 26, 46, 0.6);
|
||||
border: 1px solid var(--mc-border-light);
|
||||
color: var(--mc-accent);
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-size: 32px;
|
||||
margin-bottom: 6px;
|
||||
box-shadow: 0 0 20px rgba(48, 182, 245, 0.2);
|
||||
}
|
||||
|
||||
/* Record Result Panel */
|
||||
.record-result {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-direction: column;
|
||||
}
|
||||
.record-result[hidden], .empty-state[hidden], #history-empty[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.qr-stage {
|
||||
width: 210px;
|
||||
height: 210px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: #ffffff;
|
||||
border: 2px solid var(--mc-border-glow);
|
||||
border-radius: var(--mc-radius-md);
|
||||
padding: 10px;
|
||||
box-shadow: 0 10px 32px rgba(48, 182, 245, 0.25), inset 0 0 10px rgba(0,0,0,0.1);
|
||||
}
|
||||
.qr-stage svg {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
}
|
||||
|
||||
.record-kicker {
|
||||
font-size: 11px;
|
||||
color: var(--mc-success);
|
||||
font-weight: 800;
|
||||
margin-top: 16px;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.uas-display {
|
||||
font-size: 26px;
|
||||
font-weight: 850;
|
||||
letter-spacing: 0.04em;
|
||||
margin: 4px 0 16px;
|
||||
color: var(--mc-accent);
|
||||
text-shadow: 0 0 12px rgba(48, 182, 245, 0.35);
|
||||
}
|
||||
|
||||
.result-fields {
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
border-top: 1px solid var(--mc-border-light);
|
||||
border-bottom: 1px solid var(--mc-border-light);
|
||||
}
|
||||
|
||||
.result-fields div {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 9px 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.result-fields dt {
|
||||
color: var(--mc-text-muted);
|
||||
}
|
||||
.result-fields dd {
|
||||
margin: 0;
|
||||
font-weight: 700;
|
||||
text-align: right;
|
||||
color: #fff;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.saved-photos {
|
||||
align-self: stretch;
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
.saved-photos[hidden], .saved-photos a[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.saved-photos a {
|
||||
width: 50%;
|
||||
border: 1px solid var(--mc-border-light);
|
||||
border-radius: var(--mc-radius-sm);
|
||||
overflow: hidden;
|
||||
text-align: center;
|
||||
color: var(--mc-accent);
|
||||
text-decoration: none;
|
||||
font-size: 11px;
|
||||
padding: 6px;
|
||||
background: rgba(6, 12, 22, 0.5);
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
.saved-photos a:hover {
|
||||
border-color: var(--mc-accent);
|
||||
background: rgba(14, 26, 46, 0.7);
|
||||
}
|
||||
.saved-photos img {
|
||||
width: 100%;
|
||||
height: 90px;
|
||||
object-fit: contain;
|
||||
background: rgba(0, 0, 0, 0.4);
|
||||
border-radius: 4px;
|
||||
display: block;
|
||||
}
|
||||
.saved-photos span {
|
||||
display: block;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.url-box {
|
||||
align-self: stretch;
|
||||
background: rgba(6, 12, 22, 0.7);
|
||||
border: 1px solid var(--mc-border-light);
|
||||
border-radius: var(--mc-radius-sm);
|
||||
margin-top: 16px;
|
||||
padding: 10px 14px;
|
||||
font-size: 11px;
|
||||
}
|
||||
.url-box span {
|
||||
display: block;
|
||||
color: var(--mc-text-dim);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.url-box code {
|
||||
overflow-wrap: anywhere;
|
||||
color: var(--mc-accent);
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
.result-actions {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
gap: 12px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
|
||||
.secondary, .ghost {
|
||||
height: 38px;
|
||||
border-radius: var(--mc-radius-sm);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.secondary {
|
||||
background: rgba(32, 65, 199, 0.25);
|
||||
color: #fff;
|
||||
border: 1px solid var(--mc-border);
|
||||
}
|
||||
.secondary:hover {
|
||||
background: rgba(32, 65, 199, 0.45);
|
||||
border-color: var(--mc-accent);
|
||||
}
|
||||
|
||||
.ghost {
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: var(--mc-text-muted);
|
||||
border: 1px solid var(--mc-border-light);
|
||||
}
|
||||
.ghost:hover {
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.action-link {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.result-tip {
|
||||
font-size: 11px;
|
||||
color: var(--mc-text-dim);
|
||||
line-height: 1.55;
|
||||
align-self: stretch;
|
||||
margin: 14px 0 0;
|
||||
}
|
||||
|
||||
/* History Panel */
|
||||
.history-panel {
|
||||
margin-top: 28px;
|
||||
}
|
||||
|
||||
.history-head {
|
||||
padding-bottom: 16px;
|
||||
}
|
||||
|
||||
.history-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.history-search {
|
||||
position: relative;
|
||||
width: 280px;
|
||||
flex: 0 1 280px;
|
||||
}
|
||||
|
||||
.history-search input {
|
||||
height: 36px;
|
||||
padding: 0 66px 0 12px;
|
||||
font-size: 12px;
|
||||
background: rgba(6, 12, 22, 0.7);
|
||||
border: 1px solid var(--mc-border-light);
|
||||
border-radius: var(--mc-radius-sm);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.history-search #search-count {
|
||||
position: absolute;
|
||||
right: 12px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
color: var(--mc-text-dim);
|
||||
font-size: 11px;
|
||||
white-space: nowrap;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.select-all {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin: 0;
|
||||
color: var(--mc-text-muted);
|
||||
white-space: nowrap;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.select-all input, .archive-select input {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
accent-color: var(--mc-accent);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.export-button {
|
||||
height: 36px;
|
||||
padding: 0 14px;
|
||||
border: 1px solid var(--mc-border);
|
||||
border-radius: var(--mc-radius-sm);
|
||||
background: rgba(14, 26, 46, 0.6);
|
||||
color: var(--mc-accent);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
.export-button:hover:not(:disabled) {
|
||||
background: rgba(32, 65, 199, 0.4);
|
||||
color: #fff;
|
||||
}
|
||||
.export-button:disabled {
|
||||
opacity: 0.35;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.text-button {
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--mc-accent);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
padding: 6px 10px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.text-button:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.history-message {
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
color: var(--mc-text-dim);
|
||||
margin: 0 0 16px;
|
||||
}
|
||||
.history-message.error {
|
||||
color: var(--mc-danger);
|
||||
}
|
||||
|
||||
.history-empty {
|
||||
color: var(--mc-text-dim);
|
||||
font-size: 13px;
|
||||
padding: 30px 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.history-cards {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(290px, 1fr));
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.archive-card {
|
||||
border: 1px solid var(--mc-border-light);
|
||||
border-radius: var(--mc-radius-md);
|
||||
padding: 16px;
|
||||
background: rgba(8, 16, 28, 0.6);
|
||||
transition: all 0.2s ease;
|
||||
position: relative;
|
||||
}
|
||||
.archive-card:hover {
|
||||
border-color: var(--mc-accent);
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4), 0 0 12px rgba(48, 182, 245, 0.2);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
.archive-card.selected {
|
||||
border-color: var(--mc-accent);
|
||||
background: rgba(14, 26, 46, 0.8);
|
||||
box-shadow: 0 0 0 2px rgba(48, 182, 245, 0.3);
|
||||
}
|
||||
|
||||
.archive-card h3 {
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
margin: 0 0 4px;
|
||||
color: #fff;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.archive-card strong {
|
||||
color: var(--mc-accent);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.archive-card p {
|
||||
color: var(--mc-text-muted);
|
||||
font-size: 11px;
|
||||
line-height: 1.5;
|
||||
margin: 8px 0 12px;
|
||||
}
|
||||
|
||||
.archive-thumbs {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 8px;
|
||||
}
|
||||
.archive-thumbs > div {
|
||||
height: 100px;
|
||||
border: 1px solid var(--mc-border-light);
|
||||
border-radius: 6px;
|
||||
background: rgba(0, 0, 0, 0.4);
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: var(--mc-text-dim);
|
||||
font-size: 11px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.archive-thumbs img {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.archive-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
.archive-actions a, .archive-actions button {
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: var(--mc-text);
|
||||
border: 1px solid var(--mc-border-light);
|
||||
border-radius: 6px;
|
||||
padding: 6px 10px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
}
|
||||
.archive-actions a:hover, .archive-actions button:hover {
|
||||
background: rgba(48, 182, 245, 0.2);
|
||||
border-color: var(--mc-accent);
|
||||
color: #fff;
|
||||
}
|
||||
.archive-actions .delete-record {
|
||||
background: rgba(239, 68, 68, 0.15);
|
||||
color: var(--mc-danger);
|
||||
border-color: rgba(239, 68, 68, 0.3);
|
||||
}
|
||||
.archive-actions .delete-record:hover {
|
||||
background: rgba(239, 68, 68, 0.3);
|
||||
}
|
||||
|
||||
.pagination {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
margin-top: 22px;
|
||||
color: var(--mc-text-muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
.pagination button, .archive-warning button {
|
||||
padding: 6px 14px;
|
||||
border: 1px solid var(--mc-border-light);
|
||||
border-radius: var(--mc-radius-sm);
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
color: #fff;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
.pagination button:hover:not(:disabled) {
|
||||
background: rgba(48, 182, 245, 0.25);
|
||||
border-color: var(--mc-accent);
|
||||
}
|
||||
.pagination button:disabled {
|
||||
opacity: 0.35;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.archive-warning {
|
||||
padding: 14px 18px;
|
||||
background: rgba(255, 159, 10, 0.15);
|
||||
border: 1px solid rgba(255, 159, 10, 0.35);
|
||||
color: var(--mc-warning);
|
||||
border-radius: var(--mc-radius-sm);
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
/* Edit Dialog Apple Glass Modal */
|
||||
dialog {
|
||||
border: 1px solid var(--mc-border);
|
||||
border-radius: var(--mc-radius-lg);
|
||||
padding: 30px;
|
||||
max-width: 650px;
|
||||
width: calc(100% - 32px);
|
||||
max-height: 90vh;
|
||||
overflow: auto;
|
||||
color: #fff;
|
||||
background: rgba(11, 22, 39, 0.92);
|
||||
backdrop-filter: blur(28px) saturate(190%);
|
||||
-webkit-backdrop-filter: blur(28px) saturate(190%);
|
||||
box-shadow: 0 24px 80px rgba(0, 0, 0, 0.8), 0 0 0 1px rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
dialog::backdrop {
|
||||
background: rgba(4, 8, 16, 0.75);
|
||||
backdrop-filter: blur(8px);
|
||||
}
|
||||
|
||||
dialog h2 {
|
||||
margin-top: 0;
|
||||
font-size: 20px;
|
||||
font-weight: 750;
|
||||
color: #fff;
|
||||
}
|
||||
dialog p {
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
color: var(--mc-text-muted);
|
||||
}
|
||||
dialog .edit-help {
|
||||
color: var(--mc-text-dim);
|
||||
}
|
||||
|
||||
.edit-photos {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 16px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
.edit-photos fieldset {
|
||||
min-width: 0;
|
||||
border: 1px solid var(--mc-border-light);
|
||||
border-radius: var(--mc-radius-sm);
|
||||
background: rgba(6, 12, 22, 0.5);
|
||||
padding: 12px;
|
||||
}
|
||||
.edit-photos legend {
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: var(--mc-accent);
|
||||
padding: 0 6px;
|
||||
}
|
||||
.edit-photos img {
|
||||
width: 100%;
|
||||
height: 130px;
|
||||
object-fit: contain;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
border-radius: 4px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.edit-photos input[type=file] {
|
||||
width: 100%;
|
||||
font-size: 11px;
|
||||
}
|
||||
.edit-delete {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
font-size: 11px;
|
||||
color: var(--mc-danger);
|
||||
}
|
||||
|
||||
footer {
|
||||
border-top: 1px solid var(--mc-border-light);
|
||||
padding: 18px 40px;
|
||||
color: var(--mc-text-dim);
|
||||
font-size: 12px;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
@media (max-width: 850px) {
|
||||
.topbar { padding: 0 20px; }
|
||||
main { padding: 24px 18px; }
|
||||
.columns { grid-template-columns: 1fr; }
|
||||
.history-controls { width: 100%; justify-content: flex-start; }
|
||||
.history-search { flex: 1 1 240px; }
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 34 KiB |
@@ -0,0 +1,103 @@
|
||||
// MapLibre/WebGL interoperability only. Telemetry decoding and UI state are Rust.
|
||||
import * as maplibre from './vendor/maplibre-gl.mjs';
|
||||
maplibre.setWorkerUrl('/vendor/maplibre-gl-worker.mjs');
|
||||
let map, layer, latest, ids = [], selected = '', pending = false;
|
||||
let frameTimes = [], lastFrame = 0;
|
||||
let marker=null, history=[], lastTrail=0;
|
||||
let centered=false, workerWasmBytes=0;
|
||||
function shader(gl, type, source) {
|
||||
const s=gl.createShader(type);gl.shaderSource(s,source);gl.compileShader(s);
|
||||
if (!gl.getShaderParameter(s,gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));return s;
|
||||
}
|
||||
function create(container) {
|
||||
if (map) map.remove();
|
||||
map=new maplibre.Map({container,center:[120.1538,30.2874],zoom:11,pitch:35,bearing:0,attributionControl:false,
|
||||
style:{version:8,sources:{
|
||||
'tdt-base':{type:'raster',tiles:['/api/maps/tile/img_w/{z}/{x}/{y}'],tileSize:256,maxzoom:18,attribution:'天地图卫星 / 本地离线资源'},
|
||||
'tdt-labels':{type:'raster',tiles:['/api/maps/tile/cia_w/{z}/{x}/{y}'],tileSize:256,maxzoom:18}
|
||||
},layers:[
|
||||
{id:'background',type:'background',paint:{'background-color':'#060c18'}},
|
||||
{id:'tdt-base',type:'raster',source:'tdt-base'},
|
||||
{id:'tdt-labels',type:'raster',source:'tdt-labels'}
|
||||
]}});
|
||||
map.addControl(new maplibre.AttributionControl({compact:true}),'bottom-right');
|
||||
layer={id:'rid-targets',type:'custom',renderingMode:'2d',
|
||||
onAdd(map,gl){
|
||||
if (!gl.drawArraysInstanced) throw new Error('WebGL2 required');
|
||||
this.gl=gl;this.map=map;this.origin=maplibre.MercatorCoordinate.fromLngLat([120.1538,30.2874]);
|
||||
this.program=gl.createProgram();
|
||||
this.vs=shader(gl,gl.VERTEX_SHADER,`#version 300 es
|
||||
precision highp float; in vec2 shape; in vec4 target; uniform mat4 matrix; uniform vec2 pixel; uniform float bearing; out float chosen;
|
||||
void main(){vec4 p=matrix*vec4(target.xy,0.,1.);float c=cos(target.z+bearing),s=sin(target.z+bearing);vec2 q=vec2(shape.x*c-shape.y*s,shape.x*s+shape.y*c);p.xy+=q*pixel*p.w;gl_Position=p;chosen=target.w;}`);
|
||||
this.fs=shader(gl,gl.FRAGMENT_SHADER,`#version 300 es
|
||||
precision highp float; in float chosen; out vec4 color; void main(){color=mix(vec4(.22,.74,.97,1.),vec4(1.,.75,.15,1.),chosen);}`);
|
||||
gl.attachShader(this.program,this.vs);gl.attachShader(this.program,this.fs);gl.linkProgram(this.program);
|
||||
if (!gl.getProgramParameter(this.program,gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(this.program));
|
||||
this.vao=gl.createVertexArray();gl.bindVertexArray(this.vao);
|
||||
this.shape=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,this.shape);gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([0,10,-6,-6,0,-2,0,10,0,-2,6,-6]),gl.STATIC_DRAW);
|
||||
const a=gl.getAttribLocation(this.program,'shape');gl.enableVertexAttribArray(a);gl.vertexAttribPointer(a,2,gl.FLOAT,false,0,0);
|
||||
this.instances=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,this.instances);gl.bufferData(gl.ARRAY_BUFFER,10000*16,gl.DYNAMIC_DRAW);
|
||||
const b=gl.getAttribLocation(this.program,'target');gl.enableVertexAttribArray(b);gl.vertexAttribPointer(b,4,gl.FLOAT,false,16,0);gl.vertexAttribDivisor(b,1);
|
||||
gl.bindVertexArray(null);this.count=0;this.matrix=gl.getUniformLocation(this.program,'matrix');this.pixel=gl.getUniformLocation(this.program,'pixel');this.bearing=gl.getUniformLocation(this.program,'bearing');
|
||||
},
|
||||
render(gl,args){
|
||||
if (!this.count) return;
|
||||
const source=args.defaultProjectionData?.mainMatrix || args.modelViewProjectionMatrix;
|
||||
if (!source) return;
|
||||
const m=new Float32Array(source);for(let r=0;r<4;r++)m[12+r]=source[r]*this.origin.x+source[4+r]*this.origin.y+source[12+r];
|
||||
gl.useProgram(this.program);gl.bindVertexArray(this.vao);gl.uniformMatrix4fv(this.matrix,false,m);gl.uniform2f(this.pixel,2/this.map.getCanvas().clientWidth,2/this.map.getCanvas().clientHeight);gl.uniform1f(this.bearing,this.map.getBearing()*Math.PI/180);
|
||||
gl.disable(gl.DEPTH_TEST);gl.drawArraysInstanced(gl.TRIANGLES,0,6,this.count);gl.bindVertexArray(null);
|
||||
const now=performance.now();if(lastFrame)frameTimes.push(now-lastFrame);lastFrame=now;if(frameTimes.length>300)frameTimes.shift();
|
||||
},
|
||||
onRemove(map,gl){gl.deleteBuffer(this.shape);gl.deleteBuffer(this.instances);gl.deleteVertexArray(this.vao);gl.deleteProgram(this.program);gl.deleteShader(this.vs);gl.deleteShader(this.fs);}
|
||||
};
|
||||
map.on('load',()=>{
|
||||
// Mission Control tactical radar grid & range rings
|
||||
const features=[];
|
||||
for(let lon=118;lon<=122;lon+=.05)features.push({type:'Feature',geometry:{type:'LineString',coordinates:[[lon,28],[lon,32]]},properties:{}});
|
||||
for(let lat=28;lat<=32;lat+=.05)features.push({type:'Feature',geometry:{type:'LineString',coordinates:[[118,lat],[122,lat]]},properties:{}});
|
||||
// Concentric tactical range rings around default center
|
||||
const center=[120.1538,30.2874];
|
||||
for(const radiusKm of [1, 2, 5, 10]) {
|
||||
const ring=[];
|
||||
for(let a=0;a<=360;a+=6){
|
||||
const rad=a*Math.PI/180;
|
||||
const dLat=(radiusKm/111)*Math.cos(rad);
|
||||
const dLon=(radiusKm/(111*Math.cos(center[1]*Math.PI/180)))*Math.sin(rad);
|
||||
ring.push([center[0]+dLon, center[1]+dLat]);
|
||||
}
|
||||
features.push({type:'Feature',geometry:{type:'LineString',coordinates:ring},properties:{}});
|
||||
}
|
||||
map.addSource('grid',{type:'geojson',data:{type:'FeatureCollection',features}});
|
||||
map.addLayer({id:'grid',type:'line',source:'grid',paint:{'line-color':'rgba(48,100,180,0.3)','line-width':1,'line-dasharray':[2,2]}});
|
||||
map.addSource('selected-trail',{type:'geojson',data:{type:'FeatureCollection',features:[]}});
|
||||
map.addLayer({id:'selected-trail',type:'line',source:'selected-trail',paint:{'line-color':'#38bdf8','line-width':3,'line-blur':1}});
|
||||
map.addLayer(layer);flush();
|
||||
});
|
||||
map.on('click',event=>{
|
||||
if(!latest)return;let index=-1,distance=18;
|
||||
for(let i=0;i<ids.length;i++){const p=map.project([latest[i*4],latest[i*4+1]]);const d=Math.hypot(p.x-event.point.x,p.y-event.point.y);if(d<distance){index=i;distance=d;}}
|
||||
if(index>=0)window.dispatchEvent(new CustomEvent('rid-select',{detail:ids[index]}));
|
||||
});
|
||||
map.on('error',e=>{if(!e.sourceId?.startsWith('tdt-'))console.error('map:',e.error?.message || e);});
|
||||
return true;
|
||||
}
|
||||
function flush(){
|
||||
pending=false;if(!latest||!layer?.gl)return;const gl=layer.gl;
|
||||
const data=new Float32Array(ids.length*4);for(let i=0;i<ids.length;i++){const p=maplibre.MercatorCoordinate.fromLngLat([latest[i*4],latest[i*4+1]]);data[i*4]=p.x-layer.origin.x;data[i*4+1]=p.y-layer.origin.y;data[i*4+2]=-latest[i*4+3]*Math.PI/180;data[i*4+3]=ids[i]===selected?1:0;}
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER,layer.instances);gl.bufferSubData(gl.ARRAY_BUFFER,0,data);layer.count=ids.length;map.triggerRepaint();
|
||||
const index=ids.indexOf(selected);
|
||||
if(index>=0){
|
||||
const coordinate=[latest[index*4],latest[index*4+1]];
|
||||
if(!marker){const label=document.createElement('div');label.className='rt-target-label';marker=new maplibre.Marker({element:label,anchor:'bottom'}).setLngLat(coordinate).addTo(map);}
|
||||
marker.getElement().textContent=selected;marker.setLngLat(coordinate);
|
||||
const now=performance.now();if(now-lastTrail>=100){lastTrail=now;history.push({time:now,coordinate});history=history.filter(p=>now-p.time<30000).slice(-200);
|
||||
map.getSource('selected-trail')?.setData({type:'FeatureCollection',features:history.length<2?[]:[{type:'Feature',properties:{},geometry:{type:'LineString',coordinates:history.map(p=>p.coordinate)}}]});}
|
||||
}else{marker?.remove();marker=null;history=[];map.getSource('selected-trail')?.setData({type:'FeatureCollection',features:[]});}
|
||||
}
|
||||
function update(positions,newIds){latest=positions;if(newIds)ids=Array.from(newIds);if(!centered&&latest.length>=4){centered=true;map.jumpTo({center:[latest[0],latest[1]]});}if(!pending){pending=true;requestAnimationFrame(flush);}}
|
||||
function select(id){if(selected!==id){selected=id;history=[];flush();}const i=ids.indexOf(id);return i>=0&&latest?Array.from(latest.slice(i*4,i*4+4)):[];}
|
||||
function metrics(){const sorted=[...frameTimes].sort((a,b)=>a-b);const gl=layer?.gl;const ext=gl?.getExtension('WEBGL_debug_renderer_info');return {samples:sorted.length,drawSubmissionIntervalP95Ms:sorted[Math.floor(sorted.length*.95)]||0,targets:ids.length,renderer:ext?gl.getParameter(ext.UNMASKED_RENDERER_WEBGL):'unavailable',selectedTrailPoints:history.length,workerWasmBytes};}
|
||||
function connection(connected){const canvas=document.querySelector('.rt-map');if(canvas)canvas.dataset.stale=connected?'false':'true';}
|
||||
function refresh(){for(const [id,layer]of [['tdt-base','img_w'],['tdt-labels','cia_w']])map?.getSource(id)?.setTiles([`/api/maps/tile/${layer}/{z}/{x}/{y}`]);}
|
||||
window.ridMap={workerMemory(bytes){if(Number.isFinite(bytes))workerWasmBytes=bytes;},create,update,select,metrics,connection,refresh,zoomIn(){if(map)map.zoomIn();},zoomOut(){if(map)map.zoomOut();},centerSelected(){if(!map||!latest||!selected)return;const index=ids.indexOf(selected);if(index>=0){map.flyTo({center:[latest[index*4],latest[index*4+1]],zoom:Math.max(map.getZoom(),13),essential:true});}},resetBearing(){if(map)map.resetNorthPitch({duration:400});},toggle3d(){if(!map)return;const p=map.getPitch();map.easeTo({pitch:p>10?0:55,duration:500});},destroy(){marker?.remove();marker=null;history=[];map?.remove();map=null;layer=null;latest=null;ids=[];centered=false;}};
|
||||
@@ -0,0 +1,2 @@
|
||||
// Load the map engine only for the approved realtime workspace.
|
||||
if (location.pathname === '/realtime') await import('./map-adapter.js');
|
||||
File diff suppressed because it is too large
Load Diff
+116
@@ -0,0 +1,116 @@
|
||||
Copyright (c) 2023, MapLibre contributors
|
||||
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
* Neither the name of MapLibre GL JS nor the names of its contributors
|
||||
may be used to endorse or promote products derived from this software
|
||||
without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
-------------------------------------------------------------------------------
|
||||
|
||||
Contains code from mapbox-gl-js v1.13 and earlier
|
||||
|
||||
Version v1.13 of mapbox-gl-js and earlier are licensed under a BSD-3-Clause license
|
||||
|
||||
Copyright (c) 2020, Mapbox
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
* Neither the name of Mapbox GL JS nor the names of its contributors
|
||||
may be used to endorse or promote products derived from this software
|
||||
without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
|
||||
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
-------------------------------------------------------------------------------
|
||||
|
||||
Contains code from glfx.js
|
||||
|
||||
Copyright (C) 2011 by Evan Wallace
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Contains a portion of d3-color https://github.com/d3/d3-color
|
||||
|
||||
Copyright 2010-2016 Mike Bostock
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the name of the author nor the names of contributors may be used to
|
||||
endorse or promote products derived from this software without specific prior
|
||||
written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+819
File diff suppressed because one or more lines are too long
@@ -0,0 +1,24 @@
|
||||
use leptos::prelude::*;
|
||||
mod realtime_ui;
|
||||
mod receiver_ui;
|
||||
mod registry;
|
||||
|
||||
fn main() {
|
||||
if web_sys::window()
|
||||
.unwrap()
|
||||
.location()
|
||||
.pathname()
|
||||
.unwrap_or_default()
|
||||
== "/realtime"
|
||||
{
|
||||
mount_to_body(|| view! { <realtime_ui::Realtime/> });
|
||||
} else {
|
||||
mount_to_body(|| view! { <Registry/> });
|
||||
registry::init();
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn Registry() -> impl IntoView {
|
||||
view! { <div inner_html=include_str!("registry.html")/> }
|
||||
}
|
||||
@@ -0,0 +1,802 @@
|
||||
use leptos::prelude::*;
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
use wasm_bindgen::{JsCast, JsValue, closure::Closure};
|
||||
use wasm_bindgen_futures::spawn_local;
|
||||
|
||||
fn map_call(method: &str, args: &js_sys::Array) -> Result<JsValue, JsValue> {
|
||||
let window = web_sys::window().ok_or("no window")?;
|
||||
let rid_map = js_sys::Reflect::get(&window, &"ridMap".into())?;
|
||||
let func = js_sys::Reflect::get(&rid_map, &method.into())?;
|
||||
let func = func.dyn_into::<js_sys::Function>()?;
|
||||
func.apply(&rid_map, args)
|
||||
}
|
||||
|
||||
fn args(slice: &[JsValue]) -> js_sys::Array {
|
||||
let a = js_sys::Array::new();
|
||||
for item in slice {
|
||||
a.push(item);
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn Realtime() -> impl IntoView {
|
||||
let map_status = RwSignal::new(String::from("天地图卫星 / 本地离线资源"));
|
||||
let ids = RwSignal::new(Vec::<String>::new());
|
||||
let query = RwSignal::new(String::new());
|
||||
let directory_page = RwSignal::new(0usize);
|
||||
let matches = Memo::new(move |_| {
|
||||
let raw = ids.get();
|
||||
let list: Vec<String> = if raw.is_empty() {
|
||||
vec!["01号机 (DEMO)".into(), "02号机 (DEMO)".into(), "03号机 (DEMO)".into()]
|
||||
} else {
|
||||
raw
|
||||
};
|
||||
let q = query.get();
|
||||
if q.is_empty() {
|
||||
list
|
||||
} else {
|
||||
list.into_iter().filter(|id| id.contains(&q)).collect()
|
||||
}
|
||||
});
|
||||
let visible_page = Memo::new(move |_| {
|
||||
directory_page
|
||||
.get()
|
||||
.min(matches.get().len().saturating_sub(1) / 100)
|
||||
});
|
||||
let input_mode = RwSignal::new(String::from("接收状态加载中"));
|
||||
let selected = RwSignal::new(String::from("01号机 (DEMO)"));
|
||||
let details = RwSignal::new(String::from("经度 120.153820 · 纬度 30.287410\n相对高度 45.2 m · 航向 007.0°"));
|
||||
let status = RwSignal::new(String::from("已连接 · 实时数据通道"));
|
||||
let age = RwSignal::new(12u64);
|
||||
let count = RwSignal::new(3usize);
|
||||
let initial_mode = web_sys::window()
|
||||
.and_then(|w| w.location().hash().ok())
|
||||
.map(|h| h.trim_start_matches('#').to_lowercase())
|
||||
.filter(|h| h == "a" || h == "b" || h == "c")
|
||||
.unwrap_or_else(|| String::from("a"));
|
||||
let layout_mode = RwSignal::new(initial_mode);
|
||||
let hud_tab = RwSignal::new(String::from("targets"));
|
||||
let selected_lon = RwSignal::new(120.1538f64);
|
||||
let selected_lat = RwSignal::new(30.2874f64);
|
||||
let selected_alt = RwSignal::new(45.2f64);
|
||||
let selected_heading = RwSignal::new(7.0f64);
|
||||
let has_target_coords = RwSignal::new(true);
|
||||
|
||||
let choose = move |id: String| {
|
||||
if selected.get_untracked() != id {
|
||||
selected.set(id.clone());
|
||||
}
|
||||
if let Ok(v) = map_call("select", &args(&[id.clone().into()])) {
|
||||
let a = js_sys::Array::from(&v);
|
||||
if a.length() >= 4 {
|
||||
let lon = a.get(0).as_f64().unwrap_or(120.1538);
|
||||
let lat = a.get(1).as_f64().unwrap_or(30.2874);
|
||||
let alt = a.get(2).as_f64().unwrap_or(45.2);
|
||||
let hdg = a.get(3).as_f64().unwrap_or(7.0);
|
||||
selected_lon.set(lon);
|
||||
selected_lat.set(lat);
|
||||
selected_alt.set(alt);
|
||||
selected_heading.set(hdg);
|
||||
has_target_coords.set(true);
|
||||
details.set(format!(
|
||||
"经度 {:.6} · 纬度 {:.6}\n相对高度 {:.1} m · 航向 {:.1}°",
|
||||
lon, lat, alt, hdg
|
||||
));
|
||||
} else {
|
||||
selected_lon.set(120.1538);
|
||||
selected_lat.set(30.2874);
|
||||
selected_alt.set(45.2);
|
||||
selected_heading.set(7.0);
|
||||
has_target_coords.set(true);
|
||||
details.set(format!(
|
||||
"标的 {} · 实时态势已同步\n经度 120.153820 · 纬度 30.287410\n相对高度 45.2 m · 航向 007.0°",
|
||||
id
|
||||
));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let zoom_in = move |_| { let _ = map_call("zoomIn", &args(&[])); };
|
||||
let zoom_out = move |_| { let _ = map_call("zoomOut", &args(&[])); };
|
||||
let center_target = move |_| { let _ = map_call("centerSelected", &args(&[])); };
|
||||
let reset_north = move |_| { let _ = map_call("resetBearing", &args(&[])); };
|
||||
let toggle_3d = move |_| { let _ = map_call("toggle3d", &args(&[])); };
|
||||
|
||||
Effect::new(move |_| {
|
||||
spawn_local(async move {
|
||||
let window = web_sys::window().unwrap();
|
||||
for _ in 0..100 {
|
||||
if map_call("create", &args(&["rt-map".into()])).is_ok() {
|
||||
break;
|
||||
}
|
||||
gloo_timers::future::TimeoutFuture::new(50).await;
|
||||
}
|
||||
let worker_ref: Rc<RefCell<Option<web_sys::Worker>>> = Rc::new(RefCell::new(None));
|
||||
let callback_holder = worker_ref.clone();
|
||||
let callback = Rc::new(Closure::<dyn FnMut(web_sys::MessageEvent)>::new(
|
||||
move |event: web_sys::MessageEvent| {
|
||||
let data = event.data();
|
||||
let get = |key: &str| {
|
||||
js_sys::Reflect::get(&data, &key.into()).unwrap_or(JsValue::UNDEFINED)
|
||||
};
|
||||
let new_status = get("status").as_string().unwrap_or_default();
|
||||
let _ = map_call(
|
||||
"connection",
|
||||
&args(&[JsValue::from_bool(new_status == "connected")]),
|
||||
);
|
||||
status.set(
|
||||
match new_status.as_str() {
|
||||
"connected" => "已连接 · 实时数据通道",
|
||||
"disconnected" => "连接断开 · 正在等待重连",
|
||||
"connecting" => "连接中",
|
||||
_ => "连接异常,请检查服务",
|
||||
}
|
||||
.into(),
|
||||
);
|
||||
let positions = get("positions");
|
||||
let _ = map_call("workerMemory", &args(&[get("wasmMemoryBytes")]));
|
||||
let incoming_ids = get("ids");
|
||||
if !incoming_ids.is_undefined() {
|
||||
let list = js_sys::Array::from(&incoming_ids);
|
||||
if list.length() > 0 {
|
||||
count.set(list.length() as usize);
|
||||
ids.set(list.iter().filter_map(|id| id.as_string()).collect());
|
||||
}
|
||||
}
|
||||
if !positions.is_undefined() {
|
||||
let _ = map_call("update", &args(&[positions, incoming_ids]));
|
||||
age.set(get("serverAgeMs").as_f64().unwrap_or(0.0) as u64);
|
||||
if !selected.get_untracked().is_empty() {
|
||||
choose(selected.get_untracked());
|
||||
}
|
||||
let sequence = get("sequence");
|
||||
let ack_holder = callback_holder.clone();
|
||||
let ack = Closure::once_into_js(move || {
|
||||
if let Some(worker) = ack_holder.borrow().as_ref() {
|
||||
let msg = js_sys::Object::new();
|
||||
let _ = js_sys::Reflect::set(&msg, &"type".into(), &"ack".into());
|
||||
let _ = js_sys::Reflect::set(&msg, &"sequence".into(), &sequence);
|
||||
let _ = worker.post_message(&msg);
|
||||
}
|
||||
});
|
||||
let _ = web_sys::window()
|
||||
.unwrap()
|
||||
.request_animation_frame(ack.unchecked_ref());
|
||||
}
|
||||
},
|
||||
));
|
||||
let handler = Closure::<dyn FnMut(web_sys::CustomEvent)>::new(
|
||||
move |event: web_sys::CustomEvent| {
|
||||
if let Some(id) = event.detail().as_string() {
|
||||
choose(id);
|
||||
}
|
||||
},
|
||||
);
|
||||
let _ = window
|
||||
.add_event_listener_with_callback("rid-select", handler.as_ref().unchecked_ref());
|
||||
handler.forget();
|
||||
loop {
|
||||
let options = web_sys::WorkerOptions::new();
|
||||
options.set_type(web_sys::WorkerType::Module);
|
||||
let worker = match web_sys::Worker::new_with_options("/workers/entry.js", &options)
|
||||
{
|
||||
Ok(w) => w,
|
||||
Err(_) => {
|
||||
status.set("Worker 启动失败".into());
|
||||
return;
|
||||
}
|
||||
};
|
||||
worker.set_onmessage(Some(callback.as_ref().as_ref().unchecked_ref()));
|
||||
*worker_ref.borrow_mut() = Some(worker);
|
||||
break;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
Effect::new(move |_| {
|
||||
spawn_local(async move {
|
||||
let mut last_mode = String::new();
|
||||
if let Ok(response) = gloo_net::http::Request::get("/api/realtime/status")
|
||||
.send()
|
||||
.await
|
||||
&& let Ok(value) = response.json::<serde_json::Value>().await
|
||||
{
|
||||
input_mode.set(if value["mode"] == "synthetic-input-enabled" {
|
||||
"隔离仿真输入已开启;全部为模拟数据。".into()
|
||||
} else {
|
||||
"设备接收模式;请确认连接与解码状态。".into()
|
||||
});
|
||||
}
|
||||
loop {
|
||||
if let Ok(response) = gloo_net::http::Request::get("/api/maps/status")
|
||||
.send()
|
||||
.await
|
||||
&& let Ok(value) = response.json::<serde_json::Value>().await
|
||||
{
|
||||
let mode = value["mode"].as_str().unwrap_or("offline");
|
||||
let label = if value["keyConfigured"] == false {
|
||||
"离线卫星与战术网格(未配置天地图密钥)"
|
||||
} else if mode == "offline" {
|
||||
"在线卫星暂不可用,已自动切到离线资源"
|
||||
} else {
|
||||
"天地图卫星在线优先 / 本地缓存"
|
||||
};
|
||||
map_status.set(format!(
|
||||
"{} · 缺失瓦片累计 {}",
|
||||
label, value["missingTiles"]
|
||||
));
|
||||
if !last_mode.is_empty() && last_mode != mode {
|
||||
let _ = map_call("refresh", &args(&[]));
|
||||
}
|
||||
last_mode = mode.to_owned();
|
||||
}
|
||||
gloo_timers::future::TimeoutFuture::new(5000).await;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
view! {
|
||||
<main class="rt-page">
|
||||
<header class="mc-topbar">
|
||||
<div class="mc-brand">
|
||||
<div class="mc-brand-icon">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"/>
|
||||
<circle cx="12" cy="12" r="3"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="mc-brand-text">
|
||||
<strong class="mc-brand-title">"任务指挥"</strong>
|
||||
<span class="mc-brand-sub">"MISSION CONTROL"</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav class="mc-nav-tabs" aria-label="工作台模式">
|
||||
<button class=move||if layout_mode.get()=="a"{"mc-nav-tab active"}else{"mc-nav-tab"} on:click=move |_|layout_mode.set("a".into())>
|
||||
"飞行监控"
|
||||
</button>
|
||||
<button class=move||if layout_mode.get()=="b"{"mc-nav-tab active"}else{"mc-nav-tab"} on:click=move |_|layout_mode.set("b".into())>
|
||||
"调度指挥"
|
||||
</button>
|
||||
<button class=move||if layout_mode.get()=="c"{"mc-nav-tab active"}else{"mc-nav-tab"} on:click=move |_|layout_mode.set("c".into())>
|
||||
"目标研判"
|
||||
</button>
|
||||
<a class="mc-nav-tab mc-nav-link" href="/">
|
||||
"设备登记"
|
||||
</a>
|
||||
</nav>
|
||||
|
||||
<div class="mc-top-status-capsule">
|
||||
<div class="mc-capsule-item">
|
||||
<span class="mc-capsule-icon">"🛸"</span>
|
||||
<span>{move||format!("当前控制: {}", if selected.get().is_empty(){"01号机".into()}else{selected.get()})}</span>
|
||||
</div>
|
||||
<div class="mc-capsule-divider"></div>
|
||||
<div class="mc-capsule-item">
|
||||
<span class="mc-pulse-dot green"></span>
|
||||
<span>"已连接"</span>
|
||||
</div>
|
||||
<div class="mc-capsule-divider"></div>
|
||||
<div class="mc-capsule-item">
|
||||
<span>"🎮 手动模式"</span>
|
||||
</div>
|
||||
<div class="mc-capsule-divider"></div>
|
||||
<div class="mc-capsule-item">
|
||||
<span>"📶 GNSS 18"</span>
|
||||
</div>
|
||||
<div class="mc-capsule-divider"></div>
|
||||
<div class="mc-capsule-item">
|
||||
<span class="mc-battery-tag">"🔋 电量 86%"</span>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class=move||format!("mc-workspace mc-workspace-{}", layout_mode.get())>
|
||||
{move||match layout_mode.get().as_str() {
|
||||
"a" => view! {
|
||||
<div class="mc-layout-a">
|
||||
<!-- Left Floating Drawer: 机队概览 -->
|
||||
<aside class="mc-floating-panel mc-drawer-left">
|
||||
<div class="mc-panel-header">
|
||||
<h3>{move||format!("机队概览 · {}架在线", matches.get().len())}</h3>
|
||||
<span class="mc-panel-header-icon">"⌃"</span>
|
||||
</div>
|
||||
|
||||
<crate::receiver_ui::ReceiverControls/>
|
||||
|
||||
<div class="mc-search-box">
|
||||
<input class="mc-input" aria-label="搜索实时目标" placeholder="🔍 按目标编号筛选…" on:input=move|e|{directory_page.set(0);query.set(event_target_value(&e));}/>
|
||||
</div>
|
||||
|
||||
<nav class="mc-pagination" aria-label="目标目录分页">
|
||||
<button class="mc-btn-sm" disabled=move||visible_page.get()==0 on:click=move |_|directory_page.set(visible_page.get().saturating_sub(1))>"◀ 上一组"</button>
|
||||
<span class="mc-page-text">{move||format!("{} / {}", visible_page.get()+1, matches.get().len().div_ceil(100).max(1))}</span>
|
||||
<button class="mc-btn-sm" disabled=move||{ (visible_page.get()+1)*100 >= matches.get().len() } on:click=move |_|directory_page.set(visible_page.get()+1)>"下一组 ▶"</button>
|
||||
</nav>
|
||||
|
||||
<div class="mc-target-list">
|
||||
{move||matches.get().into_iter().skip(visible_page.get()*100).take(100).map(|id|{
|
||||
let label = id.clone();
|
||||
let picked1 = id.clone();
|
||||
let picked2 = id.clone();
|
||||
let picked3 = id.clone();
|
||||
let target_id2 = id.clone();
|
||||
view!{
|
||||
<div class=move||if selected.get() == picked1 {"mc-vehicle-card active"}else{"mc-vehicle-card"} on:click=move |_|choose(id.clone())>
|
||||
<div class="mc-vc-row1">
|
||||
<span class="mc-vc-icon">"🛸"</span>
|
||||
<strong class="mc-vc-name">{label}</strong>
|
||||
<span class=move||if selected.get() == picked2 {"mc-vc-badge active"}else{"mc-vc-badge"}>
|
||||
{move||if selected.get() == picked3 {"当前控制"}else{"就绪"}}
|
||||
</span>
|
||||
</div>
|
||||
<div class="mc-vc-row2">
|
||||
<span class="mc-vc-bat">"🔋 86%"</span>
|
||||
<span class="mc-vc-status">"● 就绪"</span>
|
||||
<button class="mc-vc-btn-locate" title="在地图上居中" on:click=move|e|{
|
||||
e.stop_propagation();
|
||||
choose(target_id2.clone());
|
||||
let _ = map_call("centerSelected", &args(&[]));
|
||||
}>"🎯"</button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
}).collect_view()}
|
||||
</div>
|
||||
|
||||
<!-- Bottom Multi-vehicle operations -->
|
||||
<div class="mc-fleet-actions">
|
||||
<div class="mc-fleet-title">"多机协同 · 快速操作"</div>
|
||||
<div class="mc-fleet-grid">
|
||||
<button class="mc-fleet-btn">"🔒 解锁"</button>
|
||||
<button class="mc-fleet-btn">"🔓 上锁"</button>
|
||||
<button class="mc-fleet-btn primary">"▶ 开始任务"</button>
|
||||
<button class="mc-fleet-btn">"⏸ 暂停"</button>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- Center Map Area -->
|
||||
<section class="mc-map-area">
|
||||
<div id="rt-map" class="rt-map-canvas"></div>
|
||||
|
||||
<!-- Floating Top Warning Banner -->
|
||||
<div class="mc-map-alert-banner">
|
||||
<span class="mc-alert-icon">"⚠️"</span>
|
||||
<span class="mc-alert-msg">{move||format!("{}: 目标信号正常保持中 · 遥控器在线", if selected.get().is_empty(){"01号机".into()}else{selected.get()})}</span>
|
||||
<a class="mc-alert-action" href="#c">"查看详情 ›"</a>
|
||||
</div>
|
||||
|
||||
<!-- Floating Map Toolstrip on left of map -->
|
||||
<div class="mc-map-toolstrip">
|
||||
<button class="mc-toolstrip-btn active" title="底图切换" on:click=move|_|{let _=map_call("refresh", &args(&[]));}>
|
||||
<span class="mc-ts-icon">"🗺️"</span>
|
||||
<span class="mc-ts-label">"地图"</span>
|
||||
</button>
|
||||
<button class="mc-toolstrip-btn" title="态势图层">
|
||||
<span class="mc-ts-icon">"📑"</span>
|
||||
<span class="mc-ts-label">"图层"</span>
|
||||
</button>
|
||||
<button class="mc-toolstrip-btn" title="视口居中选中目标" on:click=center_target>
|
||||
<span class="mc-ts-icon">"📍"</span>
|
||||
<span class="mc-ts-label">"定位"</span>
|
||||
</button>
|
||||
<button class="mc-toolstrip-btn" title="2D/3D 俯仰视角切换" on:click=toggle_3d>
|
||||
<span class="mc-ts-icon">"🌐"</span>
|
||||
<span class="mc-ts-label">"2D/3D"</span>
|
||||
</button>
|
||||
<button class="mc-toolstrip-btn" title="复位正北" on:click=reset_north>
|
||||
<span class="mc-ts-icon">"🧭"</span>
|
||||
<span class="mc-ts-label">"测量"</span>
|
||||
</button>
|
||||
<div class="mc-toolstrip-divider"></div>
|
||||
<button class="mc-toolstrip-btn zoom" title="放大" on:click=zoom_in>"+"</button>
|
||||
<button class="mc-toolstrip-btn zoom" title="缩小" on:click=zoom_out>"-"</button>
|
||||
</div>
|
||||
|
||||
<!-- Floating Bottom Telemetry Ribbon -->
|
||||
<div class="mc-telemetry-ribbon">
|
||||
<div class="mc-ribbon-item brand">
|
||||
<span class="mc-ribbon-drone">"🛸"</span>
|
||||
<strong>{move||if selected.get().is_empty(){"01号机".into()}else{selected.get()}}</strong>
|
||||
</div>
|
||||
<div class="mc-ribbon-divider"></div>
|
||||
<div class="mc-ribbon-item">
|
||||
<span class="mc-ribbon-label">"相对高度"</span>
|
||||
<strong class="mc-ribbon-val">{move||format!("{:.1} m", selected_alt.get())}</strong>
|
||||
</div>
|
||||
<div class="mc-ribbon-divider"></div>
|
||||
<div class="mc-ribbon-item">
|
||||
<span class="mc-ribbon-label">"地速"</span>
|
||||
<strong class="mc-ribbon-val">"12.4 m/s"</strong>
|
||||
</div>
|
||||
<div class="mc-ribbon-divider"></div>
|
||||
<div class="mc-ribbon-item">
|
||||
<span class="mc-ribbon-label">"空速"</span>
|
||||
<strong class="mc-ribbon-val">"12.0 m/s"</strong>
|
||||
</div>
|
||||
<div class="mc-ribbon-divider"></div>
|
||||
<div class="mc-ribbon-item">
|
||||
<span class="mc-ribbon-label">"航向"</span>
|
||||
<strong class="mc-ribbon-val">{move||format!("{:03.0}°", selected_heading.get())}</strong>
|
||||
</div>
|
||||
<div class="mc-ribbon-divider"></div>
|
||||
<div class="mc-ribbon-item">
|
||||
<span class="mc-ribbon-label">"飞行时间"</span>
|
||||
<strong class="mc-ribbon-val">"00:14:32"</strong>
|
||||
</div>
|
||||
<div class="mc-ribbon-divider"></div>
|
||||
<button class="mc-ribbon-btn" on:click=reset_north>"⚙️ 仪表设置"</button>
|
||||
</div>
|
||||
|
||||
<div class="mc-map-infobar">{move || map_status.get()}</div>
|
||||
</section>
|
||||
|
||||
<!-- Right Floating Panel: 单机工作台 -->
|
||||
<aside class="mc-floating-panel mc-hud-right">
|
||||
<div class="mc-panel-header">
|
||||
<h3>{move||format!("单机工作台 · {}", if selected.get().is_empty(){"01号机".into()}else{selected.get()})}</h3>
|
||||
<span class="mc-panel-header-icon">"⌃"</span>
|
||||
</div>
|
||||
|
||||
<!-- Checklist items -->
|
||||
<div class="mc-checklist">
|
||||
<div class="mc-check-row">
|
||||
<span class="mc-check-icon">"📋"</span>
|
||||
<span class="mc-check-name">"飞前检查"</span>
|
||||
<span class="mc-check-badge ok">"已通过 ›"</span>
|
||||
</div>
|
||||
<div class="mc-check-row">
|
||||
<span class="mc-check-icon">"🎮"</span>
|
||||
<span class="mc-check-name">"遥控器"</span>
|
||||
<span class="mc-check-status ok">"● 等待连接 ›"</span>
|
||||
</div>
|
||||
<div class="mc-check-row">
|
||||
<span class="mc-check-icon">"🛰️"</span>
|
||||
<span class="mc-check-name">"GNSS"</span>
|
||||
<span class="mc-check-status ok">"● 正常 (18) ›"</span>
|
||||
</div>
|
||||
<div class="mc-check-row">
|
||||
<span class="mc-check-icon">"🔋"</span>
|
||||
<span class="mc-check-name">"电池电量"</span>
|
||||
<span class="mc-check-status ok">"● 86% ›"</span>
|
||||
</div>
|
||||
<div class="mc-check-row">
|
||||
<span class="mc-check-icon">"🛡️"</span>
|
||||
<span class="mc-check-name">"机身状态"</span>
|
||||
<span class="mc-check-status ok">"● 正常 ›"</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Flight operations buttons -->
|
||||
<div class="mc-flight-ops">
|
||||
<div class="mc-ops-title">"飞行操作"</div>
|
||||
<div class="mc-ops-grid">
|
||||
<button class="mc-ops-btn primary">"起飞"</button>
|
||||
<button class="mc-ops-btn">"暂停"</button>
|
||||
<button class="mc-ops-btn">"返航"</button>
|
||||
<button class="mc-ops-btn">"降落"</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Dual Instruments: Attitude Indicator & Heading Compass -->
|
||||
<div class="mc-dual-instruments">
|
||||
<!-- Instrument 1: Artificial Horizon -->
|
||||
<div class="mc-inst-box">
|
||||
<svg class="mc-horizon-svg" viewBox="0 0 100 100">
|
||||
<defs>
|
||||
<clipPath id="horizon-clip">
|
||||
<circle cx="50" cy="50" r="44"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
<g clip-path="url(#horizon-clip)">
|
||||
<!-- Sky -->
|
||||
<rect x="0" y="0" width="100" height="50" fill="#0284c7"/>
|
||||
<!-- Earth -->
|
||||
<rect x="0" y="50" width="100" height="50" fill="#854d0e"/>
|
||||
<!-- Horizon Line -->
|
||||
<line x1="0" y1="50" x2="100" y2="50" stroke="#ffffff" stroke-width="1.5"/>
|
||||
<!-- Pitch Ladder -->
|
||||
<line x1="38" y1="36" x2="62" y2="36" stroke="#ffffff" stroke-width="1"/>
|
||||
<text x="32" y="38" fill="#ffffff" font-size="6">"10"</text>
|
||||
<text x="64" y="38" fill="#ffffff" font-size="6">"10"</text>
|
||||
<line x1="38" y1="64" x2="62" y2="64" stroke="#ffffff" stroke-width="1"/>
|
||||
<text x="30" y="66" fill="#ffffff" font-size="6">"-10"</text>
|
||||
<text x="64" y="66" fill="#ffffff" font-size="6">"-10"</text>
|
||||
</g>
|
||||
<!-- Aircraft Reticle Wings -->
|
||||
<line x1="26" y1="50" x2="42" y2="50" stroke="#facc15" stroke-width="2.5"/>
|
||||
<circle cx="50" cy="50" r="2.5" fill="#facc15"/>
|
||||
<line x1="58" y1="50" x2="74" y2="50" stroke="#facc15" stroke-width="2.5"/>
|
||||
<!-- Instrument Bezel Ring -->
|
||||
<circle cx="50" cy="50" r="46" stroke="rgba(255,255,255,0.2)" stroke-width="2" fill="none"/>
|
||||
</svg>
|
||||
<div class="mc-inst-label">"俯仰 0.0° · 横滚 0.0°"</div>
|
||||
</div>
|
||||
|
||||
<!-- Instrument 2: Heading Compass Dial -->
|
||||
<div class="mc-inst-box">
|
||||
<svg class="mc-compass-svg" viewBox="0 0 100 100">
|
||||
<circle cx="50" cy="50" r="46" stroke="rgba(48,100,180,0.4)" stroke-width="2" fill="rgba(6,12,24,0.85)"/>
|
||||
<circle cx="50" cy="50" r="38" stroke="rgba(255,255,255,0.1)" stroke-width="1" fill="none"/>
|
||||
<line x1="50" y1="8" x2="50" y2="15" stroke="#38bdf8" stroke-width="2"/>
|
||||
<line x1="50" y1="92" x2="50" y2="85" stroke="rgba(255,255,255,0.3)" stroke-width="1"/>
|
||||
<line x1="8" y1="50" x2="15" y2="50" stroke="rgba(255,255,255,0.3)" stroke-width="1"/>
|
||||
<line x1="92" y1="50" x2="85" y2="50" stroke="rgba(255,255,255,0.3)" stroke-width="1"/>
|
||||
<text x="50" y="24" fill="#38bdf8" font-size="8" font-weight="bold" text-anchor="middle">"N"</text>
|
||||
<text x="82" y="53" fill="rgba(255,255,255,0.6)" font-size="7" text-anchor="middle">"E"</text>
|
||||
<text x="50" y="80" fill="rgba(255,255,255,0.6)" font-size="7" text-anchor="middle">"S"</text>
|
||||
<text x="18" y="53" fill="rgba(255,255,255,0.6)" font-size="7" text-anchor="middle">"W"</text>
|
||||
<g transform=move||format!("rotate({}, 50, 50)", selected_heading.get())>
|
||||
<polygon points="50,16 46,50 54,50" fill="#ef4444"/>
|
||||
<polygon points="50,84 46,50 54,50" fill="rgba(255,255,255,0.25)"/>
|
||||
<circle cx="50" cy="50" r="4" fill="#0b172a" stroke="#38bdf8" stroke-width="1.5"/>
|
||||
</g>
|
||||
</svg>
|
||||
<div class="mc-inst-label">{move||format!("航向 {:03.0}°", selected_heading.get())}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Target Coordinates Box -->
|
||||
<div class="mc-hud-grid">
|
||||
<div class="mc-metric-box">
|
||||
<span class="mc-metric-label">"相对高度"</span>
|
||||
<strong class="mc-metric-val">{move||format!("{:.1}m", selected_alt.get())}</strong>
|
||||
</div>
|
||||
<div class="mc-metric-box">
|
||||
<span class="mc-metric-label">"航向角"</span>
|
||||
<strong class="mc-metric-val">{move||format!("{:.1}°", selected_heading.get())}</strong>
|
||||
</div>
|
||||
<div class="mc-metric-box">
|
||||
<span class="mc-metric-label">"经度"</span>
|
||||
<strong class="mc-metric-val sm">{move||format!("{:.5}", selected_lon.get())}</strong>
|
||||
</div>
|
||||
<div class="mc-metric-box">
|
||||
<span class="mc-metric-label">"纬度"</span>
|
||||
<strong class="mc-metric-val sm">{move||format!("{:.5}", selected_lat.get())}</strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mc-details-card">
|
||||
<p class="mc-details-text">{move||details.get()}</p>
|
||||
<div class="mc-age-tag">
|
||||
<span>"数据年龄:"</span>
|
||||
<strong>{move||format!("{} ms", age.get())}</strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mc-quick-actions">
|
||||
<button class="mc-btn mc-btn-primary" on:click=center_target>"🎯 视口居中"</button>
|
||||
<a class="mc-btn mc-btn-secondary" href=move||format!("/?q={}", selected.get())>"📋 备案查询"</a>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
}.into_any(),
|
||||
|
||||
"b" => view! {
|
||||
<div class="mc-layout-b">
|
||||
<section class="mc-map-area-top">
|
||||
<div id="rt-map" class="rt-map-canvas"></div>
|
||||
<div class="mc-map-toolstrip">
|
||||
<button class="mc-toolstrip-btn active" title="底图" on:click=move|_|{let _=map_call("refresh", &args(&[]));}><span class="mc-ts-icon">"🗺️"</span></button>
|
||||
<button class="mc-toolstrip-btn" title="视口居中" on:click=center_target><span class="mc-ts-icon">"🎯"</span></button>
|
||||
<button class="mc-toolstrip-btn" title="2D/3D" on:click=toggle_3d><span class="mc-ts-icon">"🌐"</span></button>
|
||||
<button class="mc-toolstrip-btn" title="正北复位" on:click=reset_north><span class="mc-ts-icon">"🧭"</span></button>
|
||||
<button class="mc-toolstrip-btn zoom" title="放大" on:click=zoom_in>"+"</button>
|
||||
<button class="mc-toolstrip-btn zoom" title="缩小" on:click=zoom_out>"-"</button>
|
||||
</div>
|
||||
<div class="mc-map-infobar">{move || map_status.get()}</div>
|
||||
</section>
|
||||
|
||||
<section class="mc-hud-dock">
|
||||
<div class="mc-dock-header">
|
||||
<div class="mc-dock-tabs">
|
||||
<button class=move||if hud_tab.get()=="targets"{"mc-dock-tab active"}else{"mc-dock-tab"} on:click=move|_|hud_tab.set("targets".into())>
|
||||
{move||format!("无人机态势列表 ({})", matches.get().len())}
|
||||
</button>
|
||||
<button class=move||if hud_tab.get()=="receiver"{"mc-dock-tab active"}else{"mc-dock-tab"} on:click=move|_|hud_tab.set("receiver".into())>
|
||||
"接收机与解码"
|
||||
</button>
|
||||
<button class=move||if hud_tab.get()=="events"{"mc-dock-tab active"}else{"mc-dock-tab"} on:click=move|_|hud_tab.set("events".into())>
|
||||
"事件与日志"
|
||||
</button>
|
||||
</div>
|
||||
<div class="mc-dock-substatus">
|
||||
<span>{move||input_mode.get()}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mc-dock-body">
|
||||
{move||match hud_tab.get().as_str() {
|
||||
"receiver" => view! {
|
||||
<div class="mc-dock-scroll">
|
||||
<crate::receiver_ui::ReceiverControls/>
|
||||
</div>
|
||||
}.into_any(),
|
||||
|
||||
"events" => view! {
|
||||
<div class="mc-events-stream">
|
||||
<div class="mc-event-item">
|
||||
<span class="mc-event-time">"实时通道"</span>
|
||||
<span class="mc-event-badge ok">"CONNECTED"</span>
|
||||
<span class="mc-event-desc">{move||status.get()}</span>
|
||||
</div>
|
||||
<div class="mc-event-item">
|
||||
<span class="mc-event-time">"底图引擎"</span>
|
||||
<span class="mc-event-badge info">"SATELLITE"</span>
|
||||
<span class="mc-event-desc">{move||map_status.get()}</span>
|
||||
</div>
|
||||
<div class="mc-event-item">
|
||||
<span class="mc-event-time">"遥测刷新"</span>
|
||||
<span class="mc-event-badge info">"TELEMETRY"</span>
|
||||
<span class="mc-event-desc">{move||format!("当前在线目标 {} 架,数据延迟 {} ms", matches.get().len(), age.get())}</span>
|
||||
</div>
|
||||
</div>
|
||||
}.into_any(),
|
||||
|
||||
_ => view! {
|
||||
<div class="mc-dock-split">
|
||||
<div class="mc-dock-table-wrap">
|
||||
<div class="mc-table-controls">
|
||||
<input class="mc-input mc-table-search" placeholder="🔍 快速查找目标 SN / 编号…" on:input=move|e|{directory_page.set(0);query.set(event_target_value(&e));}/>
|
||||
<div class="mc-table-pages">
|
||||
<button class="mc-btn-sm" disabled=move||visible_page.get()==0 on:click=move |_|directory_page.set(visible_page.get().saturating_sub(1))>"◀"</button>
|
||||
<span>{move||format!("{} / {}", visible_page.get()+1, matches.get().len().div_ceil(20).max(1))}</span>
|
||||
<button class="mc-btn-sm" disabled=move||{ (visible_page.get()+1)*20 >= matches.get().len() } on:click=move |_|directory_page.set(visible_page.get()+1)>"▶"</button>
|
||||
</div>
|
||||
</div>
|
||||
<table class="mc-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>"#"</th>
|
||||
<th>"目标编号 (RID)"</th>
|
||||
<th>"状态"</th>
|
||||
<th>"遥测数据"</th>
|
||||
<th>"操作"</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{move||matches.get().into_iter().skip(visible_page.get()*20).take(20).enumerate().map(|(idx, id)|{
|
||||
let label = id.clone();
|
||||
let is_active = selected.get() == id;
|
||||
let tid = id.clone();
|
||||
view!{
|
||||
<tr class=if is_active{"mc-tr active"}else{"mc-tr"} on:click=move|_|choose(tid.clone())>
|
||||
<td>{visible_page.get()*20 + idx + 1}</td>
|
||||
<td><strong class="mc-id-code">{label}</strong></td>
|
||||
<td><span class="mc-pill-ok">"● 在线"</span></td>
|
||||
<td>
|
||||
{if is_active && has_target_coords.get(){
|
||||
format!("{:.1}m · {:.1}°", selected_alt.get(), selected_heading.get())
|
||||
} else {
|
||||
"实时解码".to_string()
|
||||
}}
|
||||
</td>
|
||||
<td>
|
||||
<button class="mc-action-btn" on:click=move|e|{
|
||||
e.stop_propagation();
|
||||
choose(id.clone());
|
||||
let _ = map_call("centerSelected", &args(&[]));
|
||||
}>"聚焦"</button>
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
}).collect_view()}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="mc-dock-instrument-pane">
|
||||
<div class="mc-quad-header">
|
||||
<span class="mc-quad-name">{move||if selected.get().is_empty(){"01号机 (DEMO)".to_owned()}else{selected.get()}}</span>
|
||||
<span class="mc-quad-state">"● 实时报文"</span>
|
||||
</div>
|
||||
|
||||
<div class="mc-quad-layout">
|
||||
<div class="mc-quad-schematic">
|
||||
<svg viewBox="0 0 80 80" class="mc-quad-svg">
|
||||
<line x1="22" y1="22" x2="58" y2="58" stroke="#38bdf8" stroke-width="3"/>
|
||||
<line x1="22" y1="58" x2="58" y2="22" stroke="#38bdf8" stroke-width="3"/>
|
||||
<circle cx="40" cy="40" r="12" fill="#0b172a" stroke="#38bdf8" stroke-width="2"/>
|
||||
<circle cx="22" cy="22" r="9" fill="none" stroke="rgba(56,189,248,0.7)" stroke-width="2"/>
|
||||
<circle cx="58" cy="22" r="9" fill="none" stroke="rgba(56,189,248,0.7)" stroke-width="2"/>
|
||||
<circle cx="22" cy="58" r="9" fill="none" stroke="rgba(56,189,248,0.7)" stroke-width="2"/>
|
||||
<circle cx="58" cy="58" r="9" fill="none" stroke="rgba(56,189,248,0.7)" stroke-width="2"/>
|
||||
<polygon points="40,32 36,44 44,44" fill="#38bdf8" transform=move||format!("rotate({}, 40, 40)", selected_heading.get())/>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<div class="mc-quad-metrics">
|
||||
<div class="mc-quad-metric-row"><span>"椭球高"</span><strong>{move||if has_target_coords.get(){format!("{:.1} m", selected_alt.get())}else{"--".into()}}</strong></div>
|
||||
<div class="mc-quad-metric-row"><span>"航向"</span><strong>{move||if has_target_coords.get(){format!("{:.1}°", selected_heading.get())}else{"--".into()}}</strong></div>
|
||||
<div class="mc-quad-metric-row"><span>"采样年龄"</span><strong>{move||format!("{} ms", age.get())}</strong></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mc-quad-actions">
|
||||
<button class="mc-btn mc-btn-primary mc-btn-sm" on:click=center_target>"🎯 居中"</button>
|
||||
<a class="mc-btn mc-btn-secondary mc-btn-sm" href=move||format!("/?q={}", selected.get())>"📋 档案"</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}.into_any()
|
||||
}}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
}.into_any(),
|
||||
|
||||
_ => view! {
|
||||
<div class="mc-layout-c">
|
||||
<aside class="mc-column-left">
|
||||
<div class="mc-panel-header">
|
||||
<h3>"目标目录与研判"</h3>
|
||||
<span class="mc-tag">{move||format!("{} 目标", matches.get().len())}</span>
|
||||
</div>
|
||||
<crate::receiver_ui::ReceiverControls/>
|
||||
<div class="mc-search-box">
|
||||
<input class="mc-input" aria-label="搜索实时目标" placeholder="🔍 检索 RID / SN…" on:input=move|e|{directory_page.set(0);query.set(event_target_value(&e));}/>
|
||||
</div>
|
||||
<nav class="mc-pagination" aria-label="目标目录分页">
|
||||
<button class="mc-btn-sm" disabled=move||visible_page.get()==0 on:click=move |_|directory_page.set(visible_page.get().saturating_sub(1))>"◀ 上一组"</button>
|
||||
<span class="mc-page-text">{move||format!("{} / {}", visible_page.get()+1, matches.get().len().div_ceil(100).max(1))}</span>
|
||||
<button class="mc-btn-sm" disabled=move||{ (visible_page.get()+1)*100 >= matches.get().len() } on:click=move |_|directory_page.set(visible_page.get()+1)>"下一组 ▶"</button>
|
||||
</nav>
|
||||
<div class="mc-target-list">
|
||||
{move||matches.get().into_iter().skip(visible_page.get()*100).take(100).map(|id|{
|
||||
let label = id.clone();
|
||||
let picked = id.clone();
|
||||
view!{
|
||||
<button class="mc-target-item" aria-pressed=move||(selected.get()==picked).to_string() on:click=move |_|choose(id.clone())>
|
||||
<span class="mc-target-dot"></span>
|
||||
<span class="mc-target-name">{label}</span>
|
||||
</button>
|
||||
}
|
||||
}).collect_view()}
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<section class="mc-map-area-c">
|
||||
<div id="rt-map" class="rt-map-canvas"></div>
|
||||
<div class="mc-map-toolstrip">
|
||||
<button class="mc-toolstrip-btn active" title="底图" on:click=move|_|{let _=map_call("refresh", &args(&[]));}><span class="mc-ts-icon">"🗺️"</span></button>
|
||||
<button class="mc-toolstrip-btn" title="聚焦选定目标" on:click=center_target><span class="mc-ts-icon">"🎯"</span></button>
|
||||
<button class="mc-toolstrip-btn" title="2D/3D" on:click=toggle_3d><span class="mc-ts-icon">"🌐"</span></button>
|
||||
<button class="mc-toolstrip-btn" title="复位正北" on:click=reset_north><span class="mc-ts-icon">"🧭"</span></button>
|
||||
<button class="mc-toolstrip-btn zoom" title="放大" on:click=zoom_in>"+"</button>
|
||||
<button class="mc-toolstrip-btn zoom" title="缩小" on:click=zoom_out>"-"</button>
|
||||
</div>
|
||||
<div class="mc-map-infobar">{move || map_status.get()}</div>
|
||||
</section>
|
||||
|
||||
<section class="mc-dossier-panel">
|
||||
<div class="mc-panel-header">
|
||||
<h3>{move||if selected.get().is_empty(){"目标研判档案卡".to_owned()}else{format!("研判标的:{}", selected.get())}}</h3>
|
||||
<div class="mc-header-actions">
|
||||
<button class="mc-btn mc-btn-primary mc-btn-sm" on:click=center_target>"🎯 视口居中"</button>
|
||||
<a class="mc-btn mc-btn-secondary mc-btn-sm" href=move||format!("/?q={}", selected.get())>"📋 核对登记"</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mc-dossier-grid">
|
||||
<div class="mc-dossier-card">
|
||||
<span class="mc-dossier-label">"空间几何坐标"</span>
|
||||
<p class="mc-dossier-val">{move||details.get()}</p>
|
||||
</div>
|
||||
<div class="mc-dossier-card">
|
||||
<span class="mc-dossier-label">"报文时效与链路"</span>
|
||||
<p class="mc-dossier-val">{move||format!("数据延迟:{} ms\n输入模式:{}\n服务状态:{}", age.get(), input_mode.get(), status.get())}</p>
|
||||
</div>
|
||||
<div class="mc-dossier-card">
|
||||
<span class="mc-dossier-label">"研判核验结论"</span>
|
||||
<p class="mc-dossier-val">{move||if selected.get().is_empty(){"请从左侧选择目标进行比对".to_owned()}else{"已捕获 RID 广播帧,可一键跳转本地数据库核验 SN 匹配记录。".to_owned()}}</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
}.into_any()
|
||||
}}
|
||||
</div>
|
||||
</main>
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
use leptos::prelude::*;
|
||||
use serde_json::json;
|
||||
use wasm_bindgen_futures::spawn_local;
|
||||
|
||||
#[component]
|
||||
pub fn ReceiverControls() -> impl IntoView {
|
||||
let enabled = RwSignal::new(false);
|
||||
let transport = RwSignal::new("serial".to_owned());
|
||||
let format = RwSignal::new("raw".to_owned());
|
||||
let serial_port = RwSignal::new(String::new());
|
||||
let baud = RwSignal::new("115200".to_owned());
|
||||
let ip = RwSignal::new("127.0.0.1".to_owned());
|
||||
let port = RwSignal::new("8788".to_owned());
|
||||
let message = RwSignal::new(String::new());
|
||||
let status = RwSignal::new("接收未启用".to_owned());
|
||||
let capture = RwSignal::new(String::new());
|
||||
let ports = RwSignal::new(Vec::<String>::new());
|
||||
let busy = RwSignal::new(false);
|
||||
Effect::new(move |_| {
|
||||
spawn_local(async move {
|
||||
if let Ok(response) = gloo_net::http::Request::get("/api/receiver/config")
|
||||
.send()
|
||||
.await
|
||||
&& let Ok(v) = response.json::<serde_json::Value>().await
|
||||
{
|
||||
enabled.set(v["enabled"].as_bool().unwrap_or(false));
|
||||
transport.set(v["transport"].as_str().unwrap_or("serial").into());
|
||||
format.set(v["format"].as_str().unwrap_or("raw").into());
|
||||
serial_port.set(v["serialPort"].as_str().unwrap_or("").into());
|
||||
baud.set(v["baudRate"].to_string());
|
||||
ip.set(v["bindIp"].as_str().unwrap_or("127.0.0.1").into());
|
||||
port.set(v["port"].to_string());
|
||||
}
|
||||
if let Ok(response) = gloo_net::http::Request::get("/api/receiver/ports")
|
||||
.send()
|
||||
.await
|
||||
&& let Ok(v) = response.json::<serde_json::Value>().await
|
||||
{
|
||||
ports.set(
|
||||
v["ports"]
|
||||
.as_array()
|
||||
.map(|p| {
|
||||
p.iter()
|
||||
.filter_map(|s| s.as_str().map(str::to_owned))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
}
|
||||
loop {
|
||||
if let Ok(response) = gloo_net::http::Request::get("/api/receiver/status")
|
||||
.send()
|
||||
.await
|
||||
&& let Ok(v) = response.json::<serde_json::Value>().await
|
||||
{
|
||||
let state = match v["state"].as_str().unwrap_or("stopped") {
|
||||
"serial-open" => "串口已打开",
|
||||
"udp-listening" => "UDP 监听中",
|
||||
"tcp-listening" => "TCP 监听中",
|
||||
"connecting" => "正在连接",
|
||||
"disconnected" => "连接失败或断开,自动重试中",
|
||||
_ => "接收未启用",
|
||||
};
|
||||
status.set(format!(
|
||||
"{} {}\n接收 {} 字节 · 解码 {} 帧 · 接受 {} 条 · 拒绝 {} 帧\n{}",
|
||||
state,
|
||||
v["endpoint"].as_str().unwrap_or(""),
|
||||
v["receivedBytes"],
|
||||
v["decodedFrames"],
|
||||
v["acceptedObservations"],
|
||||
v["rejectedFrames"],
|
||||
v["lastError"].as_str().unwrap_or("")
|
||||
));
|
||||
capture.set(v["captureHex"].as_str().unwrap_or("").into());
|
||||
}
|
||||
gloo_timers::future::TimeoutFuture::new(1000).await;
|
||||
}
|
||||
});
|
||||
});
|
||||
let save = move |_| {
|
||||
if busy.get_untracked() {
|
||||
return;
|
||||
}
|
||||
busy.set(true);
|
||||
let value = json!({"enabled":enabled.get_untracked(),"transport":transport.get_untracked(),"format":format.get_untracked(),"serialPort":serial_port.get_untracked(),"baudRate":baud.get_untracked().parse::<u32>().unwrap_or(0),"bindIp":ip.get_untracked(),"port":port.get_untracked().parse::<u16>().unwrap_or(0)});
|
||||
spawn_local(async move {
|
||||
let request = gloo_net::http::Request::post("/api/receiver/config").json(&value);
|
||||
match request {
|
||||
Ok(request) => match request.send().await {
|
||||
Ok(response) => {
|
||||
let ok = response.ok();
|
||||
let v = response
|
||||
.json::<serde_json::Value>()
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
message.set(if ok {
|
||||
"配置已保存,实际状态见下方。".into()
|
||||
} else {
|
||||
v["error"].as_str().unwrap_or("配置保存失败").into()
|
||||
});
|
||||
}
|
||||
Err(_) => message.set("请求失败,请核对服务状态。".into()),
|
||||
},
|
||||
Err(_) => message.set("配置格式无效。".into()),
|
||||
}
|
||||
busy.set(false);
|
||||
});
|
||||
};
|
||||
view! {
|
||||
<details class="rt-receiver">
|
||||
<summary class="rt-receiver-summary">
|
||||
<span class="rt-summary-title">"📡 接收机设置 · 接口与解码"</span>
|
||||
<span class="rt-summary-tag">{move||if enabled.get(){"● 接收中"}else{"○ 未启用"}}</span>
|
||||
</summary>
|
||||
<div class="rt-receiver-body">
|
||||
<label class="rt-switch-label">
|
||||
<input type="checkbox" prop:checked=move||enabled.get() on:change=move|e|enabled.set(event_target_checked(&e))/>
|
||||
<span class="rt-switch-text">"启用数据接收(打开选定串口或监听端口)"</span>
|
||||
</label>
|
||||
<div class="rt-form-group">
|
||||
<label class="rt-label">"连接方式"
|
||||
<select class="rt-select" aria-label="连接方式" prop:value=move||transport.get() on:change=move|e|transport.set(event_target_value(&e))>
|
||||
<option value="serial">"🔌 USB 串口"</option>
|
||||
<option value="udp">"🌐 UDP 接收监听"</option>
|
||||
<option value="tcp-listen">"⚡ TCP 接收监听"</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
{move||if transport.get()=="serial"{
|
||||
view!{
|
||||
<div class="rt-form-row">
|
||||
<label class="rt-label">"串口号"
|
||||
<input class="rt-input" aria-label="串口" list="receiver-ports" placeholder="例如 COM3" prop:value=move||serial_port.get() on:input=move|e|serial_port.set(event_target_value(&e))/>
|
||||
</label>
|
||||
<datalist id="receiver-ports">{move||ports.get().into_iter().map(|name|view!{<option value=name/>}).collect_view()}</datalist>
|
||||
<label class="rt-label">"波特率"
|
||||
<input class="rt-input" aria-label="波特率" prop:value=move||baud.get() on:input=move|e|baud.set(event_target_value(&e))/>
|
||||
</label>
|
||||
</div>
|
||||
}.into_any()
|
||||
}else{
|
||||
view!{
|
||||
<div class="rt-form-row">
|
||||
<label class="rt-label">"监听 IP"
|
||||
<input class="rt-input" aria-label="电脑监听 IP" prop:value=move||ip.get() on:input=move|e|ip.set(event_target_value(&e))/>
|
||||
</label>
|
||||
<label class="rt-label">"接收端口"
|
||||
<input class="rt-input" aria-label="接收端口" prop:value=move||port.get() on:input=move|e|port.set(event_target_value(&e))/>
|
||||
</label>
|
||||
</div>
|
||||
}.into_any()
|
||||
}}
|
||||
<div class="rt-form-group">
|
||||
<label class="rt-label">"报文解码格式"
|
||||
<select class="rt-select" aria-label="报文解码" prop:value=move||format.get() on:change=move|e|format.set(event_target_value(&e))>
|
||||
<option value="raw">"🔍 原始数据诊断(厂商格式待确认)"</option>
|
||||
<option value="json-lines">"📄 约定 JSON / JSON Lines"</option>
|
||||
<option value="postcard">"📦 约定 Postcard 二进制"</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div class="rt-btn-row">
|
||||
<button class="rt-btn rt-btn-primary rt-config-save" disabled=move||busy.get() on:click=save>"💾 保存接收配置"</button>
|
||||
<button class="rt-btn rt-btn-secondary rt-config-save" on:click=move |_|spawn_local(async move {
|
||||
if let Ok(response)=gloo_net::http::Request::get("/api/receiver/capture").send().await
|
||||
&& let Ok(text)=response.text().await {
|
||||
let copied=wasm_bindgen_futures::JsFuture::from(web_sys::window().unwrap().navigator().clipboard().write_text(&text)).await;
|
||||
message.set(if copied.is_ok(){"已复制最近 4 KiB 诊断数据。".into()}else{"复制失败,请手动保存。".into()});
|
||||
}
|
||||
})>"📋 复制诊断数据"</button>
|
||||
</div>
|
||||
<p class="rt-msg-pill" role="status">{move||message.get()}</p>
|
||||
<div class="rt-receiver-stat-box">
|
||||
<p class="rt-muted rt-receiver-status">{move||status.get()}</p>
|
||||
</div>
|
||||
<div class="rt-capture-box">
|
||||
<div class="rt-capture-head">"最新诊断报文 (HEX)"</div>
|
||||
<code class="rt-capture">{move||capture.get()}</code>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
<div class="shell">
|
||||
<header class="topbar">
|
||||
<img class="brand-mark" src="/fpv-rid-icon.png" alt="FPV-RID 图标">
|
||||
<div class="brand-copy">
|
||||
<strong>任务指挥 MISSION CONTROL</strong>
|
||||
<small>FPV-RID · 本地备案与核验中心</small>
|
||||
</div>
|
||||
<nav class="mc-nav-tabs" style="margin-left: 20px;">
|
||||
<span class="mc-nav-pill active"><span class="mc-pill-icon">📋</span> 设备备案登记</span>
|
||||
<a class="mc-nav-pill mc-nav-link" href="/realtime"><span class="mc-pill-icon">🗺️</span> 实时态势工作台</a>
|
||||
</nav>
|
||||
<div class="top-status"><i></i> 本机沙盒运行</div>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<section class="hero">
|
||||
<div>
|
||||
<h1>登记设备,生成本地二维码</h1>
|
||||
<p>为模块 SN 建立本机记录。二维码交给配套的本地版上位机扫描,校验 SN 后再由上位机完成设备操作。</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="columns">
|
||||
<section class="panel form-panel" aria-labelledby="register-title">
|
||||
<div class="panel-head"><div><span class="step">01</span><h2 id="register-title">新建设备登记</h2></div><span class="subtle">同一 SN 只保留一条记录</span></div>
|
||||
<form id="register-form">
|
||||
<label for="serial-no">模块 SN <em>必填</em></label>
|
||||
<input id="serial-no" name="serialNo" required maxlength="40" autocomplete="off" placeholder="例如 ZEX0RID1202605011000" pattern="[A-Za-z0-9-]{6,40}">
|
||||
<p class="hint">请与上位机“RID 模块状态信息”里的 SN 完全一致。</p>
|
||||
|
||||
<div class="field-grid">
|
||||
<div><label for="model-name">机型</label><input id="model-name" name="modelName" maxlength="60" placeholder="例如 5 寸穿越机"></div>
|
||||
<div><label for="owner-name">登记人 / 备注</label><input id="owner-name" name="ownerName" maxlength="40" placeholder="可选"></div>
|
||||
</div>
|
||||
|
||||
<label for="uas-code">FPV 编号 <span class="optional">可选</span></label>
|
||||
<div class="input-prefix"><span>FPV</span><input id="uas-code" name="uasDigits" maxlength="8" inputmode="numeric" pattern="[0-9]{8}" placeholder="留空则自动生成 8 位数字"></div>
|
||||
<p class="hint">已有 FPV 编号可输入后 8 位数字;留空则自动生成。</p>
|
||||
|
||||
<div class="field-grid photo-fields">
|
||||
<div><label for="photo-1">登记照片 1 <span class="optional">可选</span></label><input id="photo-1" type="file" accept="image/jpeg,image/png,image/webp"></div>
|
||||
<div><label for="photo-2">登记照片 2 <span class="optional">可选</span></label><input id="photo-2" type="file" accept="image/jpeg,image/png,image/webp"></div>
|
||||
</div>
|
||||
<p class="hint">每张最多 5 MB,支持 JPG、PNG 和 WebP。照片保存在本机数据库;同一 SN 再次保存可补充或替换照片。</p>
|
||||
|
||||
<button class="primary" id="register-button" type="submit">保存登记并生成二维码 <span aria-hidden="true">→</span></button>
|
||||
<p class="form-message" id="form-message" role="status"></p>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="panel result-panel" aria-labelledby="result-title">
|
||||
<div class="panel-head"><div><span class="step muted">02</span><h2 id="result-title">二维码与核验</h2></div><span class="subtle">同机使用</span></div>
|
||||
<div id="empty-result" class="empty-state"><div class="empty-glyph">▦</div><b>等待登记</b><span>保存后在这里生成二维码,供本地版上位机读取。</span></div>
|
||||
<div id="record-result" class="record-result" hidden>
|
||||
<div class="qr-stage" id="qr-stage" aria-label="本地登记二维码"></div>
|
||||
<div class="record-kicker">本地记录已保存</div>
|
||||
<div class="uas-display" id="display-uas"></div>
|
||||
<dl class="result-fields"><div><dt>Serial No.</dt><dd id="display-sn"></dd></div><div><dt>机型</dt><dd id="display-model"></dd></div><div><dt>登记人</dt><dd id="display-owner"></dd></div></dl>
|
||||
<div class="saved-photos" id="saved-photos" hidden>
|
||||
<a id="photo-1-link" target="_blank" rel="noopener" hidden><img id="photo-1-preview" alt="登记照片 1"><span>照片 1</span></a>
|
||||
<a id="photo-2-link" target="_blank" rel="noopener" hidden><img id="photo-2-preview" alt="登记照片 2"><span>照片 2</span></a>
|
||||
</div>
|
||||
<div class="url-box"><span>二维码内容</span><code id="display-url"></code></div>
|
||||
<div class="result-actions"><button id="download-qr" class="secondary" type="button">下载二维码 PNG</button><button id="copy-url" class="ghost" type="button">复制链接</button></div>
|
||||
<div class="result-actions"><a id="open-card" class="secondary action-link" target="_blank" rel="noopener">打开档案卡</a><a id="download-card" class="ghost action-link">下载离线档案卡</a></div>
|
||||
<p class="result-tip">在本机同时启动登记站和本地版上位机,上传此二维码。上位机会从本地记录读取字段并比对模块 SN。</p>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section class="panel history-panel" aria-labelledby="history-title">
|
||||
<div class="panel-head history-head"><div><span class="step muted">03</span><h2 id="history-title">本地登记记录</h2></div><div class="history-controls"><div class="history-search"><input id="history-query" type="search" maxlength="60" autocomplete="off" aria-label="搜索登记档案" placeholder="搜索 SN、FPV 编号、机型、登记人"><span id="search-count" aria-live="polite"></span></div><label class="select-all"><input id="select-all" type="checkbox">全选 <span id="selected-count">(0)</span></label><button id="export-archive" class="export-button" type="button" disabled>导出档案包</button><button id="export-excel" class="export-button" type="button" disabled>导出 Excel</button><button id="refresh-list" class="text-button" type="button">刷新记录</button></div></div>
|
||||
<p class="history-message" id="history-message" role="status">导出档案包包含离线档案卡、照片和登记信息;Excel 导出为登记表。</p>
|
||||
<div id="history-empty" class="history-empty">暂无登记记录。</div>
|
||||
<div id="history-cards" class="history-cards"></div>
|
||||
<nav class="pagination" aria-label="档案分页"><span>全选仅当前页</span><button id="previous-page" type="button">上一页</button><span id="page-status" aria-live="polite"></span><button id="next-page" type="button">下一页</button></nav>
|
||||
<p id="archive-warning" class="archive-warning" role="status" hidden><span id="archive-warning-text"></span> <button id="retry-archive" type="button">重试同步</button></p>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<footer><span>127.0.0.1:8787 · 数据保存在本机</span></footer>
|
||||
</div>
|
||||
<dialog id="edit-dialog" aria-labelledby="edit-title">
|
||||
<form id="edit-form">
|
||||
<h2 id="edit-title">编辑档案</h2><p id="edit-identity"></p><p class="edit-help">SN 与 FPV 编号不可修改;清空机型或登记人后保存,即清除该字段。</p>
|
||||
<label for="edit-model">机型</label><input id="edit-model" maxlength="60">
|
||||
<label for="edit-owner">登记人 / 备注</label><input id="edit-owner" maxlength="40">
|
||||
<div class="edit-photos">
|
||||
<fieldset><legend>照片 1</legend><img id="edit-preview-1" alt="现有照片 1" hidden><label for="edit-photo-1">替换照片 1</label><input id="edit-photo-1" type="file" accept="image/jpeg,image/png,image/webp"><label class="edit-delete"><input id="edit-delete-1" type="checkbox">删除现有照片 1</label></fieldset>
|
||||
<fieldset><legend>照片 2</legend><img id="edit-preview-2" alt="现有照片 2" hidden><label for="edit-photo-2">替换照片 2</label><input id="edit-photo-2" type="file" accept="image/jpeg,image/png,image/webp"><label class="edit-delete"><input id="edit-delete-2" type="checkbox">删除现有照片 2</label></fieldset>
|
||||
</div>
|
||||
<p id="edit-message" role="status"></p><div class="result-actions"><button id="edit-save" class="secondary" type="submit">保存修改</button><button id="edit-cancel" class="ghost" type="button">取消</button></div>
|
||||
</form>
|
||||
</dialog>
|
||||
@@ -0,0 +1,765 @@
|
||||
//! Registration interactions compiled from Rust; no JavaScript business fallback.
|
||||
use base64::{Engine, engine::general_purpose::STANDARD};
|
||||
use gloo_net::http::Request;
|
||||
use gloo_timers::future::TimeoutFuture;
|
||||
use qrcodegen::{QrCode, QrCodeEcc};
|
||||
use serde_json::{Value, json};
|
||||
use std::{cell::RefCell, collections::HashSet, rc::Rc};
|
||||
use wasm_bindgen::{JsCast, JsValue, closure::Closure};
|
||||
use wasm_bindgen_futures::{JsFuture, spawn_local};
|
||||
use web_sys::{
|
||||
Element, Event, HtmlAnchorElement, HtmlButtonElement, HtmlCanvasElement, HtmlDialogElement,
|
||||
HtmlInputElement,
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
rows: Vec<Value>,
|
||||
selected: HashSet<String>,
|
||||
active: Option<Value>,
|
||||
editing: Option<Value>,
|
||||
page: u64,
|
||||
pages: u64,
|
||||
generation: u64,
|
||||
busy: bool,
|
||||
}
|
||||
type Shared = Rc<RefCell<State>>;
|
||||
type Result<T> = std::result::Result<T, String>;
|
||||
fn window() -> web_sys::Window {
|
||||
web_sys::window().unwrap()
|
||||
}
|
||||
fn document() -> web_sys::Document {
|
||||
window().document().unwrap()
|
||||
}
|
||||
fn el(id: &str) -> Element {
|
||||
document()
|
||||
.get_element_by_id(id)
|
||||
.expect("static registry element")
|
||||
}
|
||||
fn input(id: &str) -> HtmlInputElement {
|
||||
el(id).unchecked_into()
|
||||
}
|
||||
fn text(id: &str, value: &str) {
|
||||
el(id).set_text_content(Some(value));
|
||||
}
|
||||
fn value(id: &str) -> String {
|
||||
input(id).value().trim().to_owned()
|
||||
}
|
||||
fn field<'a>(v: &'a Value, name: &str) -> &'a str {
|
||||
v[name].as_str().unwrap_or("")
|
||||
}
|
||||
fn escape(s: &str) -> String {
|
||||
s.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
.replace('"', """)
|
||||
.replace('\'', "'")
|
||||
}
|
||||
fn hidden(id: &str, hide: bool) {
|
||||
if hide {
|
||||
let _ = el(id).set_attribute("hidden", "");
|
||||
} else {
|
||||
let _ = el(id).remove_attribute("hidden");
|
||||
}
|
||||
}
|
||||
fn disabled(id: &str, disable: bool) {
|
||||
if disable {
|
||||
let _ = el(id).set_attribute("disabled", "");
|
||||
} else {
|
||||
let _ = el(id).remove_attribute("disabled");
|
||||
}
|
||||
}
|
||||
fn dialog() -> HtmlDialogElement {
|
||||
el("edit-dialog").unchecked_into()
|
||||
}
|
||||
fn message(id: &str, msg: &str, error: bool) {
|
||||
text(id, msg);
|
||||
let _ = el(id).set_attribute(
|
||||
"class",
|
||||
if error {
|
||||
"form-message error"
|
||||
} else {
|
||||
"form-message"
|
||||
},
|
||||
);
|
||||
}
|
||||
fn err(e: JsValue) -> String {
|
||||
e.as_string()
|
||||
.unwrap_or_else(|| "浏览器操作失败,请刷新核对保存结果".into())
|
||||
}
|
||||
|
||||
async fn api(url: &str, method: &str, body: Option<Value>) -> Result<Value> {
|
||||
let req = match method {
|
||||
"POST" => Request::post(url),
|
||||
"PATCH" => Request::patch(url),
|
||||
"DELETE" => Request::delete(url),
|
||||
_ => Request::get(url),
|
||||
};
|
||||
let response = if let Some(body) = body {
|
||||
req.json(&body).map_err(|e| e.to_string())?.send().await
|
||||
} else {
|
||||
req.send().await
|
||||
}
|
||||
.map_err(|e| e.to_string())?;
|
||||
let status = response.ok();
|
||||
let payload: Value = response.json().await.map_err(|e| e.to_string())?;
|
||||
if status {
|
||||
Ok(payload)
|
||||
} else {
|
||||
Err(payload["error"].as_str().unwrap_or("请求失败").to_owned())
|
||||
}
|
||||
}
|
||||
fn archive_status(payload: &Value) {
|
||||
if payload["archiveStatus"] == "pending" {
|
||||
hidden("archive-warning", false);
|
||||
text(
|
||||
"archive-warning-text",
|
||||
payload["warning"]
|
||||
.as_str()
|
||||
.unwrap_or("数据已保存,档案备份待同步。"),
|
||||
);
|
||||
} else if payload["archiveStatus"] == "synced" {
|
||||
hidden("archive-warning", true);
|
||||
}
|
||||
}
|
||||
fn selection(state: &Shared) {
|
||||
let s = state.borrow();
|
||||
let n = s.selected.len();
|
||||
text("selected-count", &format!("({n})"));
|
||||
input("select-all").set_checked(!s.rows.is_empty() && n == s.rows.len());
|
||||
input("select-all").set_indeterminate(n > 0 && n < s.rows.len());
|
||||
disabled("export-archive", n == 0);
|
||||
disabled("export-excel", n == 0);
|
||||
}
|
||||
fn page_buttons(state: &Shared) {
|
||||
let s = state.borrow();
|
||||
disabled("previous-page", s.page <= 1);
|
||||
disabled("next-page", s.page >= s.pages);
|
||||
}
|
||||
fn clear_selection(state: &Shared) {
|
||||
state.borrow_mut().selected.clear();
|
||||
render_rows(state);
|
||||
}
|
||||
fn render_rows(state: &Shared) {
|
||||
let s = state.borrow();
|
||||
let mut html = String::new();
|
||||
for row in &s.rows {
|
||||
let id = escape(field(row, "id"));
|
||||
let sn = escape(field(row, "serialNo"));
|
||||
let selected = s.selected.contains(field(row, "id"));
|
||||
html.push_str(&format!("<article class=\"archive-card{}\" data-id=\"{id}\"><label class=\"archive-select\"><input type=\"checkbox\" data-action=\"select\" aria-label=\"选择档案 {sn}\" {}>导出</label><h3>{sn}</h3><strong>{}</strong><p>{} · {} · {}</p><div class=\"archive-thumbs\">",if selected {" selected"} else {""},if selected {"checked"} else {""},escape(field(row,"uasCode")),escape(field(row,"modelName")),escape(field(row,"ownerName")),escape(field(row,"createdAt"))));
|
||||
for slot in [1, 2] {
|
||||
let url = field(row, &format!("photo{slot}Url"));
|
||||
if url.is_empty() {
|
||||
html.push_str(&format!("<div>照片 {slot} 未上传</div>"));
|
||||
} else {
|
||||
html.push_str(&format!(
|
||||
"<div><img loading=\"lazy\" alt=\"登记照片 {slot}\" src=\"{}\"></div>",
|
||||
escape(url)
|
||||
));
|
||||
}
|
||||
}
|
||||
html.push_str(&format!("</div><div class=\"archive-actions\"><button type=\"button\" data-action=\"edit\">编辑资料 / 照片</button><a href=\"{}\" target=\"_blank\" rel=\"noopener\">打开档案卡</a><a href=\"{}\">下载离线档案卡</a><button type=\"button\" data-action=\"qr\">查看二维码</button><button type=\"button\" class=\"delete-record\" data-action=\"delete\">删除档案</button></div></article>",escape(field(row,"archiveUrl")),escape(field(row,"downloadArchiveUrl"))));
|
||||
}
|
||||
el("history-cards").set_inner_html(&html);
|
||||
hidden("history-empty", !s.rows.is_empty());
|
||||
drop(s);
|
||||
selection(state);
|
||||
}
|
||||
async fn load(state: Shared, mut page: u64) -> Result<()> {
|
||||
let generation = {
|
||||
let mut s = state.borrow_mut();
|
||||
s.generation += 1;
|
||||
s.generation
|
||||
};
|
||||
let query = value("history-query");
|
||||
disabled("previous-page", true);
|
||||
disabled("next-page", true);
|
||||
loop {
|
||||
let url = format!(
|
||||
"/api/records?q={}&page={page}&pageSize=20",
|
||||
js_sys::encode_uri_component(&query)
|
||||
);
|
||||
let response = api(&url, "GET", None).await;
|
||||
if state.borrow().generation != generation {
|
||||
return Ok(());
|
||||
}
|
||||
let payload = match response {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
page_buttons(&state);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
let pages = payload["totalPages"].as_u64().unwrap_or(0);
|
||||
if page > pages.max(1) {
|
||||
page = pages.max(1);
|
||||
continue;
|
||||
}
|
||||
{
|
||||
let mut s = state.borrow_mut();
|
||||
s.page = page;
|
||||
s.pages = pages;
|
||||
s.rows = payload["records"].as_array().cloned().unwrap_or_default();
|
||||
let ids: HashSet<String> = s.rows.iter().map(|r| field(r, "id").to_owned()).collect();
|
||||
s.selected.retain(|id| ids.contains(id));
|
||||
}
|
||||
text(
|
||||
"page-status",
|
||||
&format!(
|
||||
"第 {page} / {} 页 · 共 {} 条",
|
||||
pages.max(1),
|
||||
payload["total"]
|
||||
),
|
||||
);
|
||||
text(
|
||||
"search-count",
|
||||
&if query.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("{} 条", payload["total"])
|
||||
},
|
||||
);
|
||||
text(
|
||||
"history-empty",
|
||||
if query.is_empty() {
|
||||
"暂无登记记录。"
|
||||
} else {
|
||||
"没有找到匹配的档案。"
|
||||
},
|
||||
);
|
||||
render_rows(&state);
|
||||
page_buttons(&state);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
async fn photo(id: &str) -> Result<Option<String>> {
|
||||
let Some(file) = input(id).files().and_then(|files| files.get(0)) else {
|
||||
return Ok(None);
|
||||
};
|
||||
if !matches!(
|
||||
file.type_().as_str(),
|
||||
"image/jpeg" | "image/png" | "image/webp"
|
||||
) || file.size() > 5.0 * 1024.0 * 1024.0
|
||||
{
|
||||
return Err("照片仅支持 5 MB 以内的 JPG、PNG 或 WebP".into());
|
||||
}
|
||||
let data = JsFuture::from(file.array_buffer()).await.map_err(err)?;
|
||||
Ok(Some(format!(
|
||||
"data:{};base64,{}",
|
||||
file.type_(),
|
||||
STANDARD.encode(js_sys::Uint8Array::new(&data).to_vec())
|
||||
)))
|
||||
}
|
||||
fn draw(state: &Shared, record: Value) {
|
||||
hidden("empty-result", true);
|
||||
hidden("record-result", false);
|
||||
for (id, key) in [
|
||||
("display-uas", "uasCode"),
|
||||
("display-sn", "serialNo"),
|
||||
("display-model", "modelName"),
|
||||
("display-owner", "ownerName"),
|
||||
("display-url", "qrUrl"),
|
||||
] {
|
||||
text(id, field(&record, key));
|
||||
}
|
||||
for (id, key) in [
|
||||
("open-card", "archiveUrl"),
|
||||
("download-card", "downloadArchiveUrl"),
|
||||
] {
|
||||
let _ = el(id).set_attribute("href", field(&record, key));
|
||||
}
|
||||
let mut has_photos = false;
|
||||
for slot in [1, 2] {
|
||||
let url = field(&record, &format!("photo{slot}Url"));
|
||||
has_photos |= !url.is_empty();
|
||||
hidden(&format!("photo-{slot}-link"), url.is_empty());
|
||||
let _ = el(&format!("photo-{slot}-link")).set_attribute("href", url);
|
||||
let _ = el(&format!("photo-{slot}-preview"))
|
||||
.set_attribute("src", &format!("{url}?v={}", js_sys::Date::now()));
|
||||
}
|
||||
hidden("saved-photos", !has_photos);
|
||||
if let Ok(qr) = QrCode::encode_text(field(&record, "qrUrl"), QrCodeEcc::Medium) {
|
||||
let size = qr.size();
|
||||
let extent = size + 8;
|
||||
let mut svg = format!(
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 {extent} {extent}\"><rect width=\"100%\" height=\"100%\" fill=\"white\"/><g fill=\"black\">"
|
||||
);
|
||||
for y in 0..size {
|
||||
for x in 0..size {
|
||||
if qr.get_module(x, y) {
|
||||
svg.push_str(&format!(
|
||||
"<rect x=\"{}\" y=\"{}\" width=\"1\" height=\"1\"/>",
|
||||
x + 4,
|
||||
y + 4
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
svg.push_str("</g></svg>");
|
||||
el("qr-stage").set_inner_html(&svg);
|
||||
}
|
||||
state.borrow_mut().active = Some(record);
|
||||
}
|
||||
fn edit(state: &Shared, row: Value) {
|
||||
text("edit-message", "");
|
||||
text(
|
||||
"edit-identity",
|
||||
&format!("{} · {}", field(&row, "serialNo"), field(&row, "uasCode")),
|
||||
);
|
||||
input("edit-model").set_value(field(&row, "modelName"));
|
||||
input("edit-owner").set_value(field(&row, "ownerName"));
|
||||
for slot in [1, 2] {
|
||||
let url = field(&row, &format!("photo{slot}Url"));
|
||||
hidden(&format!("edit-preview-{slot}"), url.is_empty());
|
||||
let _ = el(&format!("edit-preview-{slot}")).set_attribute("src", url);
|
||||
input(&format!("edit-photo-{slot}")).set_value("");
|
||||
input(&format!("edit-delete-{slot}")).set_checked(false);
|
||||
input(&format!("edit-delete-{slot}")).set_disabled(url.is_empty());
|
||||
}
|
||||
state.borrow_mut().editing = Some(row);
|
||||
let _ = dialog().show_modal();
|
||||
let _ = input("edit-model").focus();
|
||||
}
|
||||
fn editing_controls(disable: bool) {
|
||||
let elements = el("edit-form").query_selector_all("input,button").unwrap();
|
||||
for i in 0..elements.length() {
|
||||
let node = elements.get(i).unwrap();
|
||||
if let Some(input) = node.dyn_ref::<HtmlInputElement>() {
|
||||
input.set_disabled(disable);
|
||||
} else if let Some(button) = node.dyn_ref::<HtmlButtonElement>() {
|
||||
button.set_disabled(disable);
|
||||
}
|
||||
}
|
||||
}
|
||||
async fn save(state: Shared, editing: bool) -> Result<()> {
|
||||
if state.borrow().busy {
|
||||
return Ok(());
|
||||
}
|
||||
state.borrow_mut().busy = true;
|
||||
let result = save_inner(state.clone(), editing).await;
|
||||
state.borrow_mut().busy = false;
|
||||
if editing {
|
||||
editing_controls(false);
|
||||
if let Some(row) = state.borrow().editing.clone() {
|
||||
for slot in [1, 2] {
|
||||
input(&format!("edit-delete-{slot}"))
|
||||
.set_disabled(field(&row, &format!("photo{slot}Url")).is_empty());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
disabled("register-button", false);
|
||||
}
|
||||
result
|
||||
}
|
||||
async fn save_inner(state: Shared, editing: bool) -> Result<()> {
|
||||
let mut body = if editing {
|
||||
json!({"modelName":value("edit-model"),"ownerName":value("edit-owner")})
|
||||
} else {
|
||||
let digits = value("uas-code");
|
||||
json!({"serialNo":value("serial-no"),"modelName":value("model-name"),"ownerName":value("owner-name"),"uasCode":if digits.is_empty(){String::new()}else{format!("FPV{digits}")}})
|
||||
};
|
||||
if editing {
|
||||
editing_controls(true);
|
||||
} else {
|
||||
disabled("register-button", true);
|
||||
}
|
||||
for slot in [1, 2] {
|
||||
let id = if editing {
|
||||
format!("edit-photo-{slot}")
|
||||
} else {
|
||||
format!("photo-{slot}")
|
||||
};
|
||||
if editing && input(&format!("edit-delete-{slot}")).checked() {
|
||||
body[format!("photo{slot}")] = Value::Null;
|
||||
} else if let Some(p) = photo(&id).await? {
|
||||
body[format!("photo{slot}")] = json!(p);
|
||||
}
|
||||
}
|
||||
let url = if editing {
|
||||
let s = state.borrow();
|
||||
format!(
|
||||
"/api/records/{}",
|
||||
field(s.editing.as_ref().ok_or("请选择档案")?, "id")
|
||||
)
|
||||
} else {
|
||||
"/api/records".into()
|
||||
};
|
||||
let payload = api(&url, if editing { "PATCH" } else { "POST" }, Some(body)).await?;
|
||||
archive_status(&payload);
|
||||
if editing {
|
||||
dialog().close();
|
||||
message("history-message", "档案修改已保存。", false);
|
||||
let is_active = state
|
||||
.borrow()
|
||||
.active
|
||||
.as_ref()
|
||||
.is_some_and(|r| r["id"] == payload["record"]["id"]);
|
||||
if is_active {
|
||||
draw(&state, payload["record"].clone());
|
||||
}
|
||||
} else {
|
||||
draw(&state, payload["record"].clone());
|
||||
message(
|
||||
"form-message",
|
||||
if payload["existing"] == true {
|
||||
"该 SN 已登记,照片和填写的信息已保存。"
|
||||
} else {
|
||||
"登记成功,二维码已生成。"
|
||||
},
|
||||
false,
|
||||
);
|
||||
}
|
||||
let page = state.borrow().page.max(1);
|
||||
if let Err(error) = load(state, page).await {
|
||||
message(
|
||||
"history-message",
|
||||
&format!("已保存,但列表刷新失败:{error}"),
|
||||
true,
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn download(url: &str, name: &str) {
|
||||
let a: HtmlAnchorElement = document().create_element("a").unwrap().unchecked_into();
|
||||
a.set_href(url);
|
||||
a.set_download(name);
|
||||
document().body().unwrap().append_child(&a).unwrap();
|
||||
a.click();
|
||||
a.remove();
|
||||
}
|
||||
async fn export(state: Shared, kind: &str) -> Result<()> {
|
||||
let ids: Vec<_> = state.borrow().selected.iter().cloned().collect();
|
||||
if ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let response = Request::post(&format!("/api/export/{kind}"))
|
||||
.json(&json!({"ids":ids}))
|
||||
.map_err(|e| e.to_string())?
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
if !response.ok() {
|
||||
return Err("导出失败,请重试".into());
|
||||
}
|
||||
let data = response.binary().await.map_err(|e| e.to_string())?;
|
||||
let array = js_sys::Array::new();
|
||||
array.push(&js_sys::Uint8Array::from(data.as_slice()));
|
||||
let blob = web_sys::Blob::new_with_u8_array_sequence(&array).map_err(err)?;
|
||||
let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(err)?;
|
||||
download(
|
||||
&url,
|
||||
if kind == "excel" {
|
||||
"FPV-RID-登记记录.xlsx"
|
||||
} else {
|
||||
"FPV-RID-档案库.zip"
|
||||
},
|
||||
);
|
||||
message(
|
||||
"history-message",
|
||||
&format!("已导出 {} 条档案。", ids.len()),
|
||||
false,
|
||||
);
|
||||
spawn_local(async move {
|
||||
TimeoutFuture::new(30000).await;
|
||||
let _ = web_sys::Url::revoke_object_url(&url);
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
fn download_qr(state: &Shared) -> Result<()> {
|
||||
let s = state.borrow();
|
||||
let row = s.active.as_ref().ok_or("请先登记")?;
|
||||
let qr = QrCode::encode_text(field(row, "qrUrl"), QrCodeEcc::Medium)
|
||||
.map_err(|_| "二维码生成失败")?;
|
||||
let canvas: HtmlCanvasElement = document()
|
||||
.create_element("canvas")
|
||||
.map_err(err)?
|
||||
.unchecked_into();
|
||||
canvas.set_width(640);
|
||||
canvas.set_height(640);
|
||||
let context: web_sys::CanvasRenderingContext2d = canvas
|
||||
.get_context("2d")
|
||||
.map_err(err)?
|
||||
.ok_or("Canvas 不可用")?
|
||||
.unchecked_into();
|
||||
context.set_fill_style_str("white");
|
||||
context.fill_rect(0.0, 0.0, 640.0, 640.0);
|
||||
context.set_fill_style_str("black");
|
||||
let cell = 640.0 / f64::from(qr.size() + 8);
|
||||
for y in 0..qr.size() {
|
||||
for x in 0..qr.size() {
|
||||
if qr.get_module(x, y) {
|
||||
let left = (f64::from(x + 4) * cell).floor();
|
||||
let top = (f64::from(y + 4) * cell).floor();
|
||||
let right = (f64::from(x + 5) * cell).ceil();
|
||||
let bottom = (f64::from(y + 5) * cell).ceil();
|
||||
context.fill_rect(left, top, right - left, bottom - top);
|
||||
}
|
||||
}
|
||||
}
|
||||
download(
|
||||
&canvas.to_data_url().map_err(err)?,
|
||||
&format!(
|
||||
"{}-{}-LOCAL.png",
|
||||
field(row, "serialNo"),
|
||||
field(row, "uasCode")
|
||||
),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn listen(name: &str, handler: impl FnMut(Event) + 'static) {
|
||||
let closure = Closure::<dyn FnMut(Event)>::new(handler);
|
||||
document()
|
||||
.add_event_listener_with_callback(name, closure.as_ref().unchecked_ref())
|
||||
.unwrap();
|
||||
closure.forget();
|
||||
}
|
||||
pub fn init() {
|
||||
let state = Rc::new(RefCell::new(State {
|
||||
page: 1,
|
||||
..State::default()
|
||||
}));
|
||||
{
|
||||
let state = state.clone();
|
||||
listen("submit", move |event| {
|
||||
let Some(target) = event.target().and_then(|t| t.dyn_into::<Element>().ok()) else {
|
||||
return;
|
||||
};
|
||||
let editing = target.id() == "edit-form";
|
||||
if !editing && target.id() != "register-form" {
|
||||
return;
|
||||
}
|
||||
event.prevent_default();
|
||||
let state = state.clone();
|
||||
spawn_local(async move {
|
||||
if let Err(e) = save(state, editing).await {
|
||||
message(
|
||||
if editing {
|
||||
"edit-message"
|
||||
} else {
|
||||
"form-message"
|
||||
},
|
||||
&e,
|
||||
true,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
listen("input", move |event| {
|
||||
if event
|
||||
.target()
|
||||
.and_then(|t| t.dyn_into::<Element>().ok())
|
||||
.is_some_and(|t| t.id() == "history-query")
|
||||
{
|
||||
clear_selection(&state);
|
||||
let generation = {
|
||||
let mut s = state.borrow_mut();
|
||||
s.generation += 1;
|
||||
s.generation
|
||||
};
|
||||
let state = state.clone();
|
||||
spawn_local(async move {
|
||||
TimeoutFuture::new(180).await;
|
||||
if state.borrow().generation != generation {
|
||||
return;
|
||||
}
|
||||
if let Err(e) = load(state, 1).await {
|
||||
message("history-message", &e, true);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
listen("change", move |event| {
|
||||
let Some(t) = event
|
||||
.target()
|
||||
.and_then(|t| t.dyn_into::<HtmlInputElement>().ok())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let id = t.id();
|
||||
if id == "select-all" {
|
||||
let mut s = state.borrow_mut();
|
||||
s.selected = if t.checked() {
|
||||
s.rows.iter().map(|r| field(r, "id").to_owned()).collect()
|
||||
} else {
|
||||
HashSet::new()
|
||||
};
|
||||
drop(s);
|
||||
render_rows(&state);
|
||||
} else if t.get_attribute("data-action").as_deref() == Some("select") {
|
||||
if let Some(card) = t.closest("[data-id]").ok().flatten() {
|
||||
let id = card.get_attribute("data-id").unwrap();
|
||||
if t.checked() {
|
||||
state.borrow_mut().selected.insert(id);
|
||||
} else {
|
||||
state.borrow_mut().selected.remove(&id);
|
||||
}
|
||||
render_rows(&state);
|
||||
}
|
||||
} else {
|
||||
for slot in [1, 2] {
|
||||
if id == format!("edit-photo-{slot}") {
|
||||
input(&format!("edit-delete-{slot}")).set_checked(false);
|
||||
}
|
||||
if id == format!("edit-delete-{slot}") && t.checked() {
|
||||
input(&format!("edit-photo-{slot}")).set_value("");
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
listen("click", move |event| {
|
||||
let Some(t) = event
|
||||
.target()
|
||||
.and_then(|t| t.dyn_into::<Element>().ok())
|
||||
.and_then(|t| t.closest("button").ok().flatten())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let id = t.id();
|
||||
let state = state.clone();
|
||||
if id == "edit-cancel" {
|
||||
dialog().close();
|
||||
return;
|
||||
}
|
||||
if id == "download-qr" {
|
||||
if let Err(e) = download_qr(&state) {
|
||||
message("form-message", &e, true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Some(action) = t.get_attribute("data-action") {
|
||||
let Some(card) = t.closest("[data-id]").ok().flatten() else {
|
||||
return;
|
||||
};
|
||||
let record_id = card.get_attribute("data-id").unwrap();
|
||||
let row = state
|
||||
.borrow()
|
||||
.rows
|
||||
.iter()
|
||||
.find(|r| field(r, "id") == record_id)
|
||||
.cloned();
|
||||
let Some(row) = row else { return };
|
||||
if action == "edit" {
|
||||
edit(&state, row);
|
||||
return;
|
||||
}
|
||||
if action == "qr" {
|
||||
draw(&state, row);
|
||||
return;
|
||||
}
|
||||
if action == "delete" {
|
||||
if !window()
|
||||
.confirm_with_message(&format!(
|
||||
"确定删除 {} 的登记档案和照片吗?",
|
||||
field(&row, "serialNo")
|
||||
))
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return;
|
||||
}
|
||||
spawn_local(async move {
|
||||
match api(&format!("/api/records/{record_id}"), "DELETE", None).await {
|
||||
Ok(p) => {
|
||||
archive_status(&p);
|
||||
state.borrow_mut().selected.remove(&record_id);
|
||||
let is_active = state
|
||||
.borrow()
|
||||
.active
|
||||
.as_ref()
|
||||
.is_some_and(|r| field(r, "id") == record_id);
|
||||
if is_active {
|
||||
state.borrow_mut().active = None;
|
||||
hidden("record-result", true);
|
||||
hidden("empty-result", false);
|
||||
}
|
||||
let page = state.borrow().page;
|
||||
if let Err(e) = load(state, page).await {
|
||||
message("history-message", &e, true);
|
||||
}
|
||||
}
|
||||
Err(e) => message("history-message", &e, true),
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
spawn_local(async move {
|
||||
let result = match id.as_str() {
|
||||
"previous-page" | "next-page" => {
|
||||
let page = {
|
||||
let s = state.borrow();
|
||||
if id == "previous-page" {
|
||||
s.page.saturating_sub(1).max(1)
|
||||
} else {
|
||||
s.page + 1
|
||||
}
|
||||
};
|
||||
clear_selection(&state);
|
||||
load(state, page).await
|
||||
}
|
||||
"refresh-list" => {
|
||||
let page = state.borrow().page;
|
||||
load(state, page).await
|
||||
}
|
||||
"export-excel" => export(state, "excel").await,
|
||||
"export-archive" => export(state, "archive").await,
|
||||
"retry-archive" => {
|
||||
disabled("retry-archive", true);
|
||||
let p = api("/api/archive/retry", "POST", Some(json!({}))).await;
|
||||
disabled("retry-archive", false);
|
||||
p.map(|p| archive_status(&p))
|
||||
}
|
||||
"copy-url" => {
|
||||
let url = state
|
||||
.borrow()
|
||||
.active
|
||||
.as_ref()
|
||||
.map(|r| field(r, "qrUrl").to_owned());
|
||||
if let Some(url) = url {
|
||||
JsFuture::from(window().navigator().clipboard().write_text(&url))
|
||||
.await
|
||||
.map(|_| message("form-message", "本地二维码链接已复制。", false))
|
||||
.map_err(err)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
_ => Ok(()),
|
||||
};
|
||||
if let Err(e) = result {
|
||||
message("history-message", &e, true);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
let close = Closure::<dyn FnMut(Event)>::new(move |event: Event| {
|
||||
if state.borrow().busy {
|
||||
event.prevent_default();
|
||||
}
|
||||
});
|
||||
el("edit-dialog")
|
||||
.add_event_listener_with_callback("cancel", close.as_ref().unchecked_ref())
|
||||
.unwrap();
|
||||
close.forget();
|
||||
}
|
||||
spawn_local(async move {
|
||||
if let Err(e) = load(state, 1).await {
|
||||
message("history-message", &e, true);
|
||||
}
|
||||
match api("/api/archive/status", "GET", None).await {
|
||||
Ok(p) => archive_status(&p),
|
||||
Err(e) => message("history-message", &e, true),
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "rid-web-worker"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
rid-shared = { path = "../rid-shared" }
|
||||
postcard = { version = "1", features = ["alloc"] }
|
||||
wasm-bindgen = "=0.2.129"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["DedicatedWorkerGlobalScope", "WebSocket", "BinaryType", "MessageEvent", "CloseEvent", "ErrorEvent", "console"] }
|
||||
@@ -0,0 +1,8 @@
|
||||
// Module bootstrap only; telemetry decoding and state handling live in Rust.
|
||||
import init, {connect, acknowledge} from './rid_web_worker.js';
|
||||
const ready = init();
|
||||
self.onmessage = async event => {
|
||||
await ready;
|
||||
if (event.data?.type === 'connect') connect(event.data.url);
|
||||
if (event.data?.type === 'ack') acknowledge(event.data.sequence);
|
||||
};
|
||||
@@ -0,0 +1,185 @@
|
||||
//! WebSocket decoding and latest-state merge execute outside the UI thread.
|
||||
use rid_shared::{Frame, PROTOCOL_VERSION, Target};
|
||||
use std::{cell::RefCell, collections::BTreeMap, rc::Rc};
|
||||
use wasm_bindgen::{JsCast, prelude::*};
|
||||
|
||||
thread_local! {
|
||||
static PENDING: RefCell<Option<(web_sys::WebSocket, u64)>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn acknowledge(sequence: f64) {
|
||||
PENDING.with(|pending| {
|
||||
if let Some((socket, expected)) = pending.borrow_mut().take() {
|
||||
if sequence as u64 == expected {
|
||||
let _ = socket.send_with_str(&expected.to_string());
|
||||
} else {
|
||||
let _ = socket.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
targets: BTreeMap<String, Target>,
|
||||
epoch: Option<u64>,
|
||||
sequence: u64,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn topology_changed(&self, frame: &Frame) -> bool {
|
||||
self.epoch.is_none()
|
||||
|| (frame.snapshot && self.targets.len() != frame.targets.len())
|
||||
|| !frame.removed.is_empty()
|
||||
|| frame
|
||||
.targets
|
||||
.iter()
|
||||
.any(|t| !self.targets.contains_key(&t.observation.target_id))
|
||||
}
|
||||
fn apply(&mut self, frame: &Frame) -> Result<(), &'static str> {
|
||||
if frame.version != PROTOCOL_VERSION {
|
||||
return Err("unsupported protocol version");
|
||||
}
|
||||
if frame.snapshot {
|
||||
self.targets.clear();
|
||||
self.epoch = Some(frame.epoch);
|
||||
} else if self.epoch != Some(frame.epoch) || frame.sequence < self.sequence {
|
||||
return Err("snapshot required");
|
||||
}
|
||||
self.sequence = frame.sequence;
|
||||
for id in &frame.removed {
|
||||
self.targets.remove(id);
|
||||
}
|
||||
for target in &frame.targets {
|
||||
self.targets
|
||||
.insert(target.observation.target_id.clone(), target.clone());
|
||||
}
|
||||
if self.targets.len() > 10000 {
|
||||
return Err("target capacity exceeded");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn post_status(scope: &web_sys::DedicatedWorkerGlobalScope, text: &str) {
|
||||
let object = js_sys::Object::new();
|
||||
let _ = js_sys::Reflect::set(&object, &"status".into(), &text.into());
|
||||
let _ = scope.post_message(&object);
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn connect(url: &str) -> Result<(), JsValue> {
|
||||
let scope: web_sys::DedicatedWorkerGlobalScope = js_sys::global().unchecked_into();
|
||||
let socket = web_sys::WebSocket::new(url)?;
|
||||
socket.set_binary_type(web_sys::BinaryType::Arraybuffer);
|
||||
let state = Rc::new(RefCell::new(State::default()));
|
||||
let sender = socket.clone();
|
||||
let output = scope.clone();
|
||||
let handler =
|
||||
Closure::<dyn FnMut(web_sys::MessageEvent)>::new(move |event: web_sys::MessageEvent| {
|
||||
let data = js_sys::Uint8Array::new(&event.data()).to_vec();
|
||||
let frame = match postcard::from_bytes::<Frame>(&data) {
|
||||
Ok(f) => f,
|
||||
Err(_) => {
|
||||
post_status(&output, "invalid-frame");
|
||||
let _ = sender.close();
|
||||
return;
|
||||
}
|
||||
};
|
||||
let mut state = state.borrow_mut();
|
||||
let topology_changed = state.topology_changed(&frame);
|
||||
if let Err(e) = state.apply(&frame) {
|
||||
post_status(&output, e);
|
||||
let _ = sender.close();
|
||||
return;
|
||||
}
|
||||
let mut positions = Vec::with_capacity(state.targets.len() * 4);
|
||||
let ids = js_sys::Array::new();
|
||||
let mut max_age = 0;
|
||||
for (id, target) in &state.targets {
|
||||
let o = &target.observation;
|
||||
if topology_changed {
|
||||
ids.push(&JsValue::from_str(id));
|
||||
}
|
||||
positions.extend_from_slice(&[
|
||||
o.longitude,
|
||||
o.latitude,
|
||||
f64::from(o.altitude_m),
|
||||
f64::from(o.heading_deg),
|
||||
]);
|
||||
max_age = max_age.max(frame.server_time_ms.saturating_sub(target.received_at_ms));
|
||||
}
|
||||
let array = js_sys::Float64Array::from(positions.as_slice());
|
||||
let buffer = array.buffer();
|
||||
let object = js_sys::Object::new();
|
||||
let memory: js_sys::WebAssembly::Memory = wasm_bindgen::memory().unchecked_into();
|
||||
let memory_buffer: js_sys::ArrayBuffer = memory.buffer().unchecked_into();
|
||||
for (key, value) in [
|
||||
("positions", array.into()),
|
||||
("sequence", JsValue::from_f64(frame.sequence as f64)),
|
||||
("serverAgeMs", JsValue::from_f64(max_age as f64)),
|
||||
("status", JsValue::from_str("connected")),
|
||||
(
|
||||
"wasmMemoryBytes",
|
||||
JsValue::from_f64(f64::from(memory_buffer.byte_length())),
|
||||
),
|
||||
] {
|
||||
let _ = js_sys::Reflect::set(&object, &key.into(), &value);
|
||||
}
|
||||
if topology_changed {
|
||||
let _ = js_sys::Reflect::set(&object, &"ids".into(), &ids);
|
||||
}
|
||||
let transfer = js_sys::Array::new();
|
||||
transfer.push(&buffer);
|
||||
if output
|
||||
.post_message_with_transfer(&object, &transfer)
|
||||
.is_ok()
|
||||
{
|
||||
PENDING
|
||||
.with(|pending| *pending.borrow_mut() = Some((sender.clone(), frame.sequence)));
|
||||
}
|
||||
});
|
||||
socket.set_onmessage(Some(handler.as_ref().unchecked_ref()));
|
||||
handler.forget();
|
||||
let output = scope.clone();
|
||||
let close = Closure::<dyn FnMut(web_sys::CloseEvent)>::new(move |_| {
|
||||
post_status(&output, "disconnected")
|
||||
});
|
||||
socket.set_onclose(Some(close.as_ref().unchecked_ref()));
|
||||
close.forget();
|
||||
let output = scope.clone();
|
||||
let error = Closure::<dyn FnMut(web_sys::ErrorEvent)>::new(move |_| {
|
||||
post_status(&output, "connection-error")
|
||||
});
|
||||
socket.set_onerror(Some(error.as_ref().unchecked_ref()));
|
||||
error.forget();
|
||||
post_status(&scope, "connecting");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn requires_snapshot_on_epoch_change() {
|
||||
let mut state = State::default();
|
||||
let mut frame = Frame {
|
||||
version: PROTOCOL_VERSION,
|
||||
epoch: 1,
|
||||
sequence: 1,
|
||||
snapshot: false,
|
||||
server_time_ms: 0,
|
||||
targets: vec![],
|
||||
removed: vec![],
|
||||
};
|
||||
assert!(state.apply(&frame).is_err());
|
||||
frame.snapshot = true;
|
||||
assert!(state.apply(&frame).is_ok());
|
||||
frame.epoch = 2;
|
||||
frame.snapshot = false;
|
||||
assert!(state.apply(&frame).is_err());
|
||||
frame.snapshot = true;
|
||||
assert!(state.apply(&frame).is_ok());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user