feat(web-ui): 添加历史轨迹功能与地图适配

- 在 web-ui 中新增历史轨迹查询与回放功能,允许用户查看历史数据。
- 更新 map-loader.js 和 history-map-adapter.js,支持历史轨迹的地图渲染与交互。
- 修改 CSS 文件以改善历史轨迹界面的样式,确保在不同主题下的视觉一致性。
- 在 receivers.js 中更新接收机配置,支持 UID 身份隔离与状态显示优化。
- 在 map_settings.rs 中设置默认经纬度,提升地图初始化体验。
This commit is contained in:
2026-11-02 15:28:01 +08:00
parent 87d0ec8352
commit 7af8fb32cf
43 changed files with 3107 additions and 302 deletions
+9 -1
View File
@@ -148,7 +148,12 @@ func fetch(client *http.Client, r request, t tile, limiter <-chan time.Time) err
}
// Valid local tiles do not consume network rate-limit slots.
<-limiter
resp, err := client.Get(fmt.Sprintf("%s/%s/%d/%d/%d", strings.TrimRight(r.BaseURL, "/"), t.layer, t.z, t.x, t.y))
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/%s/%d/%d/%d", strings.TrimRight(r.BaseURL, "/"), t.layer, t.z, t.x, t.y), nil)
if err != nil {
return err
}
req.Header.Set("x-rid-map-download", "1")
resp, err := client.Do(req)
if err != nil {
return err
}
@@ -156,6 +161,9 @@ func fetch(client *http.Client, r request, t tile, limiter <-chan time.Time) err
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("tile unavailable")
}
if resp.Header.Get("x-map-source") == "offline-parent" {
return fmt.Errorf("parent preview is not a downloaded tile")
}
data, err := io.ReadAll(io.LimitReader(resp.Body, 2*1024*1024+1))
if err != nil {
return err
+23
View File
@@ -96,3 +96,26 @@ func TestRejectsBrokenImage(t *testing.T) {
t.Fatal("oversized dimensions accepted")
}
}
func TestParentPreviewIsNeverSavedAsAnOfflineTile(t *testing.T) {
var imageBytes bytes.Buffer
_ = png.Encode(&imageBytes, image.NewRGBA(image.Rect(0, 0, 256, 256)))
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("x-rid-map-download") != "1" {
t.Error("download request is not identified")
}
w.Header().Set("x-map-source", "offline-parent")
_, _ = w.Write(imageBytes.Bytes())
}))
defer server.Close()
root := t.TempDir()
limiter := make(chan time.Time, 1)
limiter <- time.Now()
err := fetch(server.Client(), request{Output: root, BaseURL: server.URL}, tile{layer: "img_w", z: 3, x: 2, y: 2}, limiter)
if err == nil {
t.Fatal("parent preview was accepted as an actual tile")
}
if _, err := os.Stat(filepath.Join(root, "img_w", "3", "2", "2.png")); !os.IsNotExist(err) {
t.Fatal("parent preview was written to the offline directory")
}
}
+44
View File
@@ -0,0 +1,44 @@
// Deterministic map-adapter checks without an HTTP server or physical receiver.
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {readFile} from 'node:fs/promises';
import vm from 'node:vm';
const source=(await readFile(new URL('../crates/web-ui/public/history-map-adapter.js',import.meta.url),'utf8'))
.replace(/^import .*;$/gm,'').replaceAll('export function ','function ');
test('historical segments stay separate and playback moves only the marker',()=>{
let map,marker,fitCount=0,removed=false;
const sources=new Map();
class FakeMap{
constructor(){map=this;this.handlers={};}
on(name,fn){this.handlers[name]=fn;}
addControl(){}
addSource(id,value){sources.set(id,{data:value.data,setData(data){this.data=data;}});}
addLayer(){}
getSource(id){return sources.get(id);}
fitBounds(){fitCount++;}
resize(){}
remove(){removed=true;}
}
class Marker{setLngLat(point){this.position=[...point];marker=this;return this;}addTo(){return this;}remove(){}}
class Bounds{constructor(){this.points=[];}extend(point){this.points.push(point);}isEmpty(){return this.points.length===0;}}
const context=vm.createContext({window:{dispatchEvent(){}},document:{getElementById(){return {};}},
ResizeObserver:class{observe(){}disconnect(){}},Event:class{},Number,Array,Math,
ml:{setWorkerUrl(){},Map:FakeMap,Marker,LngLatBounds:Bounds,NavigationControl:class{},AttributionControl:class{}},
attachTileBuffer:()=>({destroy(){}})});
vm.runInContext(source,context);
vm.runInContext('open({longitude:118.77,latitude:32.04,zoom:15,basemap:"road"})',context);
vm.runInContext('setPoints([{longitude:118,latitude:32,segmentStart:true},{longitude:119,latitude:32,segmentStart:false},{longitude:120,latitude:32,segmentStart:true},{longitude:121,latitude:32,segmentStart:false}])',context);
map.handlers['style.load']();
const features=sources.get('history-track').data.features;
assert.equal(features.length,2);
assert.deepEqual([...features[0].geometry.coordinates].map(p=>[...p]),[[118,32],[119,32]]);
assert.deepEqual([...features[1].geometry.coordinates].map(p=>[...p]),[[120,32],[121,32]]);
assert.equal(fitCount,1);
vm.runInContext('setIndex(2)',context);
assert.deepEqual(marker.position,[120,32]);
assert.equal(fitCount,1,'playback should not recenter the map repeatedly');
vm.runInContext('close()',context);
assert.ok(removed);
});
+11 -1
View File
@@ -20,7 +20,7 @@ function fixture(){
const buffer=context.attachTileBuffer(map,()=> 'imagery');
async function advance(ms){const end=now+ms;for(let count=0;count<1000;count++){
const next=[...timers].filter(([,t])=>t.at<=end).sort((a,b)=>a[1].at-b[1].at)[0];
if(!next){now=end;return;}now=next[1].at;timers.delete(next[0]);next[1].fn();
if(!next){now=end;for(let i=0;i<1000;i++)await Promise.resolve();return;}now=next[1].at;timers.delete(next[0]);next[1].fn();
for(let i=0;i<100;i++)await Promise.resolve();
}throw Error('timer loop');}
return {buffer,requests,timers,advance,emit(name){for(const fn of events.get(name)||[])fn({});},
@@ -29,6 +29,16 @@ function fixture(){
test('opening an already-ready map warms surrounding tiles without another map event',async()=>{
const f=fixture();await f.advance(1000);assert.ok(f.requests.length>0);assert.equal(f.buffer.metrics().queued,0);f.buffer.destroy();
});
test('warming does not run multiple background downloads at once',async()=>{
let resolveFetch,active=0,maxActive=0,now=1000000,id=0;const timers=new Map();
const context=vm.createContext({AbortController,Date:{now:()=>now},setTimeout(fn,delay){const key=++id;timers.set(key,{at:now+delay,fn});return key;},clearTimeout(key){timers.delete(key);},
fetch(){active++;maxActive=Math.max(maxActive,active);return new Promise(resolve=>{resolveFetch=()=>{active--;resolve({ok:true,status:200,arrayBuffer:async()=>new ArrayBuffer(0)});};});}});
vm.runInContext(source.replace('export function attachTileBuffer','function attachTileBuffer'),context);
const map={isMoving:()=>false,isStyleLoaded:()=>true,getCanvas:()=>({clientWidth:256,clientHeight:256}),getCenter:()=>({lng:0,lat:0}),getZoom:()=>2,getPitch:()=>0,getBearing:()=>0,unproject:([x,y])=>({lng:(x-128)/16,lat:(128-y)/16}),on(){},off(){}};
const buffer=context.attachTileBuffer(map,()=> 'imagery');const startup=[...timers.values()][0];startup.fn();
assert.equal(active,1);assert.equal(maxActive,1);assert.ok(buffer.metrics().queued>0);resolveFetch();
for(let i=0;i<10;i++)await Promise.resolve();assert.equal(maxActive,1);buffer.destroy();
});
test('startup retries readiness without requiring idle or camera movement',async()=>{
const f=fixture();f.ready(false);f.emit('load');await f.advance(1000);assert.equal(f.requests.length,0);
f.ready(true);await f.advance(1000);assert.ok(f.requests.length>0);f.buffer.destroy();
+62 -5
View File
@@ -3,14 +3,15 @@ import {readFile} from 'node:fs/promises';
import vm from 'node:vm';
import assert from 'node:assert/strict';
const source=(await readFile(new URL('../crates/web-ui/public/map-adapter.js',import.meta.url),'utf8')).replace(/^import .*;$/gm,'');
let markers=0,drawCount=0,trail=[];
let markers=0,drawCount=0,trail=[],markerPositions=[];
const gl={ARRAY_BUFFER:1,bindBuffer(){},bufferSubData(_t,_o,data){assert.ok([...data].every(Number.isFinite));},getExtension(){return null;}};
let flights=[];
const map={getSource(){return{setData(data){trail=data.features;}};},triggerRepaint(){},getCanvas(){return{clientWidth:1000,clientHeight:700};},project(p){assert.ok(p.every(Number.isFinite));return{x:1,y:2};},getCenter(){return{toArray(){return[120,30];}};},getZoom(){return 15;},getPitch(){return 0;},getBearing(){return 0;},easeTo(){},flyTo(options){flights.push(options.center);},isStyleLoaded(){return true;}};
class Marker{constructor(opts){markers++;this.element=opts?.element||{dataset:{},querySelector(){return{dataset:{}};}};}setLngLat(p){assert.ok(p.every(Number.isFinite));return this;}addTo(){return this;}getElement(){return this.element;}remove(){markers--;}}
function domNode(){const node={dataset:{},className:'',textContent:'',innerHTML:'',children:[],append(...items){this.children.push(...items);},querySelector(sel){const name=sel.slice(1);const walk=item=>item.className===name?item:(item.children||[]).map(walk).find(Boolean);return walk(node)||null;}};return node;}
class Marker{constructor(opts){markers++;this.element=opts?.element||{dataset:{},querySelector(){return{dataset:{}};}};}setLngLat(p){assert.ok(p.every(Number.isFinite));markerPositions.push([...p]);return this;}addTo(){return this;}getElement(){return this.element;}remove(){markers--;}}
function domNode(){const node={dataset:{},style:{},attributes:{},listeners:{},className:'',textContent:'',innerHTML:'',children:[],append(...items){this.children.push(...items);},setAttribute(name,value){this.attributes[name]=value;},addEventListener(name,handler){this.listeners[name]=handler;},querySelector(sel){const name=sel.slice(1);const walk=item=>item.className===name?item:(item.children||[]).map(walk).find(Boolean);return walk(node)||null;}};return node;}
let now=1000;
const context=vm.createContext({window:{},document:{createElement:domNode,getElementById(){return null;}},performance:{now:()=>now},requestAnimationFrame(){},maplibre:{setWorkerUrl(){},Marker,MercatorCoordinate:{fromLngLat(p){assert.ok(p.every(Number.isFinite));return{x:p[0],y:p[1]};}}},console,Float32Array,Map,Number,Array,Math,mockMap:map,mockGl:gl});
const events=[];
const context=vm.createContext({window:{dispatchEvent(event){events.push(event);}},CustomEvent:class{constructor(type,options){this.type=type;this.detail=options.detail;}},document:{createElement:domNode,getElementById(){return null;}},performance:{now:()=>now},requestAnimationFrame(){},maplibre:{setWorkerUrl(){},Marker,MercatorCoordinate:{fromLngLat(p){assert.ok(p.every(Number.isFinite));return{x:p[0],y:p[1]};}}},console,Float32Array,Map,Set,Number,Array,Math,mockMap:map,mockGl:gl});
vm.runInContext(source,context);
vm.runInContext('map=mockMap;layer={gl:mockGl,instances:{},origin:{x:0,y:0}};centered=true;',context);
const update=(positions,generation)=>{context.input=new Float64Array(positions);context.generation=generation;vm.runInContext('window.ridMap.update(input,["TEST"],[generation]);flush();',context);drawCount=vm.runInContext('layer.count',context);};
@@ -38,4 +39,60 @@ assert.ok(trail[0].geometry.coordinates[0].length>8);
assert.equal(markers,2);
vm.runInContext('window.ridMap.setFences([{id:"BAD",geometry:{type:"circle",center:[999,0],radius_m:10}}]);',context);
assert.equal(trail.length,0);
console.log(JSON.stringify({status:'PASS',scenarios:['unknown position excluded from GPU and selection','unknown altitude/heading do not block valid position','loss removes marker and trail','recovery starts new trail','coalesced loss breaks trail','source filter hides and restores targets','saved geofence renders on the realtime map']}));
vm.runInContext('window.ridMap.select("");',context);
update([NaN,NaN,NaN,90],6);
vm.runInContext('window.ridMap.select("TEST");',context);
const beforeZero=flights.length;
vm.runInContext('window.ridMap.focusRaw([0,0]);',context);
assert.equal(flights.length,beforeZero,'missing GPS coordinates do not move the map');
assert.equal(markers,0,'missing GPS coordinates do not create a marker');
vm.runInContext('window.ridMap.focusRaw([118,31]);',context);
assert.equal(markers,1);
const afterFocus=flights.length;
vm.runInContext('window.ridMap.updateRaw([119,32]);',context);
assert.deepEqual(markerPositions.at(-1),[119,32],'raw marker follows updates');
assert.equal(flights.length,afterFocus,'raw updates do not repeatedly recenter the map');
vm.runInContext('window.ridMap.setSources([]);',context);
assert.equal(markers,0,'source filtering hides unverified markers');
vm.runInContext('window.ridMap.setSources(["TEST"]);',context);
assert.equal(markers,1,'restoring the source restores the active marker');
vm.runInContext('window.ridMap.updateRaw(null);',context);
assert.equal(markers,0,'losing raw coordinates removes the marker');
vm.runInContext('window.ridMap.updateRaw([119,32]);',context);
assert.equal(markers,1);
vm.runInContext('window.ridMap.update(new Float64Array([]),[],[]);flush();',context);
assert.equal(markers,0,'target expiration removes the unverified marker');
vm.runInContext('window.ridMap.setSources(null);',context);
context.twoPositions=new Float64Array([120,30,NaN,0,121,31,NaN,0]);
context.twoInfos=new Float64Array([390,125,2,2400,NaN,0]);
vm.runInContext('window.ridMap.update(twoPositions,["TEST","TWO"],[1,1],twoInfos);flush();',context);
assert.equal(markers,2,'each located target receives its own card');
let entries=vm.runInContext('markers',context);
assert.equal(entries.get('TEST').age.textContent,'数据年龄 390 ms');
assert.equal(entries.get('TWO').age.textContent,'数据年龄 2.4 秒');
assert.equal(entries.get('TEST').height.textContent,'几何高度 125.0 m');
assert.equal(entries.get('TWO').height.textContent,'高度 —');
assert.equal(entries.get('TEST').longitude.textContent,'经度 120.000000');
vm.runInContext('window.ridMap.select("TWO");',context);
assert.equal(entries.get('TWO').root.style.zIndex,'10','selected target renders above other cards');
assert.equal(entries.get('TEST').root.style.zIndex,'1');
assert.equal(entries.get('TWO').icon.attributes['aria-pressed'],'true');
entries.get('TEST').icon.listeners.click({stopPropagation(){}});
assert.equal(events.at(-1).detail,'TEST','clicking a logo requests selection of that target');
vm.runInContext('window.ridMap.connection(false);',context);
assert.equal(entries.get('TWO').age.textContent,'数据年龄 连接断开');
vm.runInContext('window.ridMap.connection(true);',context);
context.longIds=Array.from({length:130},(_,i)=>`T${i}`);
context.longPositions=new Float64Array(context.longIds.flatMap((_,i)=>[120+i/10000,30,NaN,0]));
vm.runInContext('window.ridMap.update(longPositions,longIds,[],null);flush();',context);
assert.equal(markers,120,'card count is bounded when many targets are visible');
vm.runInContext('window.ridMap.select("T129");',context);
entries=vm.runInContext('markers',context);
assert.equal(entries.get('T129').root.style.zIndex,'10','a selected target is retained even when the card limit is reached');
context.zeroPosition=new Float64Array([0,0,NaN,0]);
vm.runInContext('window.ridMap.update(zeroPosition,["ZERO"],[],null);flush();',context);
assert.equal(markers,0,'zero coordinate pair must not create a map marker');
context.zeroComponent=new Float64Array([0,30,NaN,0]);
vm.runInContext('window.ridMap.update(zeroComponent,["ZERO"],[],null);flush();',context);
assert.equal(markers,1,'a single zero coordinate component remains valid');
console.log(JSON.stringify({status:'PASS',scenarios:['unknown position excluded from GPU and selection','unknown altitude/heading do not block valid position','loss removes marker and trail','recovery starts new trail','coalesced loss breaks trail','source filter hides and restores targets','saved geofence renders on the realtime map','unverified marker follows its lifecycle and ignores zero GPS','per-target card age and height reference','click requests selection and selected card is on top','disconnect state','bounded card rendering']}));