feat(map-settings): 新增地图设置面板,支持底图偏好与离线瓦片下载

共享层新增 map_settings 模块,定义 Bounds、Region、Preferences 和
DownloadRequest 数据结构及验证逻辑,单次下载上限 20000 张瓦片。

前端新增独立地图设置视图,包含:
- 底图切换(影像/路网)与默认定位点配置
- 地图选点、框选下载范围交互
- 常用区域保存与离线下载任务管理

实时地图适配器改为从 Preferences 读取初始中心点和缩放级别,
使设置面板与工作台地图共享视图状态。

同时微调目标列表行高与 footer 布局,在紧凑模式下隐藏黑名单提示。
```
This commit is contained in:
2026-10-23 09:43:14 +08:00
parent df9e8bdeb5
commit 5e3c89fdf4
29 changed files with 2052 additions and 33 deletions
+15
View File
@@ -0,0 +1,15 @@
$ErrorActionPreference = 'Stop'
$ridTools = 'D:/Rust_Contact/util/tools/rid-map-downloader/0.1.0'
$env:GOCACHE = 'D:/Rust_Contact/util/tools/go-cache'
$env:GOMODCACHE = 'D:/Rust_Contact/util/tools/go-modules'
New-Item -ItemType Directory -Force $ridTools | Out-Null
Push-Location (Join-Path $PSScriptRoot 'map-downloader')
try {
go test ./...
if ($LASTEXITCODE -ne 0) { throw 'Go map downloader tests failed' }
go build -trimpath -ldflags '-s -w' -o (Join-Path $ridTools 'rid-map-downloader.exe') .
if ($LASTEXITCODE -ne 0) { throw 'Go map downloader build failed' }
Copy-Item -LiteralPath 'LICENSE-upstream.txt' -Destination $ridTools
$env:RID_MAP_DOWNLOADER = Join-Path $ridTools 'rid-map-downloader.exe'
Write-Output $env:RID_MAP_DOWNLOADER
} finally { Pop-Location }
@@ -0,0 +1,25 @@
Source: https://github.com/Cyclenerd/offline-map-tile-downloader
Pinned revision: 9b61800537b2c50a71345dfed3bbc0fcd8731711
Adaptation: RID headless JSON adapter; Web Mercator tile algorithm retained.
MIT License
Copyright (c) 2025 Matthew Drummonds
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.
+3
View File
@@ -0,0 +1,3 @@
module rid-map-downloader
go 1.22.0
+225
View File
@@ -0,0 +1,225 @@
// RID headless adapter derived from Cyclenerd/offline-map-tile-downloader (MIT).
// Upstream: 9b61800537b2c50a71345dfed3bbc0fcd8731711. See LICENSE-upstream.txt.
// Retains its Web Mercator tile algorithm; replaces web UI with a bounded JSON job.
package main
import (
"bytes"
"encoding/json"
"fmt"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"math"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
type bounds struct{ West, South, East, North float64 }
type request struct {
Bounds bounds
MinZoom, MaxZoom int
Layers []string
Output, BaseURL string
}
type tile struct {
layer string
x, y, z uint32
}
type progress struct {
Done uint64 `json:"done"`
Failed uint64 `json:"failed"`
}
// latLonToTile is from the pinned MIT upstream; clamp at Mercator world edges.
func latLonToTile(lat, lon float64, zoom uint32) (x, y uint32) {
latRad := lat * math.Pi / 180
n := math.Pow(2, float64(zoom))
x = uint32(n * ((lon + 180) / 360))
y = uint32(n * (1 - (math.Log(math.Tan(latRad)+1/math.Cos(latRad)) / math.Pi)) / 2)
if x >= uint32(n) {
x = uint32(n) - 1
}
if y >= uint32(n) {
y = uint32(n) - 1
}
return
}
func coverage(r request) ([]tile, error) {
b := r.Bounds
for _, v := range []float64{b.West, b.East, b.South, b.North} {
if math.IsNaN(v) || math.IsInf(v, 0) {
return nil, fmt.Errorf("invalid bounds")
}
}
if b.West < -180 || b.East > 180 || b.South < -85.051128 || b.North > 85.051128 || b.West >= b.East || b.South >= b.North || r.MinZoom < 0 || r.MaxZoom > 18 || r.MinZoom > r.MaxZoom || len(r.Layers) == 0 || len(r.Layers) > 4 {
return nil, fmt.Errorf("invalid coverage")
}
seen := map[string]bool{}
for _, l := range r.Layers {
if seen[l] || !(l == "vec_w" || l == "cva_w" || l == "img_w" || l == "cia_w") {
return nil, fmt.Errorf("invalid layer")
}
seen[l] = true
}
var tiles []tile
for z := uint32(r.MinZoom); z <= uint32(r.MaxZoom); z++ {
x0, y0 := latLonToTile(b.North, b.West, z)
x1, y1 := latLonToTile(b.South, b.East, z)
if uint64(x1-x0+1)*uint64(y1-y0+1)*uint64(len(r.Layers))+uint64(len(tiles)) > 20000 {
return nil, fmt.Errorf("coverage exceeds limit")
}
for _, l := range r.Layers {
for x := x0; x <= x1; x++ {
for y := y0; y <= y1; y++ {
tiles = append(tiles, tile{l, x, y, z})
}
}
}
}
return tiles, nil
}
func validImage(data []byte) bool {
if len(data) == 0 || len(data) > 2*1024*1024 {
return false
}
cfg, _, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil || cfg.Width != 256 || cfg.Height != 256 {
return false
}
_, _, err = image.Decode(bytes.NewReader(data))
return err == nil
}
func safePath(path string) bool {
for p := filepath.Clean(path); ; p = filepath.Dir(p) {
info, err := os.Lstat(p)
if err == nil && info.Mode()&os.ModeSymlink != 0 {
return false
}
if err != nil && !os.IsNotExist(err) {
return false
}
if filepath.Dir(p) == p {
return true
}
}
}
func store(path string, data []byte) error {
if !safePath(path) {
return fmt.Errorf("symlink output denied")
}
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return err
}
f, err := os.CreateTemp(filepath.Dir(path), ".rid-map-*.tmp")
if err != nil {
return err
}
name := f.Name()
defer os.Remove(name)
if _, err = f.Write(data); err != nil {
f.Close()
return err
}
if err = f.Sync(); err != nil {
f.Close()
return err
}
if err = f.Close(); err != nil {
return err
}
return os.Rename(name, path)
}
func fetch(client *http.Client, r request, t tile) error {
path := filepath.Join(r.Output, t.layer, fmt.Sprint(t.z), fmt.Sprint(t.x), fmt.Sprintf("%d.png", t.y))
if !safePath(path) {
return fmt.Errorf("invalid output")
}
if info, err := os.Stat(path); err == nil && info.Size() <= 2*1024*1024 {
if data, err := os.ReadFile(path); err == nil && validImage(data) {
return nil
}
}
resp, err := client.Get(fmt.Sprintf("%s/%s/%d/%d/%d", strings.TrimRight(r.BaseURL, "/"), t.layer, t.z, t.x, t.y))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("tile unavailable")
}
data, err := io.ReadAll(io.LimitReader(resp.Body, 2*1024*1024+1))
if err != nil {
return err
}
if !validImage(data) {
return fmt.Errorf("invalid image")
}
return store(path, data)
}
func run(input io.Reader, output io.Writer) error {
var r request
d := json.NewDecoder(io.LimitReader(input, 65537))
d.DisallowUnknownFields()
if err := d.Decode(&r); err != nil {
return err
}
u, err := url.Parse(r.BaseURL)
if err != nil || u.Scheme != "http" || u.Hostname() != "127.0.0.1" || u.Port() == "" || u.Path != "/api/maps/tile" || u.RawQuery != "" || u.User != nil {
return fmt.Errorf("only local tile proxy is allowed")
}
if !filepath.IsAbs(r.Output) || !safePath(r.Output) {
return fmt.Errorf("invalid output")
}
tiles, err := coverage(r)
if err != nil {
return err
}
client := &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }}
// A single ticker limits the whole pool, rather than each worker independently.
ticker := time.NewTicker(250 * time.Millisecond)
defer ticker.Stop()
jobs := make(chan tile)
var wg sync.WaitGroup
var mu sync.Mutex
p := progress{}
encoder := json.NewEncoder(output)
for i := 0; i < 4; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for t := range jobs {
<-ticker.C
err := fetch(client, r, t)
mu.Lock()
p.Done++
if err != nil {
p.Failed++
}
_ = encoder.Encode(p)
mu.Unlock()
}
}()
}
for _, t := range tiles {
jobs <- t
}
close(jobs)
wg.Wait()
if p.Failed > 0 {
return fmt.Errorf("some tiles failed")
}
return nil
}
func main() {
if err := run(os.Stdin, os.Stdout); err != nil {
fmt.Fprintln(os.Stderr, "map download failed")
os.Exit(1)
}
}
+75
View File
@@ -0,0 +1,75 @@
package main
import (
"bytes"
"encoding/json"
"image"
"image/png"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
)
func TestCoverageBoundaries(t *testing.T) {
r := request{Bounds: bounds{120.15, 30.28, 120.16, 30.29}, MinZoom: 11, MaxZoom: 11, Layers: []string{"vec_w", "cva_w", "img_w", "cia_w"}}
tiles, err := coverage(r)
if err != nil || len(tiles) != 4 {
t.Fatalf("coverage %d %v", len(tiles), err)
}
r.Bounds = bounds{-180, -85, 180, 85}
r.MaxZoom = 18
if _, err = coverage(r); err == nil {
t.Fatal("excessive range accepted")
}
r.MaxZoom = 19
if _, err = coverage(r); err == nil {
t.Fatal("zoom accepted")
}
}
func TestDownloadValidatesAndResumes(t *testing.T) {
var imageBytes bytes.Buffer
_ = png.Encode(&imageBytes, image.NewRGBA(image.Rect(0, 0, 256, 256)))
calls := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++; w.Write(imageBytes.Bytes()) }))
defer server.Close()
r := request{Bounds: bounds{120.15, 30.28, 120.16, 30.29}, MinZoom: 11, MaxZoom: 11, Layers: []string{"vec_w"}, Output: t.TempDir(), BaseURL: server.URL + "/api/maps/tile"}
body, _ := json.Marshal(r)
var output bytes.Buffer
if err := run(bytes.NewReader(body), &output); err != nil {
t.Fatal(err)
}
files, _ := filepath.Glob(filepath.Join(r.Output, "vec_w", "11", "*", "*.png"))
if len(files) != 1 {
t.Fatalf("files %v", files)
}
if err := run(bytes.NewReader(body), &output); err != nil {
t.Fatal(err)
}
if calls != 1 {
t.Fatal("existing valid tile downloaded again")
}
_ = os.WriteFile(files[0], []byte("bad"), 0600)
if err := run(bytes.NewReader(body), &output); err != nil {
t.Fatal(err)
}
if calls != 2 {
t.Fatal("corrupt tile not replaced")
}
r.BaseURL = "https://example.com/api/maps/tile"
body, _ = json.Marshal(r)
if run(bytes.NewReader(body), &output) == nil {
t.Fatal("external endpoint accepted")
}
}
func TestRejectsBrokenImage(t *testing.T) {
if validImage([]byte("<html>error</html>")) {
t.Fatal("invalid image accepted")
}
var b bytes.Buffer
_ = png.Encode(&b, image.NewRGBA(image.Rect(0, 0, 4096, 4096)))
if validImage(b.Bytes()) {
t.Fatal("oversized dimensions accepted")
}
}
+4 -1
View File
@@ -6,7 +6,7 @@ $ridRepo = Split-Path $PSScriptRoot -Parent
if (-not $OutputRoot) { $OutputRoot = Join-Path $ridRepo 'dist' }
$ridOutputRoot = [IO.Path]::GetFullPath($OutputRoot)
$ridDestination = Join-Path $ridOutputRoot 'FPV-RID-Rust'
$ridWhitelist = @('fpv-rid-registry.exe', '启动Rust版.cmd', '使用说明.md', 'third-party-licenses.txt', 'dependency-licenses.txt', 'build-info.json', 'SHA256SUMS.txt')
$ridWhitelist = @('fpv-rid-registry.exe', 'rid-map-downloader.exe', 'map-downloader-LICENSE.txt', '启动Rust版.cmd', '使用说明.md', 'third-party-licenses.txt', 'dependency-licenses.txt', 'build-info.json', 'SHA256SUMS.txt')
function Assert-CleanDestination {
if (Test-Path -LiteralPath $ridDestination) {
@@ -27,6 +27,7 @@ function Get-RidSourceManifest {
# Refuse a used deployment folder before building or changing any published files.
Assert-CleanDestination
& (Join-Path $PSScriptRoot 'build-map-downloader.ps1')
$ridStageRoot = Join-Path $ridOutputRoot ('.package-' + [guid]::NewGuid().ToString('N'))
$ridStage = Join-Path $ridStageRoot 'FPV-RID-Rust'
$ridTemporaryZip = Join-Path $ridStageRoot 'release.zip'
@@ -46,6 +47,8 @@ try {
if ($LASTEXITCODE -ne 0) { throw 'Cargo metadata failed' }
New-Item -ItemType Directory -Force -Path $ridStage | Out-Null
Copy-Item -LiteralPath (Join-Path $ridMetadata.target_directory 'release/fpv-rid-registry-fullstack.exe') -Destination (Join-Path $ridStage 'fpv-rid-registry.exe')
Copy-Item -LiteralPath $env:RID_MAP_DOWNLOADER -Destination (Join-Path $ridStage 'rid-map-downloader.exe')
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'map-downloader/LICENSE-upstream.txt') -Destination (Join-Path $ridStage 'map-downloader-LICENSE.txt')
Copy-Item -LiteralPath (Join-Path $ridRepo '启动Rust版.cmd') -Destination $ridStage
Copy-Item -LiteralPath (Join-Path $ridRepo 'doc/registry/rust/使用说明.md') -Destination $ridStage
Copy-Item -LiteralPath (Join-Path $ridRepo 'crates/web-ui/public/vendor/LICENSE.txt') -Destination (Join-Path $ridStage 'third-party-licenses.txt')
+3
View File
@@ -1,6 +1,9 @@
# Dot-source this file for the workspace's shared Rust installation.
$env:CARGO_HOME = 'D:\Rust_Contact\util\cargo'
$env:RUSTUP_HOME = 'D:\Rust_Contact\util\rustup'
if (-not $env:RID_MAP_DOWNLOADER) {
$env:RID_MAP_DOWNLOADER = 'D:/Rust_Contact/util/tools/rid-map-downloader/0.1.0/rid-map-downloader.exe'
}
if (($env:Path -split ';') -notcontains "$env:CARGO_HOME\bin") {
$env:Path = "$env:CARGO_HOME\bin;$env:Path"
}
+63
View File
@@ -0,0 +1,63 @@
// Actual Rust/Wasm + Go integration against an isolated data root and local fixtures.
// Does not use a real TianDiTu key or open any receiver transport.
import {mkdtemp,mkdir,writeFile,readFile} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import path from 'node:path';
import {spawn} from 'node:child_process';
import assert from 'node:assert/strict';
import {createRequire} from 'node:module';
const require=createRequire(import.meta.url);
const {chromium}=require('C:/Users/20143/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
const {PNG}=require('C:/Users/20143/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/pngjs');
const root=await mkdtemp(path.join(tmpdir(),'RID-map-settings-'));
const exe=process.argv[2]||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry-fullstack.exe';
const base='http://127.0.0.1:8787';
try{await fetch(base,{signal:AbortSignal.timeout(800)});throw Error('8787 is occupied; existing service preserved');}catch(e){if(e.message.includes('occupied'))throw e;}
const env={...process.env,RID_MAP_DOWNLOADER:process.env.RID_MAP_DOWNLOADER||'D:/Rust_Contact/util/tools/rid-map-downloader/0.1.0/rid-map-downloader.exe'};delete env.TIANDITU_TOKEN;
const fixture=new PNG({width:256,height:256});for(let i=0;i<fixture.data.length;i+=4){fixture.data[i]=25;fixture.data[i+1]=45;fixture.data[i+2]=65;fixture.data[i+3]=255;}const png=PNG.sync.write(fixture);
function xy(lon,lat,z){const n=2**z,r=lat*Math.PI/180;return [Math.floor((lon+180)/360*n),Math.floor((1-Math.log(Math.tan(r)+1/Math.cos(r))/Math.PI)/2*n)];}
const [x,y]=xy(120.155,30.285,11);
for(const layer of ['vec_w','cva_w','img_w','cia_w']){const dir=path.join(root,`maps/cache/${layer}/11/${x}`);await mkdir(dir,{recursive:true});await writeFile(path.join(dir,y+'.tile'),png);}
let child,browser,output='';const errors=[],csp=[];let report={};
function start(){child=spawn(exe,['--data-root',root],{env,windowsHide:true,stdio:['ignore','pipe','pipe']});child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);}
async function ready(){for(let i=0;i<150;i++){if(child.exitCode!==null)throw Error(output);try{if((await fetch(base+'/api/maps/preferences')).ok)return;}catch{}await new Promise(r=>setTimeout(r,100));}throw Error('server timeout');}
async function stop(){if(child?.exitCode===null){const done=new Promise(r=>child.once('exit',r));child.kill();await done;}}
const json=async(url,method='GET',body)=>{const r=await fetch(base+url,{method,headers:{'content-type':'application/json'},...(body?{body:JSON.stringify(body)}:{})});const v=await r.json();return {status:r.status,value:v};};
async function job(state){for(let i=0;i<150;i++){const v=(await json('/api/maps/downloads')).value.job;if(v?.state===state)return v;if(v?.state==='failed'&&state==='completed')throw Error(JSON.stringify(v));await new Promise(r=>setTimeout(r,100));}throw Error('job timeout '+state);}
try{
start();await ready();browser=await chromium.launch({headless:true,channel:'msedge'});const page=await browser.newPage({viewport:{width:1600,height:1000}});
page.on('pageerror',e=>errors.push(e.message));page.on('console',m=>{if(/Content Security Policy|Refused to/i.test(m.text()))csp.push(m.text());});
await page.goto(base);await page.locator('#home-app-settings').click();await page.locator('#appearance-view [data-open=maps]').click();await page.locator('#map-save').waitFor();await page.waitForFunction(()=>!document.querySelector('#map-save').disabled);
await page.waitForFunction(()=>window.ridMapSettings?.metrics()?.camera);
await page.locator('#map-settings-drawer [data-map-action=drawer]').click();assert.equal(await page.locator('#map-settings-drawer').isHidden(),true);await page.locator('.map-settings-head [data-map-action=drawer]').click();
await page.locator('.map-settings-head [data-map-action=point]').click();await page.locator('#settings-map').click({position:{x:220,y:220}});assert.match(await page.locator('#map-save-message').textContent(),/起始点已选定/);
await page.locator('#map-longitude').fill('181');await page.locator('#map-save').click();assert.match(await page.locator('#map-save-message').textContent(),/有效经纬度/);
await page.locator('#map-longitude').fill('116.4');await page.locator('#map-latitude').fill('39.9');await page.locator('#map-zoom').fill('12');await page.locator('#map-basemap').selectOption('road');await page.locator('#map-save').click();await page.waitForFunction(()=>document.querySelector('#map-save-message').textContent.includes('已保存'));
assert.equal((await json('/api/maps/preferences')).value.longitude,116.4);
// Unsaved fields survive a settings navigation within this document.
await page.locator('#map-longitude').fill('116.41');await page.locator('#map-settings-view [data-open=settings]').click();await page.locator('#appearance-view [data-open=maps]').click();assert.equal(await page.locator('#map-longitude').inputValue(),'116.41');await page.locator('#map-longitude').fill('116.4');
for(const [id,v]of Object.entries({'map-west':'120.15','map-south':'30.28','map-east':'120.16','map-north':'30.29','map-min-zoom':'11','map-max-zoom':'11'}))await page.locator('#'+id).fill(v);
await page.locator('#map-region-name').fill('验收常用区域');await page.locator('[data-map-action=region-save]').click();await page.locator('#map-save').click();await page.waitForFunction(()=>document.querySelector('#map-save-message').textContent.includes('已保存'));
await page.locator('#map-estimate').click();await page.waitForFunction(()=>document.querySelector('#map-estimate-message').textContent.includes('共 4 张'));
await page.locator('#map-download-start').click();const done=await job('completed');assert.equal(done.done,4);assert.equal(done.failed,0);
for(const layer of ['vec_w','cva_w','img_w','cia_w'])assert.deepEqual(await readFile(path.join(root,`maps/offline/${layer}/11/${x}/${y}.png`)),png);
// Offline files remain readable even after the online cache is no longer needed.
const tile=await fetch(base+`/api/maps/tile/vec_w/11/${x}/${y}`);assert.equal(tile.status,200);
const task={bounds:{west:120.15,south:30.28,east:120.16,north:30.29},minZoom:16,maxZoom:16,road:true,imagery:true};
assert.equal((await json('/api/maps/downloads','POST',task)).status,202);
assert.equal((await json('/api/maps/downloads','POST',task)).status,409);
await json('/api/maps/downloads/cancel','POST',{});await job('cancelled');
const failing={...task,bounds:{west:116.4,south:39.9,east:116.401,north:39.901},minZoom:11,maxZoom:11};await json('/api/maps/downloads','POST',failing);await job('failed');
assert.equal((await json('/api/maps/downloads/estimate','POST',{...task,minZoom:19})).status,400);
assert.equal((await fetch(base+'/api/maps/preferences',{headers:{origin:'https://foreign.invalid'}})).status,403);
// Real live renderer reads the persisted default; no telemetry is injected.
await page.goto(base+'/realtime');await page.waitForFunction(()=>window.ridMap?.metrics()?.mapReady);
const camera=await page.evaluate(()=>window.ridMap.metrics().camera);assert.ok(Math.abs(camera.center[0]-116.4)<.0001,JSON.stringify(camera));assert.ok(Math.abs(camera.center[1]-39.9)<.0001,JSON.stringify(camera));assert.equal(camera.zoom,12);
assert.equal(await page.evaluate(()=>window.ridMap.metrics().basemap),'road');
await page.locator('[data-open=settings]').first().click();await page.locator('#appearance-view [data-open=maps]').click();await page.waitForFunction(()=>!document.querySelector('#map-save').disabled);await page.waitForFunction(()=>window.ridMapSettings?.metrics()?.camera);
assert.equal(await page.locator('#map-region option').count(),2);await page.screenshot({path:path.resolve('previews/map-settings-live-C-20261023.png')});
await page.setViewportSize({width:800,height:1000});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
await stop();start();await ready();const reloaded=(await json('/api/maps/preferences')).value;assert.equal(reloaded.longitude,116.4);assert.equal(reloaded.regions[0].name,'验收常用区域');
assert.deepEqual(errors,[]);assert.deepEqual(csp,[]);
report={status:'PASS',root,camera,download:done,scenarios:['actual C drawer and MapLibre point selection','invalid coordinates','persistent default camera','draft retained across navigation','saved region reload','actual Go sidecar and four-layer offline raster validation','download cancellation and single-job limit','unavailable tiles fail honestly','foreign origin rejection','800px width','no page errors or CSP violations']};console.log(JSON.stringify(report));
}finally{await browser?.close();await stop();await writeFile(path.join(root,'server.log'),output);await writeFile(path.join(root,'report.json'),JSON.stringify(report,null,2));}
+98
View File
@@ -0,0 +1,98 @@
// Real SQLite, Rust/Wasm, Worker and WebGL acceptance. No physical transports opened.
import {mkdtemp,readFile,writeFile} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import path from 'node:path';
import http from 'node:http';
import net from 'node:net';
import {spawn} from 'node:child_process';
import {createRequire} from 'node:module';
import assert from 'node:assert/strict';
const {chromium}=createRequire(import.meta.url)('playwright');
const root=await mkdtemp(path.join(tmpdir(),'RID-target-lists-'));
const exe=process.argv[2]||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry-fullstack.exe';
const probe=net.createServer();await new Promise(r=>probe.listen(0,'127.0.0.1',r));const backend=probe.address().port;await new Promise(r=>probe.close(r));
let base,child,browser,heartbeat,output='';const errors=[],csp=[],sockets=new Set();
const proxy=http.createServer((req,res)=>{const headers={...req.headers,host:'127.0.0.1:8787'};if(headers.origin===base)headers.origin='http://127.0.0.1:8787';const upstream=http.request({hostname:'127.0.0.1',port:backend,path:req.url,method:req.method,headers},r=>{res.writeHead(r.statusCode,r.headers);r.pipe(res)});upstream.on('error',()=>{res.writeHead(502);res.end()});req.pipe(upstream)});
proxy.on('upgrade',(req,socket,head)=>{const upstream=net.connect(backend,'127.0.0.1');sockets.add(socket);sockets.add(upstream);upstream.on('connect',()=>{const headers={...req.headers,host:'127.0.0.1:8787'};if(headers.origin===base)headers.origin='http://127.0.0.1:8787';const nl=String.fromCharCode(13,10);upstream.write(['GET '+req.url+' HTTP/1.1',...Object.entries(headers).map(([k,v])=>k+': '+v),'',''].join(nl));if(head.length)upstream.write(head);socket.pipe(upstream);upstream.pipe(socket)});upstream.on('error',()=>socket.destroy());socket.on('error',()=>upstream.destroy());socket.on('close',()=>{upstream.destroy();sockets.delete(socket);sockets.delete(upstream)})});
const wait=ms=>new Promise(r=>setTimeout(r,ms));
function start(){child=spawn(exe,['--data-root',root,'--simulation-api'],{env:{...process.env,RID_TEST_PORT:String(backend),PATH:'C:\\Windows\\System32'},windowsHide:true,stdio:['ignore','pipe','pipe']});child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);child.on('error',e=>output+=e.message)}
async function stop(){if(child&&child.exitCode===null){const done=new Promise(r=>child.once('exit',r));child.kill();await done}}
async function ready(){for(let i=0;i<150;i++){if(child.exitCode!==null)throw Error(output);try{if((await fetch(base+'/api/target-lists')).ok)return}catch{}await wait(100)}throw Error('server timeout '+output)}
async function snapshot(){return(await fetch(base+'/api/target-lists')).json()}
async function save(id,kind,note='验收备注'){const current=await snapshot();const r=await fetch(base+'/api/target-lists/'+id,{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify({list_kind:kind,note,expected_revision:current.revision})});assert.equal(r.status,200);return r.json()}
let sequence=0;const targetIds=['LIST-WHITE','LIST-BLACK','LIST-OTHER'];
async function ingest(){sequence++;const frames=targetIds.map((target_id,i)=>({target_id,receiver_id:'TEST',source_epoch:1,sequence,longitude:120.15+i*.001,latitude:30.28+i*.001,altitude_m:100,heading_deg:40}));const r=await fetch(base+'/api/realtime/ingest',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(frames)});assert.equal(r.status,200)}
let report={};
try{
await new Promise(r=>proxy.listen(0,'127.0.0.1',r));base='http://127.0.0.1:'+proxy.address().port;start();await ready();
assert.deepEqual((await snapshot()).entries,[]);
await save('LIST-WHITE','white');await save('LIST-BLACK','black');await save('OFFLINE_001','white');
for(const file of ['target-lists.css','map-adapter.js'])assert.equal(await(await fetch(base+'/'+file)).text(),await readFile(path.join('dist/web-ui',file),'utf8'));
browser=await chromium.launch({headless:true,channel:'msedge'});const context=await browser.newContext({viewport:{width:1600,height:1000}});const page=await context.newPage();page.on('pageerror',e=>errors.push(e.message));page.on('console',m=>{if(/violates.*Content Security|Refused.*policy/i.test(m.text()))csp.push(m.text())});
await page.goto(base+'/realtime');await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();
const filters=page.getByRole('group',{name:'目标名单筛选'});
await page.waitForFunction(()=>![...document.querySelectorAll('.rt-target-list-filters button')].some(b=>b.disabled));
await ingest();heartbeat=setInterval(()=>ingest().catch(()=>{}),3000);
await page.getByRole('button',{name:'LIST-BLACK',exact:true}).waitFor();await page.waitForFunction(()=>window.ridMap?.metrics().mapReady&&window.ridMap.metrics().classifiedTargets.black===1);
assert.equal(await page.getByRole('button',{name:'LIST-WHITE',exact:true}).locator('.rt-list-badge').getAttribute('data-kind'),'white');
assert.equal(await page.getByRole('button',{name:'LIST-OTHER',exact:true}).locator('.rt-list-badge').getAttribute('data-kind'),'unknown');
const blackEvents=()=>page.locator('.live-events li[data-alert=true]').filter({hasText:'LIST-BLACK'});
await blackEvents().waitFor();for(let i=0;i<5;i++)await ingest();await wait(500);assert.equal(await blackEvents().count(),1);
await page.getByRole('button',{name:'LIST-BLACK',exact:true}).click();await page.locator('.rt-detail-classification').waitFor();
await page.screenshot({path:path.join(root,'classified-workspace.png')});
await filters.getByRole('button',{name:/^白名单/}).click();await page.waitForFunction(()=>window.ridMap.metrics().visibleTargets===1);assert.equal(await page.locator('.rt-target').count(),1);assert.equal(await page.evaluate(()=>window.ridMap.metrics().targets),3);
await filters.getByRole('button',{name:/^全部/}).click();await page.getByRole('button',{name:'LIST-WHITE',exact:true}).click();
await page.getByRole('button',{name:'加入黑名单',exact:true}).click();
await page.waitForFunction(()=>window.ridMap.metrics().classifiedTargets.black===2);assert.equal(await page.getByRole('button',{name:'LIST-WHITE',exact:true}).locator('.rt-list-badge').getAttribute('data-kind'),'black');
await page.locator('.rt-detail-classification').getByRole('button',{name:'加入黑名单',exact:true}).click();await wait(350);
assert.equal(await page.locator('.live-events li[data-alert=true]').filter({hasText:'LIST-WHITE'}).count(),1);
await page.getByRole('button',{name:'管理黑白名单',exact:true}).click();await page.locator('#rt-list-manager').waitFor();assert.equal((await page.locator('#rt-list-manager').innerText()).includes('rows.get'),false);assert.equal(await page.locator('.rt-list-pagination').getByRole('button',{name:'下一页',exact:true}).isDisabled(),true);
await page.locator('#rt-list-entry-id').fill('OFFLINE_002');await page.locator('#rt-list-entry-kind').selectOption('white');await page.locator('#rt-list-entry-note').fill('离线条目');await page.locator('#rt-list-entry-form .primary').click();
await page.locator('.rt-list-manager-footer').filter({hasText:'已将 OFFLINE_002 保存为白名单'}).waitFor();assert.equal(await page.evaluate(()=>window.ridMap.metrics().targets),3);
assert.equal((await(await fetch(base+'/api/records?page=1')).json()).total,0);
const offline=page.locator('.rt-list-row[data-target-id=OFFLINE_002]');await offline.getByRole('button',{name:'编辑',exact:true}).click();assert.equal(await page.locator('#rt-list-entry-id').isEditable(),false);
await page.locator('#rt-list-entry-note').fill('<img src=x onerror=alert(1)>人工备注');await page.locator('#rt-list-entry-form .primary').click();await offline.filter({hasText:'人工备注'}).waitFor();assert.equal(await offline.locator('img').count(),0);
const otherContext=await browser.newContext({viewport:{width:1280,height:900}}),other=await otherContext.newPage();await other.goto(base+'/realtime');await other.waitForFunction(()=>![...document.querySelectorAll('.rt-target-list-filters button')].some(b=>b.disabled));
await other.getByRole('button',{name:'管理黑白名单',exact:true}).click();await other.locator('.rt-list-row[data-target-id=OFFLINE_002]').filter({hasText:'人工备注'}).waitFor();
await page.locator('#rt-list-entry-note').fill('尚未保存的备注');await save('OFFLINE_002','white','来自其他浏览器');
await offline.filter({hasText:'来自其他浏览器'}).waitFor({timeout:12000});assert.equal(await page.locator('#rt-list-entry-note').inputValue(),'尚未保存的备注');
await page.getByRole('button',{name:'新增条目',exact:true}).click();await page.locator('#rt-list-entry-id').fill('LIST-OTHER');await page.locator('#rt-list-entry-note').fill('冲突后保留草稿');
let releaseRequest,heldRequest;const gate=new Promise(r=>releaseRequest=r),held=new Promise(r=>heldRequest=r);let intercept=true;
await page.route('**/api/target-lists/LIST-OTHER',async route=>{if(route.request().method()==='PUT'&&intercept){intercept=false;heldRequest();await gate;}await route.continue()});
await page.locator('#rt-list-entry-form .primary').click();await held;assert.equal(await page.locator('#rt-list-entry-id').isDisabled(),true);await save('REMOTE_001','white');releaseRequest();
await page.locator('.rt-list-manager-footer p.error').filter({hasText:'其他页面修改'}).waitFor();await page.locator('.rt-list-row[data-target-id=REMOTE_001]').waitFor();assert.equal(await page.locator('#rt-list-entry-note').inputValue(),'冲突后保留草稿');
await page.unroute('**/api/target-lists/LIST-OTHER');await page.locator('#rt-list-entry-form .primary').click();await page.locator('.rt-list-row[data-target-id=LIST-OTHER]').waitFor();
await page.locator('#rt-list-entry-note').fill('保存失败仍保留');await page.route('**/api/target-lists/LIST-OTHER',r=>r.fulfill({status:500,contentType:'application/json',body:JSON.stringify({error:'隔离保存失败'})}));
await page.locator('#rt-list-entry-form .primary').click();await page.locator('.rt-list-manager-footer p.error').filter({hasText:'隔离保存失败'}).waitFor();assert.equal(await page.locator('#rt-list-entry-note').inputValue(),'保存失败仍保留');assert.equal((await snapshot()).entries.find(e=>e.target_id==='LIST-OTHER').note,'冲突后保留草稿');await page.unroute('**/api/target-lists/LIST-OTHER');
await page.getByRole('button',{name:'新增条目',exact:true}).click();await page.locator('#rt-list-entry-id').fill('bad id');await page.locator('#rt-list-entry-form').evaluate(f=>f.dispatchEvent(new Event('submit',{bubbles:true,cancelable:true})));await page.locator('.rt-list-manager-footer p.error').filter({hasText:'目标标识须'}).waitFor();
await page.screenshot({path:path.join(root,'manager-validation.png')});
await page.locator('.rt-list-row[data-target-id=LIST-OTHER]').getByRole('button',{name:'移除',exact:true}).click();await page.waitForFunction(()=>window.ridMap.metrics().classifiedTargets.black===2);
await page.route('**/api/target-lists?revision=*',r=>r.fulfill({status:503,contentType:'application/json',body:'{}'}));
await page.locator('#rt-list-manager .rt-list-sync-error').filter({hasText:'暂用上次名单'}).waitFor({timeout:12000});
assert.equal(await page.evaluate(()=>window.ridMap.metrics().classifiedTargets.black),2);
await page.unroute('**/api/target-lists?revision=*');await page.locator('#rt-list-manager .rt-list-sync-error').getByRole('button',{name:'重试',exact:true}).click();await page.locator('#rt-list-manager .rt-list-sync-error').waitFor({state:'hidden'});
const unavailableContext=await browser.newContext(),unavailable=await unavailableContext.newPage();
await unavailable.route('**/api/target-lists**',r=>r.fulfill({status:503,contentType:'application/json',body:'{}'}));await unavailable.goto(base+'/realtime');
await unavailable.locator('.rt-list-sync-error').filter({hasText:'名单读取失败'}).first().waitFor();await unavailable.locator('.rt-target').first().waitFor();
assert.equal(await unavailable.locator('.rt-target .rt-list-badge[data-kind=unavailable]').count(),3);
assert.equal(await unavailable.getByRole('group',{name:'目标名单筛选'}).getByRole('button',{name:/^黑名单/}).isDisabled(),true);assert.ok((await unavailable.getByRole('group',{name:'目标名单筛选'}).getByRole('button',{name:/^黑名单/}).innerText()).includes('—'));
await unavailableContext.close();
const sizes=[[1600,1000],[1366,600],[1080,900],[390,844]];const geometry=[];
for(const [width,height]of sizes){await page.setViewportSize({width,height});await wait(250);await page.locator('#rt-list-entry-form .primary').scrollIntoViewIfNeeded();const box=await page.locator('#rt-list-entry-form .primary').boundingBox();assert.ok(box.x>=0&&box.x+box.width<=width&&box.y>=48&&box.y+box.height<=height+1);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.locator('.rt-list-manager-body').evaluate(e=>e.scrollTop=0);await page.screenshot({path:path.join(root,'manager-'+width+'.png')});geometry.push({width,height})}
await page.setViewportSize({width:1280,height:720});await page.evaluate(()=>document.documentElement.style.zoom='2');await page.locator('#rt-list-entry-form .primary').scrollIntoViewIfNeeded();assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.screenshot({path:path.join(root,'manager-zoom200.png')});await page.evaluate(()=>document.documentElement.style.zoom='');
await page.keyboard.press('Escape');await page.locator('#rt-list-manager').waitFor({state:'hidden'});await page.waitForFunction(()=>['rt-list-manager-open','rt-list-manager-from-directory'].includes(document.activeElement.id));
await page.setViewportSize({width:1600,height:1000});await otherContext.close();
const persisted=await snapshot();clearInterval(heartbeat);await stop();start();await ready();assert.deepEqual(await snapshot(),persisted);
await page.reload();await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();await ingest();await page.waitForFunction(()=>window.ridMap.metrics().targets===3&&window.ridMap.metrics().classifiedTargets.black===2);assert.equal(await page.getByRole('button',{name:'LIST-OTHER',exact:true}).locator('.rt-list-badge').getAttribute('data-kind'),'unknown');
// Registration remains independent: registered targets are not automatically trusted.
for(const [id,expectedKind]of [['LIST-BLACK','black'],['LIST-OTHER','unknown']]){
const response=await fetch(base+'/api/records',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({serialNo:id})});assert.equal(response.status,200);const record=(await response.json()).record;
await page.getByRole('button',{name:id,exact:true}).click();await page.locator('.rt-details').filter({hasText:'已匹配本地登记档案'}).waitFor();
assert.equal(await page.locator('.rt-detail-classification .rt-list-badge').getAttribute('data-kind'),expectedKind);
assert.equal((await fetch(base+'/api/records/'+record.id,{method:'DELETE'})).status,200);
}
assert.equal((await snapshot()).entries.find(e=>e.target_id==='LIST-BLACK').list_kind,'black');
assert.equal(await page.locator('.mc-map-toolstrip').count(),0);assert.equal(await page.evaluate(()=>window.ridMap.metrics().camera.pitch),0);
assert.deepEqual(errors,[]);assert.deepEqual(csp,[]);
report={status:'PASS',root,exe,geometry,errors,csp,revision:persisted.revision,entries:persisted.entries.length,checks:['exact persisted membership independent of registration','online quick marking and offline entry','map and directory filtering without telemetry loss','black alert deduplication','safe notes and reactive remote updates','cross-browser sync preserves unsaved draft','optimistic concurrency and failed save rollback','busy controls and ID validation','removal restores unclassified','four viewports and 200% zoom','escape return focus','restart persistence','failed initial load and stale snapshot recovery','topdown map and removed toolbar preserved']};console.log(JSON.stringify(report));
}catch(error){console.log('FAILED ROOT',root,error.stack);if(browser){const p=browser.contexts()[0]?.pages()[0];if(p)await p.screenshot({path:path.join(root,'failure.png')}).catch(()=>{});}throw error;}finally{clearInterval(heartbeat);if(browser)await browser.close();await stop();for(const socket of sockets)socket.destroy();const closed=new Promise(r=>proxy.close(r));proxy.closeAllConnections();await closed;await writeFile(path.join(root,'report.json'),JSON.stringify(report,null,2));await writeFile(path.join(root,'server.log'),output)}