Commit a7194724 by liimin

视觉调整

1 parent 16ba6bfb
...@@ -142,6 +142,45 @@ function reject(reason) { ...@@ -142,6 +142,45 @@ function reject(reason) {
stats.rejectedReason.set(reason, (stats.rejectedReason.get(reason) ?? 0) + 1); stats.rejectedReason.set(reason, (stats.rejectedReason.get(reason) ?? 0) + 1);
} }
/**
* 一行按 ',' 切成字段,认 CSV 的双引号。
*
* 为什么不能一直裸 split(','):真实表格里地址内部就带半角逗号
* (「龙岗中心城龙平西路南侧,龙福路以北」「福永大道33,39号」这类),
* 转成 CSV 时这些字段必须整段加引号。裸切会把这一行切成 6~8 段,
* 于是 parseRow 判成「字段数不为 5」整行丢 —— 丢的行不报错、不计数,
* 表现就是「导入同一份表格比内置数据多出几起」,属于最难查的那类账对不上。
*
* 规则与浏览器导入那条路的 splitCsvLineQuoted(data/ingestCore.ts)逐字一致,
* 两处只要有一处改了,ingestArtifacts.test.ts 就会红。
*/
function splitLine(line) {
if (line.indexOf('"') < 0) return line.split(',');
const out = [];
let cur = '';
let inQuote = false;
for (let i = 0; i < line.length; i += 1) {
const ch = line[i];
if (inQuote) {
if (ch === '"') {
if (line[i + 1] === '"') {
cur += '"';
i += 1;
} else {
inQuote = false;
}
} else cur += ch;
} else if (ch === '"') {
inQuote = true;
} else if (ch === ',') {
out.push(cur);
cur = '';
} else cur += ch;
}
out.push(cur);
return out;
}
/** 解析一行 → 结构化记录;不合法返回 null 并计入拒收统计,绝不静默丢弃 */ /** 解析一行 → 结构化记录;不合法返回 null 并计入拒收统计,绝不静默丢弃 */
function parseRow(fields, lineNo) { function parseRow(fields, lineNo) {
if (fields.length !== 5) { if (fields.length !== 5) {
...@@ -372,7 +411,7 @@ for await (const rawLine of rl) { ...@@ -372,7 +411,7 @@ for await (const rawLine of rl) {
if (line.startsWith('案件号')) continue; if (line.startsWith('案件号')) continue;
} }
const rec = parseRow(line.split(','), lineNo); const rec = parseRow(splitLine(line), lineNo);
if (!rec) continue; if (!rec) continue;
stats.total += 1; stats.total += 1;
......
#!/usr/bin/env node
/**
* 把业务方给的原始表格(.xlsx)转成离线管线认的那份 CSV:data/raw/incidents.sample.csv。
*
* 为什么要有这一步(而不是把 xlsx 直接喂给 preprocess.mjs):
* 内置数据的管线(preprocess.mjs)读的是**行式 CSV**,它按 ',' 切列、按位置取字段,
* 图的是首屏那三个 JSON 产物可复现、可 diff。而浏览器导入那条路(ingestCore.ts)
* 才支持 xlsx。两条路必须吃同一份表格才能对账(ingestArtifacts.test.ts 盯的就是这件事),
* 所以换内置数据时统一在这里落成 CSV,xlsx 只作为来源、不进管线。
*
* 三个转换细节,每一个都会让数据静默变味,所以都做了显式处理:
*
* 1) 报案时间是 Excel 日期序列号(例如 46284.6379166667),不是字符串。
* 按 1900 日历(序列号 − 25569 天)折算成 UTC 壁钟再打成 'YYYY-MM-DD HH:mm:ss',
* 与 preprocess/ingestCore 认的写法一致;表格里若混着文本时间,原样透传。
* 注意不能按本机时区换算:那是「Excel 里显示出来的那一刻」,跟着机器跑就会整体偏移。
*
* 2) 经纬度在源表里是文本,且带着浮点尾巴(114.31331899999998 这种)。
* 统一按 6 位小数归一(管线存的就是 lng×1e6 的整数,6 位小数与它一一对应,
* 不多不少:既抹掉浮点噪声,也不改变任何一个入库坐标)。
*
* 3) 地址里有半角逗号(「龙平西路南侧,龙福路以北」这类),CSV 必须加引号包住。
* 下游两条流水线都认 RFC4180 的引号写法(preprocess 里见 splitLine、
* ingestCore 里见 splitCsvLineQuoted),所以这里不删逗号、不改一个字:
* 改标点等于改数据,而这份表是要拿去和原始表格逐行核对的。
*
* 用法:node scripts/xlsx-to-raw-csv.mjs <原始表格.xlsx> [--out=<路径>]
* 然后跑 node scripts/preprocess.mjs 重生成 public/data/*.json
*/
import fs from 'node:fs';
import path from 'node:path';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, '..');
const OUT_CSV = path.join(ROOT, 'data/raw/incidents.sample.csv');
const HEADER = ['案件号', '出险地点', '报案时间', '经度', '纬度'];
const args = process.argv.slice(2);
const srcArg = args.find((a) => !a.startsWith('--'));
const outArg = args.find((a) => a.startsWith('--out='));
const OUT = outArg ? path.resolve(ROOT, outArg.slice('--out='.length)) : OUT_CSV;
if (!srcArg) {
console.error('用法:node scripts/xlsx-to-raw-csv.mjs <原始表格.xlsx> [--out=<路径>]');
process.exit(1);
}
const SRC = path.resolve(srcArg);
if (!fs.existsSync(SRC)) {
console.error(`[csv] 找不到源表格:${SRC}`);
process.exit(1);
}
// xlsx 是项目依赖(浏览器导入也用同一个包),从 node_modules 直接取,不额外装东西
const require = createRequire(import.meta.url);
const XLSX = require('xlsx');
/**
* Excel 序列号 → 'YYYY-MM-DD HH:mm:ss'。
*
* 25569 = 1899-12-30 到 1900-01-01 那套 1900 日历下「序列号 1」对应的天数差(含 Excel 那个
* 不存在的 1900-02-29 的偏移)。全程用 UTC 取值器:壁钟照抄,不受本机时区影响。
* 源表 WorkbookProps.date1904 为 false(1900 日历),换表时若这一项变成 true 需要另加 1462 天。
*/
function serialToText(v) {
const ms = Math.round((v - 25569) * 86400000);
const d = new Date(ms);
const p = (n) => String(n).padStart(2, '0');
return (
`${d.getUTCFullYear()}-${p(d.getUTCMonth() + 1)}-${p(d.getUTCDate())} ` +
`${p(d.getUTCHours())}:${p(d.getUTCMinutes())}:${p(Math.floor(d.getUTCSeconds()))}`
);
}
/** 6 位小数:与产物里的 lng/lat×1e6 整数一一对应,只抹浮点噪声,不移动任何一个点 */
function coordText(v) {
const n = Number(v);
if (!Number.isFinite(n)) return String(v).trim();
return n.toFixed(6);
}
/** CSV 引号规则:含逗号、引号、换行的字段才加引号,其余原样(模版数据大多不加,读起来也干净) */
function field(s) {
const t = String(s);
return /[",\n\r]/.test(t) ? `"${t.replace(/"/g, '""')}"` : t;
}
const wb = XLSX.readFile(SRC, { cellDates: false });
const sheetName = wb.SheetNames[0];
const date1904 = !!wb.Workbook?.WBProps?.date1904;
if (date1904) {
console.error('[csv] 这份表用的是 1900 之外的另一套日历(date1904),序列号换算要先调整,已终止');
process.exit(1);
}
const rows = XLSX.utils.sheet_to_json(wb.Sheets[sheetName], {
header: 1,
raw: true,
defval: '',
});
if (!rows.length) {
console.error(`[csv] 工作表「${sheetName}」是空的`);
process.exit(1);
}
// 表头按位置认,不按名字猜:源表列序若与模板不同,必须在这里拦下来,
// 而不是让下游把经纬度当时间解析、把整列地址读成空
const head = rows[0].map((c) => String(c).trim());
if (head.join(',') !== HEADER.join(',')) {
console.error(
`[csv] 表头与模板不一致:\n 期望 ${HEADER.join(',')}\n 实到 ${head.join(',')}\n` +
' 请先在源表里按模板列序整理,再重跑本脚本(列名对不上时绝不猜)',
);
process.exit(1);
}
const lines = [HEADER.join(',')];
const report = {
数据行: 0,
空行跳过: 0,
字段数不为5: 0,
案件号非纯数字: 0,
时间按文本透传: 0,
坐标非数值: 0,
};
const problems = [];
const seenCaseNo = new Map();
let dup = 0;
let tsMin = Infinity;
let tsMax = -Infinity;
for (let i = 1; i < rows.length; i += 1) {
const r = rows[i];
if (!r || r.every((c) => c === '' || c === null || c === undefined)) {
report.空行跳过 += 1;
continue;
}
if (r.length !== 5) {
report.字段数不为5 += 1;
if (problems.length < 5) problems.push(`第 ${i + 1} 行有 ${r.length} 列:${JSON.stringify(r)}`);
continue;
}
const [caseNoRaw, address, time, lngRaw, latRaw] = r;
const caseNo = String(caseNoRaw).trim();
if (!/^\d{15,24}$/.test(caseNo)) {
report.案件号非纯数字 += 1;
if (problems.length < 5) problems.push(`第 ${i + 1} 行案件号不成样:${caseNo}`);
continue;
}
const prevLine = seenCaseNo.get(caseNo);
if (prevLine !== undefined) {
dup += 1;
if (problems.length < 5) problems.push(`第 ${i + 1} 行案件号与第 ${prevLine} 行重复:${caseNo}`);
} else {
seenCaseNo.set(caseNo, i + 1);
}
let timeText;
if (typeof time === 'number' && Number.isFinite(time)) {
timeText = serialToText(time);
} else {
timeText = String(time).trim();
report.时间按文本透传 += 1;
}
if (!timeText) {
report.坐标非数值 += 1;
if (problems.length < 5) problems.push(`第 ${i + 1} 行报案时间为空`);
continue;
}
const lng = Number(lngRaw);
const lat = Number(latRaw);
if (!Number.isFinite(lng) || !Number.isFinite(lat)) {
report.坐标非数值 += 1;
if (problems.length < 5)
problems.push(`第 ${i + 1} 行经纬度读不出数:${JSON.stringify([lngRaw, latRaw])}`);
continue;
}
report.数据行 += 1;
// 时间排序性只用来打报告:管线自己按 min/max 收范围,这里不改任何行序
const epoch = Date.parse(timeText.replace(/\//g, '-').replace(' ', 'T') + '+08:00');
if (Number.isFinite(epoch)) {
if (epoch < tsMin) tsMin = epoch;
if (epoch > tsMax) tsMax = epoch;
}
lines.push([field(caseNo), field(String(address).trim()), field(timeText), coordText(lng), coordText(lat)].join(','));
}
fs.writeFileSync(OUT, lines.join('\n') + '\n', 'utf8');
const rel = path.relative(ROOT, OUT);
console.log(`[csv] 来源:${path.basename(SRC)}(工作表「${sheetName}」)`);
console.log(`[csv] 写出:${rel},${report.数据行} 行 + 表头`);
console.table(report);
if (dup) console.warn(`[csv] ⚠️ 案件号重复 ${dup} 处:内置管线不去重,这些行会各自计入起数`);
if (problems.length) {
console.warn('[csv] 需要人工确认的样本:');
for (const p of problems) console.warn(' · ' + p);
}
if (Number.isFinite(tsMin) && Number.isFinite(tsMax)) {
const f = (ms) => new Date(ms + 8 * 3600 * 1000).toISOString().slice(0, 19).replace('T', ' ');
console.log(`[csv] 报案时间跨度(北京时间):${f(tsMin)} — ${f(tsMax)}`);
}
console.log('[csv] 下一步:node scripts/preprocess.mjs 重生成 public/data/*.json');
...@@ -5,15 +5,11 @@ import { ...@@ -5,15 +5,11 @@ import {
isDockOpen, isDockOpen,
isFocusQuiet, isFocusQuiet,
useHeatmapStore, useHeatmapStore,
type PerfSnapshot,
type SpotlightView, type SpotlightView,
} from '@/store/useHeatmapStore'; } from '@/store/useHeatmapStore';
import { GRID } from './aggregate/grid'; import { GRID } from './aggregate/grid';
import type { import type { AggregateResult, Filter, SpotlightCell, SpotlightResult } from './aggregate/types';
AggregateResult,
Filter,
SpotlightCell,
SpotlightResult,
} from './aggregate/types';
import { aggregateClient } from './aggregate/aggregateClient'; import { aggregateClient } from './aggregate/aggregateClient';
import { rememberViewportAggregate } from './aggregate/viewSnapshot'; import { rememberViewportAggregate } from './aggregate/viewSnapshot';
import { ensureDetailLoaded } from './data/detailLoader'; import { ensureDetailLoaded } from './data/detailLoader';
...@@ -24,11 +20,7 @@ import { ClusterLayer, type BucketHit } from './map/ClusterLayer'; ...@@ -24,11 +20,7 @@ import { ClusterLayer, type BucketHit } from './map/ClusterLayer';
import { countBackgroundBuckets, toSignificanceMask } from './map/significance'; import { countBackgroundBuckets, toSignificanceMask } from './map/significance';
import { HotspotLayer } from './map/HotspotLayer'; import { HotspotLayer } from './map/HotspotLayer';
import { CasePinLayer } from './map/CasePinLayer'; import { CasePinLayer } from './map/CasePinLayer';
import { import { SpotlightLayer, type SpotlightData, type SpotlightUnitPaint } from './map/SpotlightLayer';
SpotlightLayer,
type SpotlightData,
type SpotlightUnitPaint,
} from './map/SpotlightLayer';
import { SpotlightKey } from './SpotlightKey'; import { SpotlightKey } from './SpotlightKey';
import { import {
CASE_FOCUS_MS, CASE_FOCUS_MS,
...@@ -39,6 +31,7 @@ import { ...@@ -39,6 +31,7 @@ import {
} from './map/focusView'; } from './map/focusView';
import { addCell, addPoint, emptyBounds, finishBounds } from './map/spotlightGeometry'; import { addCell, addPoint, emptyBounds, finishBounds } from './map/spotlightGeometry';
import { M_PER_EQUATOR } from './map/hotspotGeometry'; import { M_PER_EQUATOR } from './map/hotspotGeometry';
import { Frame } from './map/viewFrame';
import { BucketCard } from './detail/BucketCard'; import { BucketCard } from './detail/BucketCard';
import { MapKeyGuide } from './MapKeyGuide'; import { MapKeyGuide } from './MapKeyGuide';
import { fmtCompact, fmtInt, fmtMs, placeNameOf } from '@/utils/format'; import { fmtCompact, fmtInt, fmtMs, placeNameOf } from '@/utils/format';
...@@ -46,9 +39,25 @@ import { fmtCompact, fmtInt, fmtMs, placeNameOf } from '@/utils/format'; ...@@ -46,9 +39,25 @@ import { fmtCompact, fmtInt, fmtMs, placeNameOf } from '@/utils/format';
/** 拖动 / 缩放后重新聚合的防抖时长。太短会在连续缩放时反复整表扫,太长会有明显空窗 */ /** 拖动 / 缩放后重新聚合的防抖时长。太短会在连续缩放时反复整表扫,太长会有明显空窗 */
const REFRESH_DEBOUNCE_MS = 90; const REFRESH_DEBOUNCE_MS = 90;
/**
* 筛选变化后重算统计的防抖时长。比聚合那 90ms 长一点:
* 统计是「命中几十万点重归一遍维度」,多选区连点两下、时间档连切两下,
* 中间那一次的结果本来就不该给人看,而扫一遍的几十到几百毫秒是实打实的主线程占用。
* 榜单晚一百多毫秒长出来没人看得出来,界面按下去不动却人人都看得到。
*/
const STATS_DEBOUNCE_MS = 160;
/** 黑点分析的防抖。降噪强度/平滑半径是滑杆,不按住拖到底会连发十几次全量分析 */ /** 黑点分析的防抖。降噪强度/平滑半径是滑杆,不按住拖到底会连发十几次全量分析 */
const ANALYSIS_DEBOUNCE_MS = 220; const ANALYSIS_DEBOUNCE_MS = 220;
/**
* 松手后过多久把毛玻璃的模糊恢复回去。
*
* 不能立刻恢复:松手那一拍紧接着就是重新聚合与重喂热力,同一帧里再挂回一次全屏重模糊,
* 等于把卡顿原封不动挪到松手那一下。也不能太久:静止时的外观必须和原来一致。
*/
const GLASS_RESTORE_MS = 140;
/** 深圳跨径不到 0.5 个纬度,米↔像素换算统一按这个参考纬度取,与 HotspotLayer 的画法一致 */ /** 深圳跨径不到 0.5 个纬度,米↔像素换算统一按这个参考纬度取,与 HotspotLayer 的画法一致 */
const LAT_CENTER = 22.55; const LAT_CENTER = 22.55;
...@@ -102,7 +111,7 @@ const BRIGHTEN_MAX_POINTS = 80; ...@@ -102,7 +111,7 @@ const BRIGHTEN_MAX_POINTS = 80;
function excludeUnderDrawer( function excludeUnderDrawer(
keep: Uint8Array | null, keep: Uint8Array | null,
st: { drawerOpen: boolean; roster: unknown; heatRadius: number }, st: { drawerOpen: boolean; roster: unknown; heatRadius: number },
map: AMap.Map, frame: Frame,
agg: AggregateResult, agg: AggregateResult,
): Uint8Array | null { ): Uint8Array | null {
// 右缘那一张抽屉位有四种来源(明细 / 榜单 / 案件清单 / 点位清单),盖住的地一样多, // 右缘那一张抽屉位有四种来源(明细 / 榜单 / 案件清单 / 点位清单),盖住的地一样多,
...@@ -119,8 +128,9 @@ function excludeUnderDrawer( ...@@ -119,8 +128,9 @@ function excludeUnderDrawer(
let removed = 0; let removed = 0;
for (let i = 0; i < keep.length; i += 1) { for (let i = 0; i < keep.length; i += 1) {
if (keep[i] !== 1) continue; if (keep[i] !== 1) continue;
const p = map.lngLatToContainer([agg.lng[i] / 1e6, agg.lat[i] / 1e6]); // 投影走自绘层那套换算(每点两次乘加),不再逐点向地图要一个新建的坐标对象
if (p.x >= limit) { const x = frame.x(agg.lng[i] / 1e6);
if (x >= limit) {
out[i] = 0; out[i] = 0;
removed += 1; removed += 1;
} }
...@@ -129,6 +139,39 @@ function excludeUnderDrawer( ...@@ -129,6 +139,39 @@ function excludeUnderDrawer(
} }
/** /**
* 热力层这一屏的全部输入。少认一样就会出现「以为没变、其实深浅该换了」的错画,
* 所以宁可把整份列出来:那批桶、那张过滤表、抽屉在不在、缩放、中心、画布尺寸。
*/
type HeatKey = [
AggregateResult,
Uint8Array | null,
boolean,
number,
number,
number,
number,
number,
];
function sameHeatKey(a: HeatKey | null, b: HeatKey): boolean {
if (!a) return false;
for (let i = 0; i < a.length; i += 1) if (a[i] !== b[i]) return false;
return true;
}
/** 把一帧的投影基准摆好。与各自绘层用的是同一个 Frame,口径不会分家 */
function projector(
frame: Frame,
map: AMap.Map,
zoom: number,
center: { getLng(): number; getLat(): number },
size: { width: number; height: number },
): Frame {
frame.set(map, zoom, center.getLng(), center.getLat(), size.width, size.height);
return frame;
}
/**
* 榜单那一行换成屏上的一档,四种画法共用这一份。 * 榜单那一行换成屏上的一档,四种画法共用这一份。
* *
* 起数以 Worker 回传的那一个为准 —— 它和屏上那些格子出自同一次归格,牌子念的数因此 * 起数以 Worker 回传的那一个为准 —— 它和屏上那些格子出自同一次归格,牌子念的数因此
...@@ -227,7 +270,6 @@ function spotlightFrame(view: SpotlightView, result: SpotlightResult | null) { ...@@ -227,7 +270,6 @@ function spotlightFrame(view: SpotlightView, result: SpotlightResult | null) {
} }
export function MapStage() { export function MapStage() {
const containerRef = useRef<HTMLDivElement>(null); const containerRef = useRef<HTMLDivElement>(null);
const wrapRef = useRef<HTMLDivElement>(null); const wrapRef = useRef<HTMLDivElement>(null);
...@@ -242,6 +284,17 @@ export function MapStage() { ...@@ -242,6 +284,17 @@ export function MapStage() {
const aggRef = useRef<AggregateResult | null>(null); const aggRef = useRef<AggregateResult | null>(null);
const timerRef = useRef<number | null>(null); const timerRef = useRef<number | null>(null);
const analysisTimerRef = useRef<number | null>(null); const analysisTimerRef = useRef<number | null>(null);
/** 热力层最近一次的输入指纹与它算出的读数。两者一起才是「这次不必重喂」的凭据 */
const heatKeyRef = useRef<HeatKey | null>(null);
const heatReadoutRef = useRef<Partial<PerfSnapshot>>({
heatPoints: 0,
backgroundBuckets: 0,
heatGridPx: GRID.gridPx,
});
/** 只服务抽屉避让的投影基准(每帧摆一次,不重画就不必再摆) */
const projectorRef = useRef<Frame | null>(null);
/** 统计请求的防抖计时器。筛选与视口共用同一套调度(见 scheduleRefresh) */
const statsTimerRef = useRef<number | null>(null);
const [mapReady, setMapReady] = useState(false); const [mapReady, setMapReady] = useState(false);
/** /**
...@@ -253,7 +306,7 @@ export function MapStage() { ...@@ -253,7 +306,7 @@ export function MapStage() {
const [spotCellM, setSpotCellM] = useState(0); const [spotCellM, setSpotCellM] = useState(0);
const status = useHeatmapStore((s) => s.status); const status = useHeatmapStore((s) => s.status);
const progress = useHeatmapStore((s) => s.progress); // 进度读数不在这里订:导入时它每秒变好多次,全部交给下面的 StageProgress 自己订
const meta = useHeatmapStore((s) => s.meta); const meta = useHeatmapStore((s) => s.meta);
const filter = useHeatmapStore((s) => s.filter); const filter = useHeatmapStore((s) => s.filter);
const basemap = useHeatmapStore((s) => s.basemap); const basemap = useHeatmapStore((s) => s.basemap);
...@@ -271,7 +324,6 @@ export function MapStage() { ...@@ -271,7 +324,6 @@ export function MapStage() {
*/ */
const rosterOpen = useHeatmapStore((s) => s.roster !== null); const rosterOpen = useHeatmapStore((s) => s.roster !== null);
const amapError = useHeatmapStore((s) => s.amapError); const amapError = useHeatmapStore((s) => s.amapError);
const perf = useHeatmapStore((s) => s.perf);
const analysisOn = useHeatmapStore((s) => s.analysisOn); const analysisOn = useHeatmapStore((s) => s.analysisOn);
const analysisParams = useHeatmapStore((s) => s.analysisParams); const analysisParams = useHeatmapStore((s) => s.analysisParams);
const analysis = useHeatmapStore((s) => s.analysis); const analysis = useHeatmapStore((s) => s.analysis);
...@@ -306,11 +358,8 @@ export function MapStage() { ...@@ -306,11 +358,8 @@ export function MapStage() {
const setAmapError = useHeatmapStore((s) => s.setAmapError); const setAmapError = useHeatmapStore((s) => s.setAmapError);
const select = useHeatmapStore((s) => s.select); const select = useHeatmapStore((s) => s.select);
const patchPerf = useHeatmapStore((s) => s.patchPerf); // 读数块那两块入口(命中 / 点位)不在这里订阅了:它们连同读数一起搬进
// 工具条那两块读数的入口:与风险概览的同名读数走同一对 action, // ToolbarReadouts(见文件末尾),为的是聚合回来时只重画那一小条
// 从地图上看还是从面板上看,点开的必须是同一份清单
const openRoster = useHeatmapStore((s) => s.openRoster);
const openPointRoster = useHeatmapStore((s) => s.openPointRoster);
const closeSpotlight = useHeatmapStore((s) => s.closeSpotlight); const closeSpotlight = useHeatmapStore((s) => s.closeSpotlight);
/* 事件回调里要读最新筛选条件,但不能因为它们变化而重绑地图事件 —— 用 ref 过渡 */ /* 事件回调里要读最新筛选条件,但不能因为它们变化而重绑地图事件 —— 用 ref 过渡 */
...@@ -342,8 +391,15 @@ export function MapStage() { ...@@ -342,8 +391,15 @@ export function MapStage() {
* 出现「数字淡出、热力还亮着」的半截状态。 * 出现「数字淡出、热力还亮着」的半截状态。
* *
* 分析还没回来(或已关闭)时不过滤 —— 首屏一片空白比晚 200ms 出黑点更糟。 * 分析还没回来(或已关闭)时不过滤 —— 首屏一片空白比晚 200ms 出黑点更糟。
*
* @param extra 同一次取数带出的其他读数(耗时、命中数…)。热力与聚合是一次连锁,
* 两边的数各自 patchPerf 会把 store 通知发两遍,界面因此多画一整轮。
*
* ⚠️ 输入没变就不重喂:重喂是「整批桶重投影 + 重取分位 + 重传一份 WebGL 数据」,
* 一次几十毫秒起步,而一次点选(开抽屉)与一次聚合回来都会要它。判定用的是这一层
* 全部的输入 —— 那批桶、那张过滤表、抽屉在不在、以及视口本身(分位只按屏幕内那些桶取)。
*/ */
const applyHeat = useCallback(() => { const applyHeat = useCallback((extra?: Partial<PerfSnapshot>) => {
const heat = heatRef.current; const heat = heatRef.current;
const cluster = clusterRef.current; const cluster = clusterRef.current;
const map = mapRef.current; const map = mapRef.current;
...@@ -353,20 +409,54 @@ export function MapStage() { ...@@ -353,20 +409,54 @@ export function MapStage() {
if (!agg || agg.bucketCount === 0) { if (!agg || agg.bucketCount === 0) {
heat.clear(); heat.clear();
cluster?.setReference(0); cluster?.setReference(0);
st.patchPerf({ heatPoints: 0, backgroundBuckets: 0, heatGridPx: GRID.gridPx }); heatKeyRef.current = null;
heatReadoutRef.current = { heatPoints: 0, backgroundBuckets: 0, heatGridPx: GRID.gridPx };
st.patchPerf({ ...heatReadoutRef.current, ...extra });
return; return;
} }
const sig = st.analysisOn ? toSignificanceMask(st.analysis) : null; const sig = st.analysisOn ? toSignificanceMask(st.analysis) : null;
// 掩码换了但桶没换时,聚合层的过滤表还是旧的 —— 所以 setSignificance 必须在这行之前 // 掩码换了但桶没换时,聚合层的过滤表还是旧的 —— 所以 setSignificance 必须在这行之前
const raw = sig ? cluster?.keepMask : null; const raw = sig ? cluster?.keepMask : null;
const keep = raw && raw.length === agg.bucketCount ? raw : null; const keep = raw && raw.length === agg.bucketCount ? raw : null;
const size = map.getSize();
const center = map.getCenter();
const zoom = map.getZoom();
// 「右缘有没有抽屉」也在输入里:它决定压住的那半边画不画(见 excludeUnderDrawer)
const key: HeatKey = [
agg,
keep,
st.drawerOpen || st.roster !== null,
zoom,
center.getLng(),
center.getLat(),
size.width,
size.height,
];
if (sameHeatKey(heatKeyRef.current, key)) {
// 输入一模一样,重算出来的必然是同一份深浅,这一次只欠那几个读数
st.patchPerf({ ...heatReadoutRef.current, ...extra });
return;
}
heatKeyRef.current = key;
// 「背景淡化 N 处」按降噪那张表数,不按「点位数 − 实绘点数」减(见 countBackgroundBuckets) // 「背景淡化 N 处」按降噪那张表数,不按「点位数 − 实绘点数」减(见 countBackgroundBuckets)
const backgroundBuckets = countBackgroundBuckets(keep); const backgroundBuckets = countBackgroundBuckets(keep);
heat.setDataset(agg.lng, agg.lat, agg.count, excludeUnderDrawer(keep, st, map, agg)); const frame = projector(
projectorRef.current ?? (projectorRef.current = new Frame()),
map,
zoom,
center,
size,
);
heat.setDataset(agg.lng, agg.lat, agg.count, excludeUnderDrawer(keep, st, frame, agg));
// 数字浓淡的分母直接跟热力借,两层共用一个数:底色亮到哪、字就浓到哪。 // 数字浓淡的分母直接跟热力借,两层共用一个数:底色亮到哪、字就浓到哪。
// 各算各的话,聚合层会多算一圈屏幕外的缓冲桶,同一屏得出两个「最高档」。 // 各算各的话,聚合层会多算一圈屏幕外的缓冲桶,同一屏得出两个「最高档」。
cluster?.setReference(heat.maxWeight); cluster?.setReference(heat.maxWeight);
st.patchPerf({ heatPoints: heat.count, backgroundBuckets, heatGridPx: agg.gridPx }); heatReadoutRef.current = {
heatPoints: heat.count,
backgroundBuckets,
heatGridPx: agg.gridPx,
};
st.patchPerf({ ...heatReadoutRef.current, ...extra });
}, []); }, []);
/* ---------------------- 聚合:一次结果,两层共用 ---------------------- */ /* ---------------------- 聚合:一次结果,两层共用 ---------------------- */
...@@ -424,21 +514,33 @@ export function MapStage() { ...@@ -424,21 +514,33 @@ export function MapStage() {
// 点位清单的来源:把刚画到屏幕上的这批方格留着(见 viewSnapshot.ts) // 点位清单的来源:把刚画到屏幕上的这批方格留着(见 viewSnapshot.ts)
rememberViewportAggregate(res, zoom); rememberViewportAggregate(res, zoom);
// 存的是没外扩过的真实可见范围:聚合要外扩吸收拖动,而「点位数点进去看哪些方格」 // 存的是没外扩过的真实可见范围:聚合要外扩吸收拖动,而「点位数点进去看哪些方格」
// 说的就是屏幕上看得见的那一块,多给缓冲会列出画在屏幕外的格子 // 说的就是屏幕上看得见的那一块,多给缓冲会列出画在屏幕外的格子。
useHeatmapStore.getState().setViewportBBox({ // 视野没真的挪动就不换那份快照:每次聚合都塞一个新对象,等于让全界面读它的地方
// 都重算一遍,而拖动之后十有八九落在同一块地上。
const box = {
minLng: sw.getLng(), minLng: sw.getLng(),
minLat: sw.getLat(), minLat: sw.getLat(),
maxLng: ne.getLng(), maxLng: ne.getLng(),
maxLat: ne.getLat(), maxLat: ne.getLat(),
}); };
const st = useHeatmapStore.getState();
const prev = st.viewportBBox;
if (
!prev ||
prev.minLng !== box.minLng ||
prev.minLat !== box.minLat ||
prev.maxLng !== box.maxLng ||
prev.maxLat !== box.maxLat
) {
st.setViewportBBox(box);
}
// 同一份桶喂给两层:聚合圆圈拿中心 + 数字,热力拿中心 + 权重 // 同一份桶喂给两层:聚合圆圈拿中心 + 数字,热力拿中心 + 权重
cluster.setData(res.lng, res.lat, res.count, res.gx, res.gy, res.dLng, res.dLat); cluster.setData(res.lng, res.lat, res.count, res.gx, res.gy, res.dLng, res.dLat);
// 不传 res.maxCount:热力层的归一化上限在 HeatLayer 内部取 P82, // 不传 res.maxCount:热力层的归一化上限在 HeatLayer 内部取 P82,
// 用全局最大值会把绝大多数桶压到渐变最左端,热力几乎看不见。 // 用全局最大值会把绝大多数桶压到渐变最左端,热力几乎看不见。
applyHeat(); // 这一轮的耗时 / 命中 / 方格数随热力那一次一起写进 store:一次取数只通知界面一遍
applyHeat({
patchPerf({
aggregateMs: res.ms, aggregateMs: res.ms,
matched: res.matched, matched: res.matched,
clusterBuckets: res.bucketCount, clusterBuckets: res.bucketCount,
...@@ -447,7 +549,7 @@ export function MapStage() { ...@@ -447,7 +549,7 @@ export function MapStage() {
} catch (err) { } catch (err) {
console.error('[aggregate] 聚合失败', err); console.error('[aggregate] 聚合失败', err);
} }
}, [applyHeat, patchPerf]); }, [applyHeat]);
/* ---------------------- 统计(与视口无关,只跟筛选有关) ---------------------- */ /* ---------------------- 统计(与视口无关,只跟筛选有关) ---------------------- */
...@@ -618,14 +720,83 @@ export function MapStage() { ...@@ -618,14 +720,83 @@ export function MapStage() {
}; };
}, [mapReady, runAggregate]); }, [mapReady, runAggregate]);
/**
* 拖动 / 缩放期间给整页挂一个状态类,把毛玻璃的模糊压下来。
*
* backdrop-filter 的账是「每帧把它身后那块区域重新采样再卷积一遍」:底下一整块全屏 WebGL 地图,
* 地图一动,顶栏(整屏宽)、右栏面板、左侧清单、图例、读数胶囊、抽屉全都要各自重模糊一次。
* 这是拖地图卡顿里最大的一笔单项开销,而且它跟数据量无关 —— 空图也卡。
* 只在按住地图这段时间生效,松手后恢复原本的磨砂,静止时外观与原来一致;
* 那几层底色同步压实(见 design.css 的 html.hm-map-busy),免得「少模糊」被读成「玻璃变透明」。
*
* 恢复刻意推迟一拍:松手紧接着就是重新聚合与重喂热力,同一帧里再把重模糊挂回去,
* 等于把卡顿原封不动挪到松手那一下。三个收尾事件都清一次,漏掉哪个都不会把状态卡住。
*/
useEffect(() => {
if (!mapReady) return;
const map = mapRef.current;
if (!map) return;
const root = document.documentElement;
let timer = 0;
const busy = () => {
if (timer) {
window.clearTimeout(timer);
timer = 0;
}
root.classList.add('hm-map-busy');
};
const settle = () => {
if (timer) window.clearTimeout(timer);
timer = window.setTimeout(() => {
timer = 0;
root.classList.remove('hm-map-busy');
}, GLASS_RESTORE_MS);
};
map.on('dragstart', busy);
map.on('zoomstart', busy);
map.on('dragend', settle);
map.on('zoomend', settle);
map.on('moveend', settle);
return () => {
map.off('dragstart', busy);
map.off('zoomstart', busy);
map.off('dragend', settle);
map.off('zoomend', settle);
map.off('moveend', settle);
if (timer) window.clearTimeout(timer);
root.classList.remove('hm-map-busy');
};
}, [mapReady]);
/* ---------------------- 筛选变化 → 三个入口一起刷新 ---------------------- */ /* ---------------------- 筛选变化 → 三个入口一起刷新 ---------------------- */
/**
* 筛选一变就重取聚合、重算统计,但都不立刻动手,而是排进防抖。
*
* 这两件事是全表扫:统计要把命中的几十万点重归一遍维度,聚合要按当前视野重切方格。
* 逐条改动马上去扫,就会出现「多选区里连点两个区、界面先卡住不动」那种卡顿 ——
* 而连点之间那些中间结果本来就不该给人看。
*/
useEffect(() => { useEffect(() => {
if (!mapReady || status !== 'ready') return; if (!mapReady || status !== 'ready') return;
// 筛选变了,之前的选中桶可能已经不在结果里,先关掉弹窗避免指向错误数据 // 筛选变了,之前的选中桶可能已经不在结果里,先关掉弹窗避免指向错误数据
select(null); select(null);
if (timerRef.current) window.clearTimeout(timerRef.current);
timerRef.current = window.setTimeout(() => {
timerRef.current = null;
void runAggregate(); void runAggregate();
}, REFRESH_DEBOUNCE_MS);
if (statsTimerRef.current) window.clearTimeout(statsTimerRef.current);
statsTimerRef.current = window.setTimeout(() => {
statsTimerRef.current = null;
void runStats(); void runStats();
}, STATS_DEBOUNCE_MS);
return () => {
if (timerRef.current) window.clearTimeout(timerRef.current);
timerRef.current = null;
if (statsTimerRef.current) window.clearTimeout(statsTimerRef.current);
statsTimerRef.current = null;
};
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [mapReady, status, filter]); }, [mapReady, status, filter]);
...@@ -974,6 +1145,40 @@ export function MapStage() { ...@@ -974,6 +1145,40 @@ export function MapStage() {
mapRef.current.setZoomAndCenter(SHENZHEN_VIEW.zoom, [m.center.lng, m.center.lat]); mapRef.current.setZoomAndCenter(SHENZHEN_VIEW.zoom, [m.center.lng, m.center.lat]);
}, []); }, []);
/**
* 屏幕尺寸与两侧浮层的避让宽度。
*
* 桶卡是绝对定位在地图上的浮层,它要知道「看得见的那一段」从哪儿到哪儿,否则会弹到右侧
* 面板或左侧清单底下。这份账原先每次渲染现读一遍,而 `getComputedStyle` 与 `clientWidth`
* 都是「要答案就得先把布局算完」的读数 —— 渲染恰好发生在地图刚动完、图层刚喂完数据那一刻,
* 等于在最忙的一帧里再插一次强制重排。
* 现在只在真的变了的时候算:窗口尺寸(rAF 合帧,拖动窗口边缘不会连读几十次)与两侧浮层开合。
* 顺带让对象引用稳定下来,桶卡不必每轮都跟着重摆一次。
*/
const [viewportTick, setViewportTick] = useState(0);
useEffect(() => {
let raf = 0;
const onResize = () => {
if (raf) return;
raf = requestAnimationFrame(() => {
raf = 0;
setViewportTick((t) => t + 1);
});
};
window.addEventListener('resize', onResize);
return () => {
window.removeEventListener('resize', onResize);
if (raf) cancelAnimationFrame(raf);
};
}, []);
const stageSize = useMemo(
() => mapSize(wrapRef.current, railOpen, dockOpen),
// 容器在地图初始化好之前没有尺寸,所以 mapReady 也是这一份读数的依赖
// eslint-disable-next-line react-hooks/exhaustive-deps
[railOpen, dockOpen, mapReady, viewportTick],
);
const legendHint = useMemo(() => { const legendHint = useMemo(() => {
if (!mapReady) return null; if (!mapReady) return null;
// 降噪开着时数字有两种来源,必须当场说清哪个作数:网格数字随缩放变,盘心数字和清单一致。 // 降噪开着时数字有两种来源,必须当场说清哪个作数:网格数字随缩放变,盘心数字和清单一致。
...@@ -1029,38 +1234,7 @@ export function MapStage() { ...@@ -1029,38 +1234,7 @@ export function MapStage() {
</button> </button>
</div> </div>
) : ( ) : (
<div className="hm-map__stat-chip"> <ToolbarReadouts />
{/* 三个标签各两字(命中 / 点位 / 耗时)是刻意压着的:设计稿里工具条的实测宽度
被写进 design.css 的让位阈值(760、1140 那两段),加长要先回去核那些阈值。
「点位」不是「打点」——后者是口语,前者是这份图里一直在用的说法。 */}
<span className="dot" />
{/* 命中 / 点位 两块数字是可点的:它们报的就是风险概览顶上那两块的同一份账,
所以点下去也开同一张抽屉。耗时不可点 —— 那是这套界面的事,不是数据 */}
<button
type="button"
className="hm-map__stat-link"
onClick={() => openRoster({ source: '命中案件 · 当前筛选' })}
title="点开看这些案件的清单,可在清单里再按区、街道、时间、关键词收窄"
>
命中 <b>{fmtCompact(perf.matched)}</b> 起
</button>
<span style={{ color: 'var(--hm-divider)' }}>|</span>
<button
type="button"
className="hm-map__stat-link"
disabled={perf.clusterBuckets === 0}
onClick={() => openPointRoster('热力点位 · 屏幕上的方格')}
title={
perf.clusterBuckets > 0
? '点开看屏幕上这批方格,一行一个格子,报的是格子里的案件数'
: '地图还没聚合出方格,没有可列的点位'
}
>
点位 <b>{perf.clusterBuckets}</b> 处
</button>
<span style={{ color: 'var(--hm-divider)' }}>|</span>
耗时 <b className="hm-perf">{fmtMs(perf.aggregateMs)}</b>
</div>
)} )}
{/* 文案只写「回到全市」,但做的事有两件,所以把第二件写在 tooltip 里: {/* 文案只写「回到全市」,但做的事有两件,所以把第二件写在 tooltip 里:
不写清楚,用户会以为自己刚点的筛选还留着,或者反过来以为该保留的筛选被清了。 */} 不写清楚,用户会以为自己刚点的筛选还留着,或者反过来以为该保留的筛选被清了。 */}
...@@ -1072,32 +1246,11 @@ export function MapStage() { ...@@ -1072,32 +1246,11 @@ export function MapStage() {
</div> </div>
{mapReady && selection && ( {mapReady && selection && (
<BucketCard <BucketCard selection={selection} containerSize={stageSize} onClose={() => select(null)} />
selection={selection}
containerSize={mapSize(wrapRef.current, railOpen, dockOpen)}
onClose={() => select(null)}
/>
)} )}
{(status === 'loading' || (status === 'ready' && !mapReady)) && ( {(status === 'loading' || (status === 'ready' && !mapReady)) && (
<div className="hm-map__overlay"> <StageProgress showFile={status === 'loading'} />
<div className="hm-loading">
<div className="hm-loading__ring" />
<div>
{status === 'loading'
? `正在加载数据${progress ? ` · ${progress.file}` : ''}`
: '正在初始化地图'}
</div>
{progress && (
<div className="hm-progress">
<div
className="hm-progress__bar"
style={{ width: `${Math.round(progress.ratio * 100)}%` }}
/>
</div>
)}
</div>
</div>
)} )}
{amapError && <MapKeyGuide error={amapError} />} {amapError && <MapKeyGuide error={amapError} />}
...@@ -1119,7 +1272,81 @@ export function MapStage() { ...@@ -1119,7 +1272,81 @@ export function MapStage() {
{/* 右下那颗讲的是热力权重与背景淡化:聚焦期间热力层本来就收着, {/* 右下那颗讲的是热力权重与背景淡化:聚焦期间热力层本来就收着,
留着会出现「底色不见了,读数还在报底色由多少个点画出来」 */} 留着会出现「底色不见了,读数还在报底色由多少个点画出来」 */}
{mapReady && !spotlight && ( {mapReady && !spotlight && <HeatReadouts analysisOn={analysisOn} />}
</div>
);
}
/**
* 工具条上那三个读数(命中 / 点位 / 耗时)。
*
* 单独成一个组件只为一件事:这三个数每拖一次地图就换一次。读数原先订在 MapStage 里,
* 于是每次聚合回来都要把整棵地图子树重画一遍 —— 图例、说明条、聚焦层、桶卡、四张抽屉的
* 挂载点全跟着走一遍 render,「拖着拖着就沉」正是这么攒出来的。
* 现在这一小条自己订阅自己重画,MapStage 对 perf 一无所知。
*
* 订阅按字段拆开,不整份拿 perf:perf 每次 patch 都换一个新对象,整份订阅等于
* 「任何一格读数变了就全变」,而这一块根本用不到 membersMs、analysisMs 那些。
*
* 三个标签各两字(命中 / 点位 / 耗时)是刻意压着的:设计稿里工具条的实测宽度
* 被写进 design.css 的让位阈值(760、1140 那两段),加长要先回去核那些阈值。
* 「点位」不是「打点」—— 后者是口语,前者是这份图里一直在用的说法。
*/
function ToolbarReadouts() {
const matched = useHeatmapStore((s) => s.perf.matched);
const clusterBuckets = useHeatmapStore((s) => s.perf.clusterBuckets);
const aggregateMs = useHeatmapStore((s) => s.perf.aggregateMs);
// 与风险概览的同名读数走同一对 action:从地图上看还是从面板上看,点开的必须是同一份清单
const openRoster = useHeatmapStore((s) => s.openRoster);
const openPointRoster = useHeatmapStore((s) => s.openPointRoster);
return (
<div className="hm-map__stat-chip">
<span className="dot" />
{/* 命中 / 点位 两块数字是可点的:它们报的就是风险概览顶上那两块的同一份账,
所以点下去也开同一张抽屉。耗时不可点 —— 那是这套界面的事,不是数据 */}
<button
type="button"
className="hm-map__stat-link"
onClick={() => openRoster({ source: '命中案件 · 当前筛选' })}
title="点开看这些案件的清单,可在清单里再按区、街道、时间、关键词收窄"
>
命中 <b>{fmtCompact(matched)}</b> 起
</button>
<span style={{ color: 'var(--hm-divider)' }}>|</span>
<button
type="button"
className="hm-map__stat-link"
disabled={clusterBuckets === 0}
onClick={() => openPointRoster('热力点位 · 屏幕上的方格')}
title={
clusterBuckets > 0
? '点开看屏幕上这批方格,一行一个格子,报的是格子里的案件数'
: '地图还没聚合出方格,没有可列的点位'
}
>
点位 <b>{clusterBuckets}</b> 处
</button>
<span style={{ color: 'var(--hm-divider)' }}>|</span>
耗时 <b className="hm-perf">{fmtMs(aggregateMs)}</b>
</div>
);
}
/**
* 右下那颗:底色由多少个点画出来、其中多少处被降噪淡掉、方格多大。
*
* 与工具条那条同理,它跟着每次重喂热力换数,所以也不留在 MapStage 里。
*
* @param analysisOn 降噪开关。它决定 tooltip 的说法和「背景淡化」那一截出不出现,
* 而它是用户点的开关、不是聚合回来的副产品,由父级传进来正好。
*/
function HeatReadouts({ analysisOn }: { analysisOn: boolean }) {
const heatPoints = useHeatmapStore((s) => s.perf.heatPoints);
const backgroundBuckets = useHeatmapStore((s) => s.perf.backgroundBuckets);
const heatGridPx = useHeatmapStore((s) => s.perf.heatGridPx);
return (
<Tooltip <Tooltip
title={ title={
analysisOn analysisOn
...@@ -1129,21 +1356,50 @@ export function MapStage() { ...@@ -1129,21 +1356,50 @@ export function MapStage() {
> >
<div className="hm-map__stat-chip hm-map__foot"> <div className="hm-map__stat-chip hm-map__foot">
<InfoCircleOutlined style={{ color: 'var(--hm-accent-cyan)' }} /> <InfoCircleOutlined style={{ color: 'var(--hm-accent-cyan)' }} />
热力点位 <b>{fmtCompact(perf.heatPoints)}</b> 热力点位 <b>{fmtCompact(heatPoints)}</b>
{analysisOn && perf.backgroundBuckets > 0 && ( {analysisOn && backgroundBuckets > 0 && (
<> <>
<span style={{ color: 'var(--hm-divider)' }}>|</span> <span style={{ color: 'var(--hm-divider)' }}>|</span>
{/* 用降噪那张表数出来的背景格子,不拿「点位数 − 热力点位」减: {/* 用降噪那张表数出来的背景格子,不拿「点位数 − 热力点位」减:
两个数之间还隔着「右缘抽屉压住的那半边不画」这一步(见 excludeUnderDrawer), 两个数之间还隔着「右缘抽屉压住的那半边不画」这一步(见 excludeUnderDrawer),
减出来的数会把被抽屉挡住也说成被降噪淡化 */} 减出来的数会把被抽屉挡住也说成被降噪淡化 */}
背景淡化 <b>{fmtCompact(perf.backgroundBuckets)}</b> 处 背景淡化 <b>{fmtCompact(backgroundBuckets)}</b> 处
</> </>
)} )}
<span style={{ color: 'var(--hm-divider)' }}>|</span>方格 <b>{perf.heatGridPx}px</b> <span style={{ color: 'var(--hm-divider)' }}>|</span>方格 <b>{heatGridPx}px</b>
</div> </div>
</Tooltip> </Tooltip>
);
}
/**
* 载入进度那一层。
*
* 单独成组件是因为 progress 换得极勤:导入几十万条时解析 Worker 每过一小段就报一次数,
* 原先这个读数订在 MapStage 上,于是每次进度更新都把整棵地图子树重画一遍 ——
* 进度条还在走,用户已经在拖地图了,两边叠在一起就是「导入的时候整机发沉」。
* 现在只有这一小条跟着进度重画,MapStage 不认识 progress。
*/
function StageProgress({ showFile }: { showFile: boolean }) {
const progress = useHeatmapStore((s) => s.progress);
return (
<div className="hm-map__overlay">
<div className="hm-loading">
<div className="hm-loading__ring" />
<div>
{showFile ? `正在加载数据${progress ? ` · ${progress.file}` : ''}` : '正在初始化地图'}
</div>
{progress && (
<div className="hm-progress">
<div
className="hm-progress__bar"
style={{ width: `${Math.round(progress.ratio * 100)}%` }}
/>
</div>
)} )}
</div> </div>
</div>
); );
} }
...@@ -1175,7 +1431,11 @@ function coverSides(opts: { ...@@ -1175,7 +1431,11 @@ function coverSides(opts: {
} }
/** /**
* 读数带缓存:每次渲染都读 layout 会触发强制重排。 * 读一次布局:容器宽度扣掉两侧浮层,得到「桶卡可以待的那一段」。
*
* ⚠️ 这里有 getComputedStyle 与 clientWidth,两个都会把布局算完才给数,
* 所以只在 MapStage 的 stageSize 里调用(窗口尺寸与浮层开合真的变了才算一次),
* 不要放回 render —— 那等于每次渲染都在最忙的一帧里强制重排。
* *
* railOpen 时从宽度里扣掉右侧操作区(面板 + 把手 + 两边留白), * railOpen 时从宽度里扣掉右侧操作区(面板 + 把手 + 两边留白),
* dockOpen 时再扣掉左侧的清单通栏 —— 桶卡是绝对定位在地图上的, * dockOpen 时再扣掉左侧的清单通栏 —— 桶卡是绝对定位在地图上的,
......
...@@ -54,10 +54,12 @@ const RAMP_TITLE: Record<SpotlightView['kind'], string> = { ...@@ -54,10 +54,12 @@ const RAMP_TITLE: Record<SpotlightView['kind'], string> = {
const RAMP_NOTE: Record<SpotlightView['kind'], string> = { const RAMP_NOTE: Record<SpotlightView['kind'], string> = {
// 整片涂起数是典型误读:面积最大的那个区一定最深,而那只代表案件总数多。 // 整片涂起数是典型误读:面积最大的那个区一定最深,而那只代表案件总数多。
// 所以这里把两件事分开说,牌子仍然念总数(榜上就是这么排的) // 所以这里把两件事分开说,牌子仍然念总数(榜上就是这么排的)
districts: '深浅在这几块区之间比较,最深的是每平方公里案件最多的一块;牌子上的数字是该区案件总数。', districts:
'深浅在这几块区之间比较,最深的是每平方公里案件最多的一块;牌子上的数字是该区案件总数。',
streets: '深浅按每一条街道自己最挤的那一格比较,跨街道比多少请看牌子上的起数。', streets: '深浅按每一条街道自己最挤的那一格比较,跨街道比多少请看牌子上的起数。',
roads: '深浅按每一条道路自己最挤的那一段比较,跨道路比多少请看牌子上的起数。', roads: '深浅按每一条道路自己最挤的那一段比较,跨道路比多少请看牌子上的起数。',
places: '牌子上一行是案件数,第二行是这段时间里有案的天数。方格颜色只用来分清是哪几处,不表示多少。', places:
'牌子上一行是案件数,第二行是这段时间里有案的天数。方格颜色只用来分清是哪几处,不表示多少。',
}; };
/** /**
......
...@@ -1296,7 +1296,8 @@ function handleSpotlight(reqId: number, filter: Filter, dim: SpotlightDim, idxs: ...@@ -1296,7 +1296,8 @@ function handleSpotlight(reqId: number, filter: Filter, dim: SpotlightDim, idxs:
for (let i = 0; i < s.n; i += 1) { for (let i = 0; i < s.n; i += 1) {
if (mask[i] !== 1) continue; if (mask[i] !== 1) continue;
const v = dim === 'streets' ? streetCol[i] : detail !== null ? roadIdx!.ofDetail[detail[i]] : -1; const v =
dim === 'streets' ? streetCol[i] : detail !== null ? roadIdx!.ofDetail[detail[i]] : -1;
const g = slotOf.get(v); const g = slotOf.get(v);
if (g === undefined) continue; if (g === undefined) continue;
const x = lng[i]; const x = lng[i];
......
...@@ -357,7 +357,20 @@ const lastDayKey = dayKey(dataMaxTs); ...@@ -357,7 +357,20 @@ const lastDayKey = dayKey(dataMaxTs);
/** 以数据里最后那一天为末端往回推:近期窗口必须锚在这段日子上,而不是锚在全量数据上 */ /** 以数据里最后那一天为末端往回推:近期窗口必须锚在这段日子上,而不是锚在全量数据上 */
const shortFrom = (days: number) => const shortFrom = (days: number) =>
Math.floor(Date.parse(`${lastDayKey}T00:00:00Z`) / 1000) - TZ - days * DAY; Math.floor(Date.parse(`${lastDayKey}T00:00:00Z`) / 1000) - TZ - days * DAY;
const SHORT: Filter = { from: shortFrom(44), to: dataMaxTs, districts: [], keyword: '' }; /**
* 「近期」这一档的长度跟着数据跨度走,不写死。
*
* 这一档存在的意义是「窗口真的比全量短」:只有短出去,命中数才会变少,
* 后面那一大批「按筛选重算」的断言才不是在拿全量对全量空跑。
* 原先写死 44 天,是因为那时内置样本跨半年;换成只有一段月份的表之后,
* 44 天窗口把每一个点都收进来,short.matched < full.matched 直接不成立 ——
* 看着像数据错了,其实是对账的尺子还停在旧样本上。
*
* 取跨度的一半并夹在 [10, 44]:跨度大时仍是原来的 44 天,跨度小时自动缩成一段真窗口;
* 下限 10 天是因为「近 N 天」那个 N 会按窗口长度算(上限 30),再短就把这条分支挤没了。
*/
const RECENT_DAYS = Math.min(44, Math.max(10, Math.round(spanDays(timeRange.min, timeRange.max) / 2)));
const SHORT: Filter = { from: shortFrom(RECENT_DAYS), to: dataMaxTs, districts: [], keyword: '' };
/** 比 30 天还短的一窗:专门盯「近 N 天」的 N —— 窗口不足 30 天时不许还写着 30 */ /** 比 30 天还短的一窗:专门盯「近 N 天」的 N —— 窗口不足 30 天时不许还写着 30 */
const WEEK: Filter = { from: shortFrom(6), to: dataMaxTs, districts: [], keyword: '' }; const WEEK: Filter = { from: shortFrom(6), to: dataMaxTs, districts: [], keyword: '' };
const nanshan = dict.districts.indexOf('南山区'); const nanshan = dict.districts.indexOf('南山区');
...@@ -366,7 +379,7 @@ const WITH_KW: Filter = { ...FULL, keyword: '南山' }; ...@@ -366,7 +379,7 @@ const WITH_KW: Filter = { ...FULL, keyword: '南山' };
const CASES: Array<{ name: string; f: Filter }> = [ const CASES: Array<{ name: string; f: Filter }> = [
{ name: '全量', f: FULL }, { name: '全量', f: FULL },
{ name: '近 45 天', f: SHORT }, { name: `近 ${RECENT_DAYS} 天`, f: SHORT },
{ name: '近 7 天', f: WEEK }, { name: '近 7 天', f: WEEK },
{ name: '南山区 + 关键词医院', f: WITH_FILTER }, { name: '南山区 + 关键词医院', f: WITH_FILTER },
{ name: '关键词命中区名', f: WITH_KW }, { name: '关键词命中区名', f: WITH_KW },
......
...@@ -14,7 +14,12 @@ import { UNRESOLVED_LABEL } from '../aggregate/types'; ...@@ -14,7 +14,12 @@ import { UNRESOLVED_LABEL } from '../aggregate/types';
/** 复刻 ingestCore 里的调用姿势:先按 '-' 切、去空白、丢空段 */ /** 复刻 ingestCore 里的调用姿势:先按 '-' 切、去空白、丢空段 */
function parse(address: string) { function parse(address: string) {
return splitAddress(address.split('-').map((s) => s.trim()).filter(Boolean)); return splitAddress(
address
.split('-')
.map((s) => s.trim())
.filter(Boolean),
);
} }
describe('splitAddress', () => { describe('splitAddress', () => {
......
...@@ -46,13 +46,50 @@ function firstDiffs(mine: ArrayLike<number>, theirs: number[], limit = 5): strin ...@@ -46,13 +46,50 @@ function firstDiffs(mine: ArrayLike<number>, theirs: number[], limit = 5): strin
return out; return out;
} }
/**
* 源文本按行切列,认 CSV 的双引号。
*
* 这里必须自己实现一遍(而不是复用任何一条流水线的解析器):这一条断言讲的是
* 「列存下标与源文本行号一一对应」,复用被测方的切法就等于拿结论当前提。
* 真实表格里地址自带半角逗号(「…龙平西路南侧,龙福路以北」),裸 split(',') 会把那一行
* 切成 6 段、时间列读到地址尾巴,报错信息看着像数据坏了 —— 其实是对账自己不会切。
*/
function splitRow(line: string): string[] {
if (!line.includes('"')) return line.split(',');
const out: string[] = [];
let cur = '';
let inQuote = false;
for (let i = 0; i < line.length; i += 1) {
const ch = line[i];
if (inQuote) {
if (ch === '"') {
if (line[i + 1] === '"') {
cur += '"';
i += 1;
} else inQuote = false;
} else cur += ch;
} else if (ch === '"') inQuote = true;
else if (ch === ',') {
out.push(cur);
cur = '';
} else cur += ch;
}
out.push(cur);
return out;
}
describe('内置数据与浏览器导入同构', () => { describe('内置数据与浏览器导入同构', () => {
const bytes = readBytes(CSV); const bytes = readBytes(CSV);
const products = ingestBytes('incidents.sample.csv', bytes.buffer as ArrayBuffer); const products = ingestBytes('incidents.sample.csv', bytes.buffer as ArrayBuffer);
const shippedMeta = json<MetaFile>(META); const shippedMeta = json<MetaFile>(META);
const shippedIncidents = json<{ n: number; lng: number[]; lat: number[]; ts: number[]; d: number[]; s: number[] }>( const shippedIncidents = json<{
INCIDENTS, n: number;
); lng: number[];
lat: number[];
ts: number[];
d: number[];
s: number[];
}>(INCIDENTS);
const shippedDetail = json<{ caseNo: string[]; a: number[] }>(DETAIL); const shippedDetail = json<{ caseNo: string[]; a: number[] }>(DETAIL);
const lng = new Int32Array(products.columns.lng); const lng = new Int32Array(products.columns.lng);
...@@ -114,14 +151,17 @@ describe('内置数据与浏览器导入同构', () => { ...@@ -114,14 +151,17 @@ describe('内置数据与浏览器导入同构', () => {
* 而总量数字看起来完全正常 —— 这正是最难发现的一类错。 * 而总量数字看起来完全正常 —— 这正是最难发现的一类错。
*/ */
it('报案时间按北京时间落库,逐条对回源文本', () => { it('报案时间按北京时间落库,逐条对回源文本', () => {
const lines = Buffer.from(bytes).toString('utf8').split(/\r?\n/).filter((l) => l.trim()); const lines = Buffer.from(bytes)
const header = lines[0].split(','); .toString('utf8')
.split(/\r?\n/)
.filter((l) => l.trim());
const header = splitRow(lines[0]);
const timeCol = header.findIndex((h) => h.includes('报案时间')); const timeCol = header.findIndex((h) => h.includes('报案时间'));
expect(timeCol).toBeGreaterThan(-1); expect(timeCol).toBeGreaterThan(-1);
let checked = 0; let checked = 0;
for (let r = 1; r < lines.length && checked < 3000; r += 1) { for (let r = 1; r < lines.length && checked < 3000; r += 1) {
const cells = lines[r].split(','); const cells = splitRow(lines[r]);
const text = (cells[timeCol] ?? '').trim(); const text = (cells[timeCol] ?? '').trim();
if (!text) continue; if (!text) continue;
// 行号必须与列存下标一一对应:中间只要有一行被丢掉或被拆开,后面的比对就全错位 // 行号必须与列存下标一一对应:中间只要有一行被丢掉或被拆开,后面的比对就全错位
......
...@@ -177,8 +177,7 @@ export function splitAddress(parts: string[]): { district: string; rest: string ...@@ -177,8 +177,7 @@ export function splitAddress(parts: string[]): { district: string; rest: string
const known = districtNamesByLen.find((n) => seg.startsWith(n)); const known = districtNamesByLen.find((n) => seg.startsWith(n));
if (known) return { district: known, rest: joinRest(seg.slice(known.length), tailRest) }; if (known) return { district: known, rest: joinRest(seg.slice(known.length), tailRest) };
const alias = districtAliasByLen.find(([from]) => seg.startsWith(from)); const alias = districtAliasByLen.find(([from]) => seg.startsWith(from));
if (alias) if (alias) return { district: alias[1], rest: joinRest(seg.slice(alias[0].length), tailRest) };
return { district: alias[1], rest: joinRest(seg.slice(alias[0].length), tailRest) };
const short = districtShortNames.find(([from]) => seg.startsWith(from)); const short = districtShortNames.find(([from]) => seg.startsWith(from));
if (short) { if (short) {
const [word, district] = short; const [word, district] = short;
...@@ -242,9 +241,15 @@ const COLUMN_ALIASES: Record<ColumnKey, string[]> = { ...@@ -242,9 +241,15 @@ const COLUMN_ALIASES: Record<ColumnKey, string[]> = {
}; };
function buildColumnMap(header: Array<unknown>): Record<ColumnKey, number> { function buildColumnMap(header: Array<unknown>): Record<ColumnKey, number> {
const cells = header.map((v) => String(v ?? '').trim().toLowerCase()); const cells = header.map((v) =>
String(v ?? '')
.trim()
.toLowerCase(),
);
const find = (aliases: string[]) => const find = (aliases: string[]) =>
cells.findIndex((c) => aliases.some((a) => c === a.toLowerCase() || c.includes(a.toLowerCase()))); cells.findIndex((c) =>
aliases.some((a) => c === a.toLowerCase() || c.includes(a.toLowerCase())),
);
const map: Record<ColumnKey, number> = { const map: Record<ColumnKey, number> = {
caseNo: find(COLUMN_ALIASES.caseNo), caseNo: find(COLUMN_ALIASES.caseNo),
address: find(COLUMN_ALIASES.address), address: find(COLUMN_ALIASES.address),
...@@ -394,9 +399,7 @@ export function ingestBytes( ...@@ -394,9 +399,7 @@ export function ingestBytes(
const isExcel = /\.xlsx$/i.test(fileName) || /\.xls$/i.test(fileName) || looksLikeZip(view); const isExcel = /\.xlsx$/i.test(fileName) || /\.xls$/i.test(fileName) || looksLikeZip(view);
onProgress?.('decode', 0.05); onProgress?.('decode', 0.05);
const rows: Array<Array<unknown>> = isExcel const rows: Array<Array<unknown>> = isExcel ? splitXlsx(bytes) : splitCsv(decodeCsv(view));
? splitXlsx(bytes)
: splitCsv(decodeCsv(view));
onProgress?.('decode', 0.5); onProgress?.('decode', 0.5);
if (rows.length < 2) throw new Error('文件里只有表头或完全是空的'); if (rows.length < 2) throw new Error('文件里只有表头或完全是空的');
...@@ -488,7 +491,10 @@ export function ingestBytes( ...@@ -488,7 +491,10 @@ export function ingestBytes(
} }
// 地址拆解:区按模板取第 3 段、具体地址取第 4 段起(剥名与兜底见 splitAddress) // 地址拆解:区按模板取第 3 段、具体地址取第 4 段起(剥名与兜底见 splitAddress)
const parts = address.split('-').map((s) => s.trim()).filter(Boolean); const parts = address
.split('-')
.map((s) => s.trim())
.filter(Boolean);
const { district, rest } = splitAddress(parts); const { district, rest } = splitAddress(parts);
if (!district) report.districtUnknown += 1; if (!district) report.districtUnknown += 1;
...@@ -516,7 +522,12 @@ export function ingestBytes( ...@@ -516,7 +522,12 @@ export function ingestBytes(
`${district || UNRESOLVED_LABEL}|${street}`, `${district || UNRESOLVED_LABEL}|${street}`,
'街道', '街道',
); );
const detailIdx = intern(addrDetailMap, addrDetails, detail || rest || '(地址未提供)', '详细地点'); const detailIdx = intern(
addrDetailMap,
addrDetails,
detail || rest || '(地址未提供)',
'详细地点',
);
const i = report.count; const i = report.count;
lngArr[i] = Math.round(lngDeg * COORD_SCALE); lngArr[i] = Math.round(lngDeg * COORD_SCALE);
...@@ -592,13 +603,6 @@ export function ingestBytes( ...@@ -592,13 +603,6 @@ export function ingestBytes(
columns, columns,
detail, detail,
report, report,
transfer: [ transfer: [columns.lng, columns.lat, columns.ts, columns.d, columns.s, detail.a],
columns.lng,
columns.lat,
columns.ts,
columns.d,
columns.s,
detail.a,
],
}; };
} }
...@@ -77,8 +77,11 @@ export function loadDetail(onProgress?: (p: LoadProgress) => void): Promise<Deta ...@@ -77,8 +77,11 @@ export function loadDetail(onProgress?: (p: LoadProgress) => void): Promise<Deta
/** 把浏览器空闲时间利用起来做非首屏必需的加载 */ /** 把浏览器空闲时间利用起来做非首屏必需的加载 */
export function whenIdle(fn: () => void, timeout = 2000): void { export function whenIdle(fn: () => void, timeout = 2000): void {
const ric = (window as unknown as { requestIdleCallback?: (cb: () => void, o?: { timeout: number }) => number }) const ric = (
.requestIdleCallback; window as unknown as {
requestIdleCallback?: (cb: () => void, o?: { timeout: number }) => number;
}
).requestIdleCallback;
if (typeof ric === 'function') { if (typeof ric === 'function') {
ric(fn, { timeout }); ric(fn, { timeout });
} else { } else {
......
import { useMemo } from 'react';
import { useHeatmapStore } from '@/store/useHeatmapStore'; import { useHeatmapStore } from '@/store/useHeatmapStore';
import { fmtDateTime, fmtInt } from '@/utils/format'; import { fmtDateTime, fmtInt } from '@/utils/format';
import type { BucketRow } from '@/features/heatmap/aggregate/types';
// 定位标记用地图针(EnvironmentOutlined)而不是 AnchorOutlined:后者在网络语境里是 // 定位标记用地图针(EnvironmentOutlined)而不是 AnchorOutlined:后者在网络语境里是
// 「超链接锚点」,会被读成复制链接。口径同案件清单抽屉那一列。 // 「超链接锚点」,会被读成复制链接。口径同案件清单抽屉那一列。
import { EnvironmentOutlined } from '@ant-design/icons'; import { EnvironmentOutlined } from '@ant-design/icons';
import { Button, Drawer, Empty, Spin, Table, Tooltip } from 'antd'; import { Button, Drawer, Empty, Spin, Table, type TableColumnsType } from 'antd';
/** 明细表的行:数据行 + 全局序号 + 行键,都在铺数据那一步算好 */
type DetailRow = BucketRow & { seq: number; _k: string };
/** 明细还没到位时给表体的那个空值:必须是常量引用,`?? []` 每次渲染都给新数组,memo 等于没做 */
const NO_DETAIL_ROWS: BucketRow[] = [];
/**
* 明细抽屉的表头。
*
* 写在模块作用域:这张表每一页都要拿同一份列定义,放在组件里就是每次重渲染新建一个数组,
* Table 收到新引用便把拍平的列缓存重建一遍、把整页重画一遍。
* 这里没有「行政区」那一列 —— 明细本身就是一个小范围,整列同一个区没有信息量
* (案件清单抽屉在只切一个区时同样把它收掉)。
*
* 定位那一列的提示语走浏览器原生 title 而不是 antd Tooltip:一页就是一批浮层实例,
* 每次换页全建一遍、每次悬停算一次定位,而这句话只需要在鼠标停住时念出来。
*/
const DETAIL_COLUMNS: TableColumnsType<DetailRow> = [
{
title: '序号',
dataIndex: 'seq',
width: 56,
align: 'right',
render: (v: number) => (
<span style={{ color: 'var(--hm-text-3)', fontVariantNumeric: 'tabular-nums' }}>{v}</span>
),
},
{
title: '案件号',
dataIndex: 'caseNo',
width: 168,
render: (v: string) => (
<span style={{ color: 'var(--hm-primary)', fontVariantNumeric: 'tabular-nums' }}>{v}</span>
),
},
{
title: '报案时间',
dataIndex: 'ts',
width: 132,
render: (v: number) => fmtDateTime(v),
},
{
title: '出险地点',
dataIndex: 'address',
render: (v: string) => <span style={{ fontSize: 12 }}>{v}</span>,
},
/**
* 定位到地图上的这一处。列的样式、位置和案件清单抽屉那一列完全一样:
* 同一个动作在所有名单里都长同一个样、都在最右一列,鼠标不用重新找。
* 单独一列而不是跟在地址文字后面 —— 地址长短不一,贴在后面时每行的
* 点击目标都落在不同的横向位置。
*/
{
title: '定位',
key: 'locate',
width: 56,
align: 'center',
render: (_v: unknown, r) => (
<Button
type="text"
size="small"
className="hm-locate"
icon={<EnvironmentOutlined />}
title="在地图上定位这一处(明细保持打开)"
aria-label={`定位 ${r.caseNo}`}
onClick={(e) => {
// 翻页、点别的行都不该被这次点击顺带触发
e.stopPropagation();
// 牌子上写出险地址;地址列还没到位时那一段是空的,退回案件号,
// 免得标记旁边挂一块什么都没有的白牌
useHeatmapStore.getState().focusCasePoint({
lng: r.lng,
lat: r.lat,
address: r.address || r.caseNo,
});
}}
/>
),
},
];
/** /**
* 明细抽屉。两种取数范围共用它: * 明细抽屉。两种取数范围共用它:
...@@ -20,10 +103,14 @@ export function BucketDrawer() { ...@@ -20,10 +103,14 @@ export function BucketDrawer() {
const selection = useHeatmapStore((s) => s.selection); const selection = useHeatmapStore((s) => s.selection);
const scopeLabel = useHeatmapStore((s) => s.scopeLabel); const scopeLabel = useHeatmapStore((s) => s.scopeLabel);
const clearHotspot = useHeatmapStore((s) => s.clearHotspot); const clearHotspot = useHeatmapStore((s) => s.clearHotspot);
const focusCasePoint = useHeatmapStore((s) => s.focusCasePoint);
const clearCasePin = useHeatmapStore((s) => s.clearCasePin); const clearCasePin = useHeatmapStore((s) => s.clearCasePin);
const rows = members?.rows ?? []; const rows = members?.rows ?? NO_DETAIL_ROWS;
// 序号与行键只在数据真的换了一份时才算一遍(见上面那段注释里的口径)
const tableRows = useMemo(
() => rows.map((r, i) => ({ ...r, seq: i + 1, _k: `${r.caseNo}-${i}` })),
[rows],
);
return ( return (
<Drawer <Drawer
...@@ -96,75 +183,9 @@ export function BucketDrawer() { ...@@ -96,75 +183,9 @@ export function BucketDrawer() {
// 序号在铺数据时按全局下标算好,不用 render 里的页内 index: // 序号在铺数据时按全局下标算好,不用 render 里的页内 index:
// 后者每页都从 1 开始,翻到第二页就对不上「共 N 起」,也不能用来口述第几行。 // 后者每页都从 1 开始,翻到第二页就对不上「共 N 起」,也不能用来口述第几行。
// 各列宽度和案件清单抽屉对齐:两张抽屉列的是同一批字段,横着摆在一起不该一宽一窄。 // 各列宽度和案件清单抽屉对齐:两张抽屉列的是同一批字段,横着摆在一起不该一宽一窄。
dataSource={rows.map((r, i) => ({ ...r, seq: i + 1, _k: `${r.caseNo}-${i}` }))} dataSource={tableRows}
columns={[ rowKey="_k"
{ columns={DETAIL_COLUMNS}
title: '序号',
dataIndex: 'seq',
width: 56,
align: 'right',
render: (v: number) => (
<span style={{ color: 'var(--hm-text-3)', fontVariantNumeric: 'tabular-nums' }}>
{v}
</span>
),
},
{
title: '案件号',
dataIndex: 'caseNo',
width: 168,
render: (v: string) => (
<span style={{ color: 'var(--hm-primary)', fontVariantNumeric: 'tabular-nums' }}>
{v}
</span>
),
},
{
title: '报案时间',
dataIndex: 'ts',
width: 132,
render: (v: number) => fmtDateTime(v),
},
{
title: '出险地点',
dataIndex: 'address',
render: (v: string) => <span style={{ fontSize: 12 }}>{v}</span>,
},
/**
* 定位到地图上的这一处。列的样式、位置和案件清单抽屉那一列完全一样:
* 同一个动作在所有名单里都长同一个样、都在最右一列,鼠标不用重新找。
* 单独一列而不是跟在地址文字后面 —— 地址长短不一,贴在后面时每行的
* 点击目标都落在不同的横向位置。
*/
{
title: '定位',
key: 'locate',
width: 56,
align: 'center',
render: (_v: unknown, r) => (
<Tooltip title="在地图上定位这一处(明细保持打开)">
<Button
type="text"
size="small"
className="hm-locate"
icon={<EnvironmentOutlined />}
aria-label={`定位 ${r.caseNo}`}
onClick={(e) => {
// 翻页、点别的行都不该被这次点击顺带触发
e.stopPropagation();
// 牌子上写出险地址;地址列还没到位时那一段是空的,退回案件号,
// 免得标记旁边挂一块什么都没有的白牌
focusCasePoint({
lng: r.lng,
lat: r.lat,
address: r.address || r.caseNo,
});
}}
/>
</Tooltip>
),
},
]}
/> />
)} )}
......
...@@ -9,6 +9,7 @@ import { ...@@ -9,6 +9,7 @@ import {
Select, Select,
Spin, Spin,
Table, Table,
type TableColumnsType,
Tooltip, Tooltip,
} from 'antd'; } from 'antd';
import dayjs, { type Dayjs } from 'dayjs'; import dayjs, { type Dayjs } from 'dayjs';
...@@ -26,6 +27,7 @@ import { ...@@ -26,6 +27,7 @@ import {
} from '@/features/heatmap/spotlight/spotlightView'; } from '@/features/heatmap/spotlight/spotlightView';
import { import {
UNRESOLVED_LABEL, UNRESOLVED_LABEL,
type BucketRow,
type RosterPick, type RosterPick,
type RosterWhere, type RosterWhere,
} from '@/features/heatmap/aggregate/types'; } from '@/features/heatmap/aggregate/types';
...@@ -50,6 +52,9 @@ const PRESET_OPTIONS: Array<{ label: string; value: PickPreset }> = [ ...@@ -50,6 +52,9 @@ const PRESET_OPTIONS: Array<{ label: string; value: PickPreset }> = [
]; ];
const WEEKDAY_NAMES = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']; const WEEKDAY_NAMES = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
/** 名单还没到位时给表体的那个空值:必须是常量引用,见 CaseRosterDrawer 里 rows 那一行 */
const NO_ROWS: BucketRow[] = [];
/** /**
* 右缘那张「清单」抽屉的位置。 * 右缘那张「清单」抽屉的位置。
* *
...@@ -111,7 +116,9 @@ function CaseRosterDrawer() { ...@@ -111,7 +116,9 @@ function CaseRosterDrawer() {
const result = view?.result ?? null; const result = view?.result ?? null;
const loading = view?.loading ?? false; const loading = view?.loading ?? false;
const rows = result?.rows ?? []; // 空表用模块级那一份常量:`?? []` 每次渲染都给一个新数组,
// 下面那份按 rows 建的表体就会每次渲染重算一遍,memo 等于没做
const rows = result?.rows ?? NO_ROWS;
const total = result?.total ?? 0; const total = result?.total ?? 0;
const pick = view?.query.pick; const pick = view?.query.pick;
const seed = view?.seed; const seed = view?.seed;
...@@ -232,6 +239,111 @@ function CaseRosterDrawer() { ...@@ -232,6 +239,111 @@ function CaseRosterDrawer() {
if (spot) st.openSpotlight(spot); if (spot) st.openSpotlight(spot);
}; };
/**
* 表体与表头各 memo 一次。
*
* Table 每拿到一个新的 columns / dataSource 引用,就把拍平的列缓存重建一遍、整页重画一遍;
* 而这张抽屉的父组件每点一次筛钮、每改一次时间都要重渲染,那一百行于是跟着重渲染 ——
* 哪怕这一页的数据一个字节都没换。序号按全局下标算(页内 index 翻到第二页就从 1 重来,
* 对不上「共 N 起」),所以它只跟 rows 与 offset 有关。
*/
const showDistrictColumn = !(pick && pick.districts.length === 1);
const offset = view?.query.offset ?? 0;
const caseRows = useMemo(
() => rows.map((r, i) => ({ ...r, seq: offset + i + 1 })),
[rows, offset],
);
const caseColumns = useMemo<TableColumnsType<BucketRow & { seq: number }>>(
() => [
{
title: '序号',
dataIndex: 'seq',
width: 56,
align: 'right',
render: (v: number) => (
<span style={{ color: 'var(--hm-text-3)', fontVariantNumeric: 'tabular-nums' }}>{v}</span>
),
},
{
title: '案件号',
dataIndex: 'caseNo',
width: 168,
render: (v: string) => (
<span style={{ color: 'var(--hm-primary)', fontVariantNumeric: 'tabular-nums' }}>
{v}
</span>
),
},
{
title: '报案时间',
dataIndex: 'ts',
width: 132,
render: (v: number) => fmtDateTime(v),
},
// 已经限定到一个区时不再列「行政区」:整列一模一样的字,
// 白占一个本可以放地址的位(地址列本身也带着区名)
...(showDistrictColumn
? [
{
title: '行政区',
dataIndex: 'district',
width: 76,
render: (v: number) => (
<span style={{ color: 'var(--hm-text-2)', fontSize: 12 }}>
{placeNameOf(meta?.dict.districts[v]) || '未标注'}
</span>
),
},
]
: []),
{
title: '出险地点',
dataIndex: 'address',
render: (v: string) => <span style={{ fontSize: 12 }}>{v}</span>,
},
/**
* 定位到地图上的这一处。
*
* 单独一列而不是跟在地址后面:地址长短不一,图标贴在文字后面时
* 每行的点击目标都落在不同的横向位置,鼠标要来回找。
* 也只给图标不加文字 —— 这一列每一行都一样,写满「定位」两个字
* 会把地址列挤到读不完。
*
* 提示语走浏览器原生的 title 而不是 antd 的 Tooltip:一页最多一百行,
* 包一层 Tooltip 就是一百只浮层实例,每次换页全建一遍、每次悬停算一次定位,
* 而这句话只需要在鼠标停住时念出来。
*/
{
title: '定位',
key: 'locate',
width: 56,
align: 'center',
render: (_v: unknown, r) => (
<Button
type="text"
size="small"
className="hm-locate"
icon={<EnvironmentOutlined />}
title="在地图上定位这一处(清单保持打开)"
aria-label={`定位 ${r.caseNo}`}
onClick={(e) => {
// 翻页、点别的行都不该被这次点击顺带触发
e.stopPropagation();
// 牌子上写出险地址;地址列还没到位时那一段是空的,退回案件号,
// 免得标记旁边挂一块什么都没有的白牌
focusCasePoint({
lng: r.lng,
lat: r.lat,
address: r.address || r.caseNo,
});
}}
/>
),
},
],
[showDistrictColumn, meta, focusCasePoint],
);
return ( return (
<Drawer <Drawer
rootClassName="hm-drawer-glass" rootClassName="hm-drawer-glass"
...@@ -410,8 +522,8 @@ function CaseRosterDrawer() { ...@@ -410,8 +522,8 @@ function CaseRosterDrawer() {
size="small" size="small"
loading={loading} loading={loading}
rowKey={(r) => `${r.caseNo}-${r.ts}-${r.lng}`} rowKey={(r) => `${r.caseNo}-${r.ts}-${r.lng}`}
// 序号按全局下标算:页内 index 翻到第二页就从 1 重来,对不上「共 N 起」 dataSource={caseRows}
dataSource={rows.map((r, i) => ({ ...r, seq: view.query.offset + i + 1 }))} columns={caseColumns}
pagination={{ pagination={{
current: Math.floor(view.query.offset / view.query.limit) + 1, current: Math.floor(view.query.offset / view.query.limit) + 1,
pageSize: view.query.limit, pageSize: view.query.limit,
...@@ -426,92 +538,6 @@ function CaseRosterDrawer() { ...@@ -426,92 +538,6 @@ function CaseRosterDrawer() {
onChange: (page, pageSize) => onChange: (page, pageSize) =>
useHeatmapStore.getState().setRosterPage((page - 1) * pageSize, pageSize), useHeatmapStore.getState().setRosterPage((page - 1) * pageSize, pageSize),
}} }}
columns={[
{
title: '序号',
dataIndex: 'seq',
width: 56,
align: 'right',
render: (v: number) => (
<span style={{ color: 'var(--hm-text-3)', fontVariantNumeric: 'tabular-nums' }}>
{v}
</span>
),
},
{
title: '案件号',
dataIndex: 'caseNo',
width: 168,
render: (v: string) => (
<span style={{ color: 'var(--hm-primary)', fontVariantNumeric: 'tabular-nums' }}>
{v}
</span>
),
},
{
title: '报案时间',
dataIndex: 'ts',
width: 132,
render: (v: number) => fmtDateTime(v),
},
// 已经限定到一个区时不再列「行政区」:整列一模一样的字,
// 白占一个本可以放地址的位(地址列本身也带着区名)
...(pick && pick.districts.length === 1
? []
: [
{
title: '行政区',
dataIndex: 'district',
width: 76,
render: (v: number) => (
<span style={{ color: 'var(--hm-text-2)', fontSize: 12 }}>
{placeNameOf(meta?.dict.districts[v]) || '未标注'}
</span>
),
},
]),
{
title: '出险地点',
dataIndex: 'address',
render: (v: string) => <span style={{ fontSize: 12 }}>{v}</span>,
},
/**
* 定位到地图上的这一处。
*
* 单独一列而不是跟在地址后面:地址长短不一,图标贴在文字后面时
* 每行的点击目标都落在不同的横向位置,鼠标要来回找。
* 也只给图标不加文字 —— 这一列每一行都一样,写满「定位」两个字
* 会把地址列挤到读不完。
*/
{
title: '定位',
key: 'locate',
width: 56,
align: 'center',
render: (_v: unknown, r) => (
<Tooltip title="在地图上定位这一处(清单保持打开)">
<Button
type="text"
size="small"
className="hm-locate"
icon={<EnvironmentOutlined />}
aria-label={`定位 ${r.caseNo}`}
onClick={(e) => {
// 翻页、点别的行都不该被这次点击顺带触发
e.stopPropagation();
// 牌子上写出险地址;地址列还没到位时那一段是空的,退回案件号,
// 免得标记旁边挂一块什么都没有的白牌
focusCasePoint({
lng: r.lng,
lat: r.lat,
address: r.address || r.caseNo,
});
}}
/>
</Tooltip>
),
},
]}
/> />
<div className="hm-roster-foot"> <div className="hm-roster-foot">
......
import { Drawer, Empty, Table } from 'antd'; import { useMemo } from 'react';
import { Drawer, Empty, Table, type TableColumnsType } from 'antd';
import { useHeatmapStore } from '@/store/useHeatmapStore'; import { useHeatmapStore } from '@/store/useHeatmapStore';
import { bucketBBox } from '@/features/heatmap/aggregate/viewSnapshot'; import { bucketBBox } from '@/features/heatmap/aggregate/viewSnapshot';
import type { PointRosterRow } from '@/features/heatmap/aggregate/types'; import type { PointRosterRow } from '@/features/heatmap/aggregate/types';
...@@ -30,6 +31,78 @@ export function PointListDrawer() { ...@@ -30,6 +31,78 @@ export function PointListDrawer() {
// 条形只在这一批格子之间归一(最多的一格 = 满格):和面板两张榜同一口径 // 条形只在这一批格子之间归一(最多的一格 = 满格):和面板两张榜同一口径
const maxCount = rows.length ? rows[0].count : 0; const maxCount = rows.length ? rows[0].count : 0;
const listedCases = rows.reduce((sum, r) => sum + r.count, 0); const listedCases = rows.reduce((sum, r) => sum + r.count, 0);
/**
* 表头 memo 一次:条形那一列要按「这批格子里最多的一格」归一,所以它只跟 maxCount 有关。
* 放在 render 里就是每次重渲染换一个新引用,Table 收到新引用会把整页重画一遍。
*/
const columns = useMemo<TableColumnsType<PointRosterRow>>(
() => [
{
title: '名次',
dataIndex: 'seq',
width: 56,
align: 'right',
render: (v: number) => (
<span style={{ color: 'var(--hm-text-3)', fontVariantNumeric: 'tabular-nums' }}>{v}</span>
),
},
{
title: '案件数',
dataIndex: 'count',
width: 84,
align: 'right',
render: (v: number) => (
<span style={{ color: 'var(--hm-primary)', fontVariantNumeric: 'tabular-nums' }}>
{fmtCompact(v)}
</span>
),
},
{
title: '与最多的一格相比',
dataIndex: 'count',
key: 'bar',
width: 132,
render: (v: number) => (
<div className="hm-board__bar">
<div
style={{
width: `${maxCount ? Math.max((v / maxCount) * 100, 1.5) : 0}%`,
// 整表一种墨色:长短是唯一的编码,颜色在这里没有第二层含义
background: 'var(--hm-primary)',
}}
/>
</div>
),
},
{
title: '屏幕位置',
key: 'pos',
width: 108,
render: (_v: unknown, r: PointRosterRow) => (
<span style={{ color: 'var(--hm-text-2)', fontSize: 12 }}>
第 {r.col} 列 第 {r.row} 行
</span>
),
},
{
title: '中心坐标',
key: 'coord',
render: (_v: unknown, r: PointRosterRow) => (
<span
style={{
fontSize: 12,
color: 'var(--hm-text-2)',
fontVariantNumeric: 'tabular-nums',
}}
title="方格中心:这一格里所有案件经纬度的平均位置"
>
{r.lng.toFixed(5)}, {r.lat.toFixed(5)}
</span>
),
},
],
[maxCount],
);
return ( return (
<Drawer <Drawer
...@@ -93,73 +166,7 @@ export function PointListDrawer() { ...@@ -93,73 +166,7 @@ export function PointListDrawer() {
})} })}
rowClassName={() => 'hm-row--link'} rowClassName={() => 'hm-row--link'}
dataSource={rows} dataSource={rows}
columns={[ columns={columns}
{
title: '名次',
dataIndex: 'seq',
width: 56,
align: 'right',
render: (v: number) => (
<span style={{ color: 'var(--hm-text-3)', fontVariantNumeric: 'tabular-nums' }}>
{v}
</span>
),
},
{
title: '案件数',
dataIndex: 'count',
width: 84,
align: 'right',
render: (v: number) => (
<span style={{ color: 'var(--hm-primary)', fontVariantNumeric: 'tabular-nums' }}>
{fmtCompact(v)}
</span>
),
},
{
title: '与最多的一格相比',
dataIndex: 'count',
key: 'bar',
width: 132,
render: (v: number) => (
<div className="hm-board__bar">
<div
style={{
width: `${maxCount ? Math.max((v / maxCount) * 100, 1.5) : 0}%`,
// 整表一种墨色:长短是唯一的编码,颜色在这里没有第二层含义
background: 'var(--hm-primary)',
}}
/>
</div>
),
},
{
title: '屏幕位置',
key: 'pos',
width: 108,
render: (_v: unknown, r: PointRosterRow) => (
<span style={{ color: 'var(--hm-text-2)', fontSize: 12 }}>
第 {r.col} 列 第 {r.row} 行
</span>
),
},
{
title: '中心坐标',
key: 'coord',
render: (_v: unknown, r: PointRosterRow) => (
<span
style={{
fontSize: 12,
color: 'var(--hm-text-2)',
fontVariantNumeric: 'tabular-nums',
}}
title="方格中心:这一格里所有案件经纬度的平均位置"
>
{r.lng.toFixed(5)}, {r.lat.toFixed(5)}
</span>
),
},
]}
/> />
)} )}
......
import { ellipsize, roundRectPath } from './canvasKit'; import { ellipsizeBy, roundRectPath } from './canvasKit';
import { MAP_LABEL_FONT, PALETTE, paletteHexToRgb, rgbCss } from './palette'; import { MAP_LABEL_FONT, PALETTE, paletteHexToRgb, rgbCss } from './palette';
import { CanvasSurface, mercY, textWidth } from './viewFrame';
/** 主色与浅主色先折成 rgb 三元组:draw 每帧都要拼颜色,别在帧里反复解析 hex */ /** 主色与浅主色先折成 rgb 三元组:牌子描边每帧都要用,别在帧里反复解析 hex */
const PRIMARY = paletteHexToRgb(PALETTE.primary); const PRIMARY = paletteHexToRgb(PALETTE.primary);
const PRIMARY_SOFT = paletteHexToRgb(PALETTE.primarySoft); const PRIMARY_SOFT = paletteHexToRgb(PALETTE.primarySoft);
const RING_START = rgbCss(PRIMARY, 0.3);
const RING_END = rgbCss(PRIMARY, 0);
const PIN_RING = rgbCss(PRIMARY, 0.9);
/** 屏幕上被定位的那一起案件 */ /** 屏幕上被定位的那一起案件 */
export interface CasePin { export interface CasePin {
...@@ -45,6 +49,25 @@ const HALO_FRAME_MS = 33; ...@@ -45,6 +49,25 @@ const HALO_FRAME_MS = 33;
* 再长就已经超出「瞄一眼定位到哪一个」的需要了,完整地址在清单那一行里。 * 再长就已经超出「瞄一眼定位到哪一个」的需要了,完整地址在清单那一行里。
*/ */
const CHIP_MAX_TEXT_W = 260; const CHIP_MAX_TEXT_W = 260;
const CHIP_H = 18;
/** 牌子左右内边距:文字宽 + 这一段 = 牌子宽 */
const CHIP_PAD = 14;
/** 两块牌子与标记之间的空隙(上方一块贴着标记上沿,下方一块贴着光圈内沿) */
const CHIP_ABOVE_GAP = 22;
const CHIP_BELOW_GAP = 8;
const CHIP_FONT_MAIN = `600 11px ${MAP_LABEL_FONT}`;
const CHIP_FONT_SUB = `400 11px ${MAP_LABEL_FONT}`;
/** 量不到画布时的一字兜底宽度。只影响牌子长短,不参与任何数字口径 */
const FALLBACK_CHAR_W = 10;
/** 一块牌子:文字与尺寸在定位那一次算好,光圈每帧只是照着落笔 */
interface PreparedChip {
text: string;
w: number;
/** 这套尺寸按多宽的画布算的(牌子最大宽度跟着画布走),画布没变就不重算 */
fittedW: number;
}
/** /**
* 案件定位标记层 —— 清单里点「定位」之后钉在屏幕上的那一个点。 * 案件定位标记层 —— 清单里点「定位」之后钉在屏幕上的那一个点。
...@@ -60,13 +83,25 @@ const CHIP_MAX_TEXT_W = 260; ...@@ -60,13 +83,25 @@ const CHIP_MAX_TEXT_W = 260;
* 光圈在标记存在期间一直转。这和「定位期间把热力、方格数字、黑点盘暂时收起」是同一件事 * 光圈在标记存在期间一直转。这和「定位期间把热力、方格数字、黑点盘暂时收起」是同一件事
* 的两半:那些覆盖物收掉之后,屏幕上只剩底图,画面里没有一处还在动的东西, * 的两半:那些覆盖物收掉之后,屏幕上只剩底图,画面里没有一处还在动的东西,
* 用户很难在几百公里的底图里第一时间逮住那一针。 * 用户很难在几百公里的底图里第一时间逮住那一针。
*
* ⚠️ 帧预算(2026-10-15 性能调优):这一层是唯一「自己会动」的层,所以它不能像另外三层
* 那样在视图没变时整帧跳过 —— 光圈得继续转。省的地方有两处:
* - 地图没动时只擦标记自己占的那一小块(见 CanvasSurface.beginAnimated),不再每 33ms
* 把整屏 clearRect 一遍。整屏清空会把这块画布的损坏区域扩到全屏,浏览器每帧都要按全屏
* 重做一遍合成与上传 ——「明明只有一颗点在闪、整页却跟着卡」就是这么来的;
* - 两块牌子的文字与尺寸在定位那一次算完(截断要逐字量一遍),光圈那一帧只是落笔。
* 转的还是同一个光圈、同一块牌子、同一行说明。
*/ */
export class CasePinLayer { export class CasePinLayer {
private layer: AMap.CustomLayer | null = null; private layer: AMap.CustomLayer | null = null;
private canvas: HTMLCanvasElement | null = null; private surface: CanvasSurface | null = null;
private ctx: CanvasRenderingContext2D | null = null;
private pin: CasePin | null = null; private pin: { lng: number; my: number; address: string } | null = null;
/** 上一帧真正落笔的屏幕范围(光圈外沿 ∪ 两块牌子),下一帧只擦这一块 */
private dirty = new Float64Array(4);
private hasDirty = false;
private chipMain: PreparedChip = { text: '', w: 0, fittedW: -1 };
private chipSub: PreparedChip = { text: '', w: 0, fittedW: -1 };
private lastFrame = 0; private lastFrame = 0;
private raf = 0; private raf = 0;
...@@ -74,18 +109,15 @@ export class CasePinLayer { ...@@ -74,18 +109,15 @@ export class CasePinLayer {
private ensure() { private ensure() {
if (this.layer) return; if (this.layer) return;
const canvas = document.createElement('canvas'); const surface = new CanvasSurface();
canvas.style.position = 'absolute'; this.surface = surface;
canvas.style.left = '0';
canvas.style.top = '0'; const layer = new AMap.CustomLayer(surface.canvas, {
// 标记只做提示,不接点击:接了就会抢掉地图拖动,也会和桶、黑点的命中判定打架
canvas.style.pointerEvents = 'none';
this.canvas = canvas;
const layer = new AMap.CustomLayer(canvas, {
// 高于黑点层(140):定位标记是用户此刻正在找的东西,盖过一切结论 // 高于黑点层(140):定位标记是用户此刻正在找的东西,盖过一切结论
zIndex: 150, zIndex: 150,
zooms: [3, 20], zooms: [3, 20],
// 标记必须跟着地图走,所以拖动途中地图发起的每一帧都要落笔;
// 地图不动时由下面那条 33ms 的 rAF 驱动光圈,笔只在标记那一小块里动
alwaysRender: true, alwaysRender: true,
}); });
layer.render = () => this.draw(); layer.render = () => this.draw();
...@@ -96,14 +128,21 @@ export class CasePinLayer { ...@@ -96,14 +128,21 @@ export class CasePinLayer {
/** 传 null 即撤掉标记(清单收起、换看别的名单时) */ /** 传 null 即撤掉标记(清单收起、换看别的名单时) */
setPin(pin: CasePin | null) { setPin(pin: CasePin | null) {
this.ensure(); this.ensure();
this.pin = pin;
if (!pin) { if (!pin) {
this.stopHalo(); this.stopHalo();
this.draw(); this.pin = null;
this.hasDirty = false;
// release 一次做掉两件事:画布清零(标记当场消失),并把这块全屏 backing store 交还
this.surface?.release();
return; return;
} }
this.pin = { lng: pin.lng, my: mercY(pin.lat), address: pin.address };
// 牌子上的字只由地址与画布宽度决定,与地图无关:重新定位就重算一次
this.chipMain.fittedW = -1;
this.chipSub.fittedW = -1;
// 重复定位同一个点也要重新走一遍取景,所以这里无条件重开光圈 // 重复定位同一个点也要重新走一遍取景,所以这里无条件重开光圈
this.lastFrame = 0; this.lastFrame = 0;
this.surface?.invalidate();
this.startHalo(); this.startHalo();
this.draw(); this.draw();
} }
...@@ -131,50 +170,71 @@ export class CasePinLayer { ...@@ -131,50 +170,71 @@ export class CasePinLayer {
destroy() { destroy() {
this.stopHalo(); this.stopHalo();
this.pin = null; this.pin = null;
if (this.layer) { this.layer?.setMap(null);
this.layer.setMap(null);
this.layer = null; this.layer = null;
} this.surface?.destroy();
this.canvas = null; this.surface = null;
this.ctx = null;
} }
private draw() { private draw() {
const canvas = this.canvas; const surface = this.surface;
const ctx = this.ctx ?? canvas?.getContext('2d') ?? null; if (!surface) return;
if (!canvas || !ctx) return; const opened = surface.beginAnimated(this.map);
this.ctx = ctx; if (!opened) return;
const ctx = surface.context;
const size = this.map.getSize(); if (!ctx) return;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
if ( // 地图没动 → beginAnimated 不整屏清空,只把上一帧标记那一块擦掉再重画
canvas.width !== Math.round(size.width * dpr) || if (!opened.clearedAll && this.hasDirty) {
canvas.height !== Math.round(size.height * dpr) ctx.clearRect(this.dirty[0], this.dirty[1], this.dirty[2], this.dirty[3]);
) {
canvas.width = Math.round(size.width * dpr);
canvas.height = Math.round(size.height * dpr);
canvas.style.width = `${size.width}px`;
canvas.style.height = `${size.height}px`;
} }
ctx.setTransform(dpr, 0, 0, dpr, 0, 0); this.hasDirty = false;
ctx.clearRect(0, 0, size.width, size.height);
const pin = this.pin; const pin = this.pin;
if (!pin) return; if (!pin) return;
const p = this.map.lngLatToContainer([pin.lng, pin.lat]); const x = surface.frame.x(pin.lng);
const x = p.x; const y = surface.frame.y(pin.my);
const y = p.y; const w = surface.width;
if (x < -40 || y < -60 || x > size.width + 40 || y > size.height + 60) return; const h = surface.height;
if (x < -40 || y < -60 || x > w + 40 || y > h + 60) return;
this.drawHalo(ctx, x, y);
const main = this.fitChip(this.chipMain, pin.address, CHIP_FONT_MAIN, w);
const sub = this.fitChip(
this.chipSub,
// 覆盖物是被暂时收走的,不是没了。不写这一句,屏幕突然空一半看着像图坏了
'定位中 · 热力与数字已暂时收起',
CHIP_FONT_SUB,
w,
);
const above = this.drawChip(ctx, main, x, y - CHIP_ABOVE_GAP - CHIP_H, w, h, false);
// 说明行落在标记下方:离环内沿留 8px,再往下就是它的顶边(与原先的算法一致)
const below = this.drawChip(ctx, sub, x, y + CHIP_ABOVE_GAP + CHIP_BELOW_GAP, w, h, true);
// 扩散光圈:几圈由内向外淡出的环,错开相位连续转,标记在就一直转 // 记下这一帧占的地方:光圈按最外一圈算(环还在往外扩,按当前半径擦会留下残影),
// 两块牌子按它们真正落笔的位置算(贴屏幕边时会被收进来,不能照理论位置取)
const halo = HALO_END_R + 2;
const x0 = Math.min(x - halo, above.left, below.left);
const x1 = Math.max(x + halo, above.left + above.w, below.left + below.w);
const y0 = Math.min(y - halo, above.top);
const y1 = Math.max(y + halo, below.top + CHIP_H);
this.dirty[0] = Math.max(0, x0);
this.dirty[1] = Math.max(0, y0);
this.dirty[2] = Math.min(w, x1) - this.dirty[0];
this.dirty[3] = Math.min(h, y1) - this.dirty[1];
this.hasDirty = true;
}
/** 扩散光圈 + 白底衬 + 主色点 */
private drawHalo(ctx: CanvasRenderingContext2D, x: number, y: number) {
const now = performance.now(); const now = performance.now();
const phase = (now % HALO_PERIOD_MS) / HALO_PERIOD_MS; const phase = (now % HALO_PERIOD_MS) / HALO_PERIOD_MS;
// 底下一团随呼吸明暗的柔光:先给眼睛一块暖色区域,环才不至于像悬空的细线 // 底下一团随呼吸明暗的柔光:先给眼睛一块暖色区域,环才不至于像悬空的细线
const breathe = 0.5 + 0.5 * Math.sin(phase * Math.PI * 2); const breathe = 0.5 + 0.5 * Math.sin(phase * Math.PI * 2);
const glowR = HALO_START_R + 8 + 7 * breathe; const glowR = HALO_START_R + 8 + 7 * breathe;
const glow = ctx.createRadialGradient(x, y, 2, x, y, glowR); const glow = ctx.createRadialGradient(x, y, 2, x, y, glowR);
glow.addColorStop(0, rgbCss(PRIMARY, 0.3)); glow.addColorStop(0, RING_START);
glow.addColorStop(1, rgbCss(PRIMARY, 0)); glow.addColorStop(1, RING_END);
ctx.beginPath(); ctx.beginPath();
ctx.arc(x, y, glowR, 0, Math.PI * 2); ctx.arc(x, y, glowR, 0, Math.PI * 2);
ctx.fillStyle = glow; ctx.fillStyle = glow;
...@@ -196,17 +256,28 @@ export class CasePinLayer { ...@@ -196,17 +256,28 @@ export class CasePinLayer {
ctx.fillStyle = 'rgba(255, 255, 255, 0.92)'; ctx.fillStyle = 'rgba(255, 255, 255, 0.92)';
ctx.fill(); ctx.fill();
ctx.lineWidth = 1.5; ctx.lineWidth = 1.5;
ctx.strokeStyle = rgbCss(PRIMARY, 0.9); ctx.strokeStyle = PIN_RING;
ctx.stroke(); ctx.stroke();
ctx.beginPath(); ctx.beginPath();
ctx.arc(x, y, 4.5, 0, Math.PI * 2); ctx.arc(x, y, 4.5, 0, Math.PI * 2);
ctx.fillStyle = PALETTE.primary; ctx.fillStyle = PALETTE.primary;
ctx.fill(); ctx.fill();
}
this.drawChip(ctx, pin.address, x, y, size.width, size.height); /**
// 覆盖物是被暂时收走的,不是没了。不写这一句,屏幕突然空一半看着像图坏了 * 牌子上那一行字:截断 + 尺寸。
this.drawChip(ctx, '定位中 · 热力与数字已暂时收起', x, y + 22, size.width, size.height, true); *
* 画布宽度没变就沿用上一次的结果 —— 一次截断要逐字量几十遍,而它跟光圈转不转没关系。
*/
private fitChip(chip: PreparedChip, text: string, font: string, canvasW: number): PreparedChip {
if (chip.fittedW === canvasW) return chip;
const maxTextW = Math.min(CHIP_MAX_TEXT_W, canvasW - 24);
const measure = (t: string) => textWidth(font, t) ?? t.length * FALLBACK_CHAR_W;
chip.text = ellipsizeBy(measure, text, maxTextW);
chip.w = Math.min(maxTextW + CHIP_PAD, measure(chip.text) + CHIP_PAD);
chip.fittedW = canvasW;
return chip;
} }
/** /**
...@@ -217,36 +288,35 @@ export class CasePinLayer { ...@@ -217,36 +288,35 @@ export class CasePinLayer {
* 地址长度由填写决定,可能一路写到门牌后面的场所名,所以给牌子一个上限宽度: * 地址长度由填写决定,可能一路写到门牌后面的场所名,所以给牌子一个上限宽度:
* 超出就截断加省略号(完整地址在清单那一行里,牌子只负责「认得出是哪儿」)。 * 超出就截断加省略号(完整地址在清单那一行里,牌子只负责「认得出是哪儿」)。
* 上限也按画布宽度收:小窗口里牌子不该横穿整屏。 * 上限也按画布宽度收:小窗口里牌子不该横穿整屏。
*
* @returns 牌子真正落笔的位置与宽度(贴屏幕边时会被收进来,擦除范围按这个算)
*/ */
private drawChip( private drawChip(
ctx: CanvasRenderingContext2D, ctx: CanvasRenderingContext2D,
text: string, chip: PreparedChip,
x: number, x: number,
y: number, idealTop: number,
canvasW: number, canvasW: number,
canvasH: number, canvasH: number,
below = false, below: boolean,
) { ): { left: number; top: number; w: number } {
ctx.font = `${below ? 400 : 600} 11px ${MAP_LABEL_FONT}`; const w = chip.w;
const maxTextW = Math.min(CHIP_MAX_TEXT_W, canvasW - 24); const top = Math.max(4, Math.min(idealTop, canvasH - CHIP_H - 4));
const label = ellipsize(ctx, text, maxTextW);
const w = Math.min(maxTextW + 14, ctx.measureText(label).width + 14);
const h = 18;
const ideal = below ? y + 8 : y - 22 - h;
const top = Math.max(4, Math.min(ideal, canvasH - h - 4));
const left = Math.max(4, Math.min(x - w / 2, canvasW - w - 4)); const left = Math.max(4, Math.min(x - w / 2, canvasW - w - 4));
roundRectPath(ctx, left, top, w, h, 5); roundRectPath(ctx, left, top, w, CHIP_H, 5);
ctx.fillStyle = below ? 'rgba(255, 255, 255, 0.82)' : 'rgba(255, 255, 255, 0.94)'; ctx.fillStyle = below ? 'rgba(255, 255, 255, 0.82)' : 'rgba(255, 255, 255, 0.94)';
ctx.fill(); ctx.fill();
ctx.lineWidth = 1; ctx.lineWidth = 1;
ctx.strokeStyle = rgbCss(PRIMARY_SOFT, below ? 0.55 : 0.9); ctx.strokeStyle = rgbCss(PRIMARY_SOFT, below ? 0.55 : 0.9);
ctx.stroke(); ctx.stroke();
// 说明行比案件号淡一档:它是背景交代,不该和「钉住的是哪一行」争注意力 // 说明行比地址淡一档:它是背景交代,不该和「钉住的是哪一行」争注意力
ctx.font = below ? CHIP_FONT_SUB : CHIP_FONT_MAIN;
ctx.fillStyle = below ? 'rgba(34, 43, 95, 0.72)' : PALETTE.primaryDeep; ctx.fillStyle = below ? 'rgba(34, 43, 95, 0.72)' : PALETTE.primaryDeep;
ctx.textAlign = 'center'; ctx.textAlign = 'center';
ctx.textBaseline = 'middle'; ctx.textBaseline = 'middle';
ctx.fillText(label, left + w / 2, top + h / 2 + 0.5); ctx.fillText(chip.text, left + w / 2, top + CHIP_H / 2 + 0.5);
return { left, top, w };
} }
} }
...@@ -5,6 +5,7 @@ import { CLUSTER_LABEL, inkAt } from './palette'; ...@@ -5,6 +5,7 @@ import { CLUSTER_LABEL, inkAt } from './palette';
import { reference } from './HeatLayer'; import { reference } from './HeatLayer';
import { bucketTouchesSignificant, type SignificanceMask } from './significance'; import { bucketTouchesSignificant, type SignificanceMask } from './significance';
import { HOTSPOT_MAX_DRAW_PX, hotspotSpan } from './hotspotGeometry'; import { HOTSPOT_MAX_DRAW_PX, hotspotSpan } from './hotspotGeometry';
import { CanvasSurface, mercY, textWidth } from './viewFrame';
export type { SignificanceMask }; export type { SignificanceMask };
...@@ -59,6 +60,8 @@ const HIT_PAD = 7; ...@@ -59,6 +60,8 @@ const HIT_PAD = 7;
const DOT_HIT_R = 5; const DOT_HIT_R = 5;
/** 视口裁剪的外扩量,取底衬可能出现的最大半径 */ /** 视口裁剪的外扩量,取底衬可能出现的最大半径 */
const CULL_PAD = 26; const CULL_PAD = 26;
/** 拿不到画布时的一字兜底宽度(粗体数字约 6.2px)。只影响底衬大小,不参与任何数字口径 */
const FALLBACK_CHAR_W = 6.2;
/** /**
* 聚合数字层 —— 在本项目里**没有**使用高德的 AMap.MarkerCluster,原因有两条,都是硬约束: * 聚合数字层 —— 在本项目里**没有**使用高德的 AMap.MarkerCluster,原因有两条,都是硬约束:
...@@ -101,28 +104,40 @@ const CULL_PAD = 26; ...@@ -101,28 +104,40 @@ const CULL_PAD = 26;
* 还有一件事要交代清楚,否则这一层的数字会被读成算错了:这里的数字是**屏幕像素网格** * 还有一件事要交代清楚,否则这一层的数字会被读成算错了:这里的数字是**屏幕像素网格**
* 的计数,随缩放变化;黑点清单里的案件数是**地理连通域**的计数,不随缩放变化。 * 的计数,随缩放变化;黑点清单里的案件数是**地理连通域**的计数,不随缩放变化。
* 降噪开启后,被黑点盘压住的桶整块让位(见 setHotspotDiscs),一个位置只留一个数。 * 降噪开启后,被黑点盘压住的桶整块让位(见 setHotspotDiscs),一个位置只留一个数。
*
* ⚠️ 帧预算(2026-10-15 性能调优)。原先每帧对每个桶做一次 lngLatToContainer、
* 一次 toLocaleString、一次 measureText、一次字体串赋值 —— 一屏八百个格子就是每帧三千多次
* 跨模块调用加同样多的临时对象,而 CustomLayer 是每帧回调,页面停着不动也在付这笔钱。
* 现在这些全部挪到喂数据那一次做完(经纬度 → 墨卡托纬度、案量 → 数字串 → 底衬半径 → 靛墨),
* 每帧只剩「两次乘加求位置 + 落笔」,视图与本层都没变时整帧跳过(见 viewFrame.ts)。
* 屏上还是同一批数字、同一套深浅、同一种字 —— 改的只有「什么时候算它」。
*/ */
export class ClusterLayer { export class ClusterLayer {
private layer: AMap.CustomLayer | null = null; private layer: AMap.CustomLayer | null = null;
private canvas: HTMLCanvasElement | null = null; private surface: CanvasSurface | null = null;
private ctx: CanvasRenderingContext2D | null = null;
private opts: ClusterLayerOptions = { ...DEFAULT_CLUSTER_OPTIONS }; private opts: ClusterLayerOptions = { ...DEFAULT_CLUSTER_OPTIONS };
/* 当前数据集 */ /* 当前数据集 */
private lng: Int32Array = new Int32Array(0);
private lat: Int32Array = new Int32Array(0);
private count: Int32Array = new Int32Array(0); private count: Int32Array = new Int32Array(0);
private gx: Int32Array = new Int32Array(0); private gx: Int32Array = new Int32Array(0);
private gy: Int32Array = new Int32Array(0); private gy: Int32Array = new Int32Array(0);
/** 桶中心的经纬度(度):让位判定与命中回传用它,不再每桶除一次 1e6 */
private lngDeg = new Float64Array(0);
private latDeg = new Float64Array(0);
/** 桶中心的墨卡托纬度:与缩放无关,喂数据时算一次,每帧只剩减法与乘法 */
private my = new Float64Array(0);
/** 屏上那一串数字、它的底衬半径、本格那支靛墨 —— 都只由桶自己的案量决定 */
private label: string[] = [];
private plateR = new Float32Array(0);
private ink: string[] = [];
/** 这一格的数字走哪一档字号(1 = 长数字那档)。与底衬半径同源,画时按档切换 */
private wide = new Uint8Array(0);
/* 绘制缓存:屏幕坐标,供命中检测复用,避免点击时再做一次投影 */ /* 绘制缓存:屏幕坐标,供命中检测复用,避免点击时再做一次投影 */
private sx = new Float32Array(0); private sx = new Float32Array(0);
private sy = new Float32Array(0); private sy = new Float32Array(0);
private sr = new Float32Array(0); private sr = new Float32Array(0);
/* 文字宽度缓存:标签种类有限(数字 + 万),缓存后每帧省掉几百次 measureText */
private textW = new Map<string, number>();
private visible = true; private visible = true;
/** /**
* 数字浓淡的归一化上限。由 MapStage 从热力层喂过来(heat.maxWeight), * 数字浓淡的归一化上限。由 MapStage 从热力层喂过来(heat.maxWeight),
...@@ -147,17 +162,14 @@ export class ClusterLayer { ...@@ -147,17 +162,14 @@ export class ClusterLayer {
private ensure() { private ensure() {
if (this.layer) return; if (this.layer) return;
const canvas = document.createElement('canvas'); const surface = new CanvasSurface();
canvas.style.position = 'absolute'; this.surface = surface;
canvas.style.left = '0';
canvas.style.top = '0';
// 必须让地图继续接收鼠标事件,否则 canvas 会把拖动、缩放全部吃掉
canvas.style.pointerEvents = 'none';
this.canvas = canvas;
const layer = new AMap.CustomLayer(canvas, { const layer = new AMap.CustomLayer(surface.canvas, {
zIndex: 130, zIndex: 130,
zooms: [3, 20], zooms: [3, 20],
// 回调仍然每帧给(拖动途中地图一直在动,覆盖物必须跟着走),
// 但「这一帧到底画不画」由 CanvasSurface.begin 判:视图没动就整帧跳过。
alwaysRender: true, alwaysRender: true,
}); });
layer.render = () => this.draw(); layer.render = () => this.draw();
...@@ -180,8 +192,6 @@ export class ClusterLayer { ...@@ -180,8 +192,6 @@ export class ClusterLayer {
dLat = 0, dLat = 0,
) { ) {
this.ensure(); this.ensure();
this.lng = lng;
this.lat = lat;
this.count = count; this.count = count;
this.gx = gx; this.gx = gx;
this.gy = gy; this.gy = gy;
...@@ -195,11 +205,70 @@ export class ClusterLayer { ...@@ -195,11 +205,70 @@ export class ClusterLayer {
this.sx = new Float32Array(count.length); this.sx = new Float32Array(count.length);
this.sy = new Float32Array(count.length); this.sy = new Float32Array(count.length);
this.sr = new Float32Array(count.length); this.sr = new Float32Array(count.length);
this.recomputeLabels(lng, lat);
this.recomputeKeep(); this.recomputeKeep();
this.recomputeUnder(); this.recomputeUnder();
this.scheduleDraw(); this.scheduleDraw();
} }
/**
* 喂一次数据就把「这一格写什么、底衬多大、落在墨卡托哪一条纬线上、该用哪支墨」算完。
*
* 这四样都只与桶自己的数据有关(案量、经纬度、归一化上限),与缩放和屏幕都无关 ——
* 留在每帧里算,等于把同一道题在拖动途中重做几百遍,而那几百遍正是卡顿的账单。
* measureText 按标签去重:一屏几百个格子的数字,翻来覆去也就是几十种写法。
*
* ⚠️ 数字仍由 fmtCompact 给(与清单、盘心同一个函数),深浅仍由 inkLevel 给:
* 这里改的是算的时机,不是算的方式。
*/
private recomputeLabels(lng: Int32Array, lat: Int32Array) {
const n = this.count.length;
this.lngDeg = new Float64Array(n);
this.latDeg = new Float64Array(n);
this.my = new Float64Array(n);
this.label = new Array(n);
this.plateR = new Float32Array(n);
this.ink = new Array<string>(n);
this.wide = new Uint8Array(n);
const widths = new Map<string, number>();
const inks = new Map<number, string>();
const cap = this.ref || this.refSelf;
for (let i = 0; i < n; i += 1) {
const lngI = lng[i] / 1e6;
const latI = lat[i] / 1e6;
this.lngDeg[i] = lngI;
this.latDeg[i] = latI;
this.my[i] = mercY(latI);
const n0 = this.count[i];
const label = fmtCompact(n0);
this.label[i] = label;
// 字号档只看位数:四位数以下用正档,更长的(几千、几万)收紧一档,
// 底衬半径与它同源,否则长数字会顶出底衬
const wide = label.length > 3;
this.wide[i] = wide ? 1 : 0;
let tw = widths.get(label);
if (tw === undefined) {
// 量不到画布时(无 canvas 的环境)按字数估,只影响底衬大小
tw =
textWidth(wide ? CLUSTER_LABEL.fontWide : CLUSTER_LABEL.font, label) ??
label.length * FALLBACK_CHAR_W;
widths.set(label, tw);
}
// 底衬半径只由文字宽度决定,不随案件数放大 —— 这是遮挡能降下来的关键
this.plateR[i] = Math.max(LABEL_MIN_R, tw / 2 + 3);
// INK_FLOOR 抬底:1 起的字最淡,但仍要能在白底衬 + 暖色热力上认出来。
// 深浅只由案量决定,同一个数在全屏必然同色,所以按数查表;一屏的案量种类远少于格子数
let ink = inks.get(n0);
if (ink === undefined) {
ink = inkAt(INK_FLOOR + (1 - INK_FLOOR) * inkLevel(n0, cap));
inks.set(n0, ink);
}
this.ink[i] = ink;
}
}
clear() { clear() {
this.setData( this.setData(
new Int32Array(0), new Int32Array(0),
...@@ -216,8 +285,15 @@ export class ClusterLayer { ...@@ -216,8 +285,15 @@ export class ClusterLayer {
if (!visible) return; if (!visible) return;
this.ensure(); this.ensure();
} }
if (visible) this.layer?.show(); if (visible) {
else this.layer?.hide(); this.layer?.show();
this.surface?.invalidate();
} else {
this.layer?.hide();
// 收起期间不必继续占着一张全屏画布:图层开关、聚焦与定位让位都会走到这里,
// 而一张 DPR 2 的全屏画布就是三十来兆 backing store 加一块参与合成的表面
this.surface?.release();
}
} }
/** 传入 null 即关掉淡化,恢复「所有格子都写数字」的原始视图 */ /** 传入 null 即关掉淡化,恢复「所有格子都写数字」的原始视图 */
...@@ -244,9 +320,23 @@ export class ClusterLayer { ...@@ -244,9 +320,23 @@ export class ClusterLayer {
* 必须从热力层拿而不是自己算:那边算的是「视野内、且过了降噪过滤的那批桶」的分位上限, * 必须从热力层拿而不是自己算:那边算的是「视野内、且过了降噪过滤的那批桶」的分位上限,
* 自己按整批数组算会多用一圈屏幕外的桶,同一屏就会得出两个「最高档」—— * 自己按整批数组算会多用一圈屏幕外的桶,同一屏就会得出两个「最高档」——
* 表现是淡字压在最亮的底色上,深浅看着错乱。传 0 表示退回 setData 里的兜底值。 * 表现是淡字压在最亮的底色上,深浅看着错乱。传 0 表示退回 setData 里的兜底值。
*
* 深浅是逐桶查表算好的,所以这里只换分母重填那张表(一次归一化上限的对数换算),
* 不在每帧里现算几百个对数。
*/ */
setReference(max: number) { setReference(max: number) {
this.ref = max > 0 ? max : 0; this.ref = max > 0 ? max : 0;
const cap = this.ref || this.refSelf;
const inks = new Map<number, string>();
for (let i = 0; i < this.ink.length; i += 1) {
const n = this.count[i];
let ink = inks.get(n);
if (ink === undefined) {
ink = inkAt(INK_FLOOR + (1 - INK_FLOOR) * inkLevel(n, cap));
inks.set(n, ink);
}
this.ink[i] = ink;
}
this.scheduleDraw(); this.scheduleDraw();
} }
...@@ -271,9 +361,7 @@ export class ClusterLayer { ...@@ -271,9 +361,7 @@ export class ClusterLayer {
const halfLng = this.dLng / 2; const halfLng = this.dLng / 2;
const halfLat = this.dLat / 2; const halfLat = this.dLat / 2;
for (let i = 0; i < n; i += 1) { for (let i = 0; i < n; i += 1) {
if ( if (bucketTouchesSignificant(this.sig, this.lngDeg[i], this.latDeg[i], halfLng, halfLat)) {
bucketTouchesSignificant(this.sig, this.lng[i] / 1e6, this.lat[i] / 1e6, halfLng, halfLat)
) {
keep[i] = 1; keep[i] = 1;
} }
} }
...@@ -324,8 +412,8 @@ export class ClusterLayer { ...@@ -324,8 +412,8 @@ export class ClusterLayer {
const under = new Uint8Array(n); const under = new Uint8Array(n);
for (let i = 0; i < n; i += 1) { for (let i = 0; i < n; i += 1) {
const lng = this.lng[i] / 1e6; const lng = this.lngDeg[i];
const lat = this.lat[i] / 1e6; const lat = this.latDeg[i];
for (let k = 0; k < shapes.length; k += 1) { for (let k = 0; k < shapes.length; k += 1) {
const s = shapes[k]; const s = shapes[k];
const dx = (lng - s.lng) / s.a; const dx = (lng - s.lng) / s.a;
...@@ -363,50 +451,38 @@ export class ClusterLayer { ...@@ -363,50 +451,38 @@ export class ClusterLayer {
return sum / this.count.length; return sum / this.count.length;
} }
private drawScheduled = false; /** 「数据变了但地图没动」的兜底重绘:合并到同一帧,并把本层标记为脏 */
private scheduleDraw() { private scheduleDraw() {
if (this.drawScheduled) return; this.surface?.schedule(() => this.draw());
this.drawScheduled = true;
// CustomLayer 每帧会自己回调 render;这里只兜底处理「数据变了但地图没动」的情况
requestAnimationFrame(() => {
this.drawScheduled = false;
if (this.layer && this.canvas) this.draw();
});
} }
private draw() { private draw() {
const canvas = this.canvas; const surface = this.surface;
const ctx = this.ctx ?? canvas?.getContext('2d') ?? null; if (!surface) return;
if (!canvas || !ctx) return; // 对齐尺寸、清空、取这一帧的投影基准;视图与本层都没动时直接返回 null。
this.ctx = ctx; // CustomLayer 空闲时也每帧回调,这个出口就是「页面停着不动也在满帧烧 CPU」的止血点。
const frame = surface.begin(this.map);
const size = this.map.getSize(); if (!frame || !this.visible || this.count.length === 0) return;
const dpr = Math.min(window.devicePixelRatio || 1, 2); const ctx = surface.context;
if (!ctx) return;
if (
canvas.width !== Math.round(size.width * dpr) || const w = surface.width;
canvas.height !== Math.round(size.height * dpr) const h = surface.height;
) { const showNumbers = this.opts.showNumbers;
canvas.width = Math.round(size.width * dpr);
canvas.height = Math.round(size.height * dpr);
canvas.style.width = `${size.width}px`;
canvas.style.height = `${size.height}px`;
}
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, size.width, size.height);
if (!this.visible || this.count.length === 0) return;
const w = size.width;
const h = size.height;
ctx.textAlign = 'center'; ctx.textAlign = 'center';
ctx.textBaseline = 'middle'; ctx.textBaseline = 'middle';
// 底衬、描边宽度与描边色整层一样,出循环设一次;
// 只有字色与字号逐格不同(深浅讲案量、字号看位数),字号见下面按档切换
ctx.lineWidth = CLUSTER_LABEL.haloWidth;
ctx.strokeStyle = CLUSTER_LABEL.halo;
// ctx.font 赋值要重新解析字体串,几百个格子各设一次就是几百次解析。
// 字号只有两档,相邻格子大多同档,所以按「档变了才设」处理。
let fontWide = -1;
for (let i = 0; i < this.count.length; i += 1) { for (let i = 0; i < this.count.length; i += 1) {
const p = this.map.lngLatToContainer([this.lng[i] / 1e6, this.lat[i] / 1e6]); const x = frame.x(this.lngDeg[i]);
const x = p.x; const y = frame.y(this.my[i]);
const y = p.y;
if (x < -CULL_PAD || y < -CULL_PAD || x > w + CULL_PAD || y > h + CULL_PAD) { if (x < -CULL_PAD || y < -CULL_PAD || x > w + CULL_PAD || y > h + CULL_PAD) {
this.sr[i] = 0; this.sr[i] = 0;
continue; continue;
...@@ -414,21 +490,15 @@ export class ClusterLayer { ...@@ -414,21 +490,15 @@ export class ClusterLayer {
this.sx[i] = x; this.sx[i] = x;
this.sy[i] = y; this.sy[i] = y;
const n = this.count[i];
// 深浅只由这个格子自己的案量决定,基准与热力层共用同一个归一化上限。
// INK_FLOOR 抬底:1 起的字最淡,但仍要能在白底衬 + 暖色热力上认出来。
const tone = INK_FLOOR + (1 - INK_FLOOR) * inkLevel(n, this.ref || this.refSelf);
// 关掉数字时一律只留一个极小的定位点,不画底衬 —— 放在这里而不是分门槛处理, // 关掉数字时一律只留一个极小的定位点,不画底衬 —— 放在这里而不是分门槛处理,
// 保证「不写数字」这一档下所有格子的长相是统一的;点的墨色仍按案量走, // 保证「不写数字」这一档下所有格子的长相是统一的;点的墨色仍按案量走,
// 于是它和写数字时说的是同一套深浅。 // 于是它和写数字时说的是同一套深浅。
if (!this.opts.showNumbers) { if (!showNumbers) {
this.sr[i] = DOT_HIT_R; this.sr[i] = DOT_HIT_R;
ctx.globalAlpha = this.keep[i] === 1 ? 1 : 0.22; ctx.globalAlpha = this.keep[i] === 1 ? 1 : 0.22;
ctx.beginPath(); ctx.beginPath();
ctx.arc(x, y, 3.5, 0, Math.PI * 2); ctx.arc(x, y, 3.5, 0, Math.PI * 2);
ctx.fillStyle = inkAt(tone); ctx.fillStyle = this.ink[i];
ctx.fill(); ctx.fill();
ctx.globalAlpha = 1; ctx.globalAlpha = 1;
continue; continue;
...@@ -441,21 +511,8 @@ export class ClusterLayer { ...@@ -441,21 +511,8 @@ export class ClusterLayer {
continue; continue;
} }
// 数字写法直接用一个 fmtCompact:以前这里自己写了一套「只折万、不加千分位」, const label = this.label[i];
// 于是同一个数盘心写 1234、清单写 1,234 —— 数值对得上、长相对不上, const r = this.plateR[i];
// 而这种小差别最容易被读成「是不是算了两遍」。
const label = fmtCompact(n);
const wide = label.length > 3;
ctx.font = wide ? CLUSTER_LABEL.fontWide : CLUSTER_LABEL.font;
let tw = this.textW.get(label);
if (tw === undefined) {
tw = ctx.measureText(label).width;
this.textW.set(label, tw);
}
// 底衬半径只由文字宽度决定,不随案件数放大 —— 这是遮挡能降下来的关键
const r = Math.max(LABEL_MIN_R, tw / 2 + 3);
this.sr[i] = r; this.sr[i] = r;
// 降噪视图下,非显著区域的数字淡出:热点之间的数字墙是最主要的干扰源 // 降噪视图下,非显著区域的数字淡出:热点之间的数字墙是最主要的干扰源
...@@ -466,14 +523,18 @@ export class ClusterLayer { ...@@ -466,14 +523,18 @@ export class ClusterLayer {
ctx.fillStyle = CLUSTER_LABEL.plate; ctx.fillStyle = CLUSTER_LABEL.plate;
ctx.fill(); ctx.fill();
// 先描白边再填深色字:热力底色是暖色时,深色字靠白描边才立得住 // 先描白边再填深色字:热力底色是暖色时,深色字靠白描边才立得住。
ctx.lineWidth = CLUSTER_LABEL.haloWidth; // 字号档只由字符串长短决定(见 recomputeLabels),底衬半径与它同源。
ctx.strokeStyle = CLUSTER_LABEL.halo; const wide = this.wide[i];
if (wide !== fontWide) {
ctx.font = wide ? CLUSTER_LABEL.fontWide : CLUSTER_LABEL.font;
fontWide = wide;
}
ctx.strokeText(label, x, y + 0.5); ctx.strokeText(label, x, y + 0.5);
// 字色取本格那一档的靛墨,不再一律用最深的那支。底衬与白描边保持不动: // 字色取本格那一档的靛墨,不再一律用最深的那支。底衬与白描边保持不动:
// 它们管的是「认不认识得出」,不是「有几起」—— 让底衬也跟着案量变薄, // 它们管的是「认不认识得出」,不是「有几档」—— 让底衬也跟着案量变薄,
// 淡字压上薄底就直接糊进热力暖色里了。 // 淡字压上薄底就直接糊进热力暖色里了。
ctx.fillStyle = inkAt(tone); ctx.fillStyle = this.ink[i];
ctx.fillText(label, x, y + 0.5); ctx.fillText(label, x, y + 0.5);
ctx.globalAlpha = 1; ctx.globalAlpha = 1;
} }
...@@ -510,8 +571,8 @@ export class ClusterLayer { ...@@ -510,8 +571,8 @@ export class ClusterLayer {
gx: this.gx[best], gx: this.gx[best],
gy: this.gy[best], gy: this.gy[best],
count: this.count[best], count: this.count[best],
lng: this.lng[best] / 1e6, lng: this.lngDeg[best],
lat: this.lat[best] / 1e6, lat: this.latDeg[best],
screenX: this.sx[best], screenX: this.sx[best],
screenY: this.sy[best], screenY: this.sy[best],
}; };
...@@ -520,7 +581,7 @@ export class ClusterLayer { ...@@ -520,7 +581,7 @@ export class ClusterLayer {
destroy() { destroy() {
this.layer?.setMap(null); this.layer?.setMap(null);
this.layer = null; this.layer = null;
this.canvas = null; this.surface?.destroy();
this.ctx = null; this.surface = null;
} }
} }
import { HEAT_GRADIENT } from './palette'; import { HEAT_GRADIENT } from './palette';
import { resolveHeatMapCtor } from './loadAmap'; import { resolveHeatMapCtor } from './loadAmap';
import { Frame, mercY } from './viewFrame';
export interface HeatLayerStyle { export interface HeatLayerStyle {
/** 热力扩散半径,像素 */ /** 热力扩散半径,像素 */
...@@ -8,6 +9,9 @@ export interface HeatLayerStyle { ...@@ -8,6 +9,9 @@ export interface HeatLayerStyle {
opacity: number; opacity: number;
} }
/** 喂给高德的一个权重点:桶中心 + 起数 */
type HeatPoint = { lng: number; lat: number; count: number };
/** /**
* 默认值经过两次调整: * 默认值经过两次调整:
* - 26 → 40:半径越大色块越连贯,低密度区也能连成片而不是散点; * - 26 → 40:半径越大色块越连贯,低密度区也能连成片而不是散点;
...@@ -80,6 +84,28 @@ export class HeatLayer { ...@@ -80,6 +84,28 @@ export class HeatLayer {
private style: HeatLayerStyle = { ...DEFAULT_HEAT_STYLE }; private style: HeatLayerStyle = { ...DEFAULT_HEAT_STYLE };
private visible = true; private visible = true;
private dataset: AMap.HeatMapDataSet | null = null; private dataset: AMap.HeatMapDataSet | null = null;
/**
* 上一次喂进去的那批桶,连同一遍换算好的点表。
*
* 只按引用判同(数组换了就重建),所以聚合一换结果、显著性掩码一重算(它是新建的表),
* 这份缓存立刻作废 —— 不存在「拿旧坐标画新数」的口子。
*/
private feed: {
lng: Int32Array;
lat: Int32Array;
count: Int32Array;
keep: Uint8Array | null;
data: HeatPoint[];
} | null = null;
/**
* 视野判定的投影基准,每次喂数据时按当前缩放与中心重设一次。
*
* 高德自己不带「这批桶哪些在屏幕里」的接口,setDataSet 收到什么就画什么,
* 所以分位数只能我们自己按视野内那批算 —— 这件事原本靠逐个调 lngLatToContainer,
* 几万个桶就是几万次内部投影加同样多个临时对象(喂数据发生在每次聚合之后,
* 拖动时也会走,这笔钱正是「拖一下卡一下」的一部分)。换成一次换算 + 每桶两次乘加。
*/
private readonly frame = new Frame();
constructor(private readonly map: AMap.Map) {} constructor(private readonly map: AMap.Map) {}
...@@ -127,23 +153,54 @@ export class HeatLayer { ...@@ -127,23 +153,54 @@ export class HeatLayer {
setDataset(lng: Int32Array, lat: Int32Array, count: Int32Array, keep?: Uint8Array | null) { setDataset(lng: Int32Array, lat: Int32Array, count: Int32Array, keep?: Uint8Array | null) {
const heat = this.ensure(); const heat = this.ensure();
const n = lng.length; const n = lng.length;
const picked: number[] = [];
for (let i = 0; i < n; i += 1) {
if (!keep || keep[i] === 1) picked.push(i);
}
const data: Array<{ lng: number; lat: number; count: number }> = new Array(picked.length);
const size = this.map.getSize(); const size = this.map.getSize();
const inView: number[] = []; const center = this.map.getCenter();
for (let k = 0; k < picked.length; k += 1) { // 一次换算代替每桶一次 lngLatToContainer:判断「这一桶在不在视野里」原先要为每个桶
const i = picked[k]; // 在高德内部新建一个 LngLat 再投影一次(两万桶就是两万次)。投影是纯几何,
// 缩放与中心定了就定死,所以取一次基准,剩下按桶做两次乘加(见 viewFrame.ts)。
this.frame.set(
this.map,
this.map.getZoom(),
center.getLng(),
center.getLat(),
size.width,
size.height,
);
// 这批桶的「同一份底数」是否还指着同一批数:数据集来自 Worker 的全量降采样,与视野无关,
// 换的只是当前视野里挑出来的那一份权重。
const prev = this.feed;
const sameSource =
prev !== null &&
prev.lng === lng &&
prev.lat === lat &&
prev.count === count &&
prev.keep === (keep ?? null);
const data: HeatPoint[] = sameSource && prev ? prev.data : [];
// 两份权重:视野内那批是分位的主口径,视野外只剩缓冲区那一圈;
// 视野内一个都不剩(极端缩放/平移动画途中)才退回整批,与原先同一规则
const inView = new Int32Array(n);
const all = new Int32Array(n);
let v = 0;
let a = 0;
for (let i = 0; i < n; i += 1) {
if (keep && keep[i] !== 1) continue;
const lng6 = lng[i] / 1e6; const lng6 = lng[i] / 1e6;
const lat6 = lat[i] / 1e6; const lat6 = lat[i] / 1e6;
data[k] = { lng: lng6, lat: lat6, count: count[i] }; const c = count[i];
const p = this.map.lngLatToContainer([lng6, lat6]); // 只有换了底数才建对象:一桶一个对象,两万桶就是两万多次分配,
if (p.x >= 0 && p.y >= 0 && p.x <= size.width && p.y <= size.height) inView.push(count[i]); // 而它每次 moveend 都要重来一遍 —— 堆压力正是「拖一阵子越来越沉」的来源之一。
// 深浅口径不受影响:max 每帧照当前视野重算,进图的还是同一批点。
if (!sameSource) data.push({ lng: lng6, lat: lat6, count: c });
all[a++] = c;
const x = this.frame.x(lng6);
if (x < 0 || x > size.width) continue;
const y = this.frame.y(mercY(lat6));
if (y >= 0 && y <= size.height) inView[v++] = c;
} }
const weights = Int32Array.from(inView.length > 0 ? inView : picked.map((i) => count[i])); this.feed = { lng, lat, count, keep: keep ?? null, data };
this.dataset = { data, max: reference(weights) }; this.dataset = { data, max: reference(v > 0 ? inView.subarray(0, v) : all.subarray(0, a)) };
heat.setDataSet(this.dataset); heat.setDataSet(this.dataset);
heat.setOptions({ visible: this.visible }); heat.setOptions({ visible: this.visible });
} }
...@@ -151,6 +208,8 @@ export class HeatLayer { ...@@ -151,6 +208,8 @@ export class HeatLayer {
/** 数据被筛选清空时要把旧数据集显式清掉,否则地图上会残留上一次的热力色块 */ /** 数据被筛选清空时要把旧数据集显式清掉,否则地图上会残留上一次的热力色块 */
clear() { clear() {
this.dataset = null; this.dataset = null;
// 缓存的那一份点表跟着作废:下次喂的是另一批桶,不能拿旧的坐标去画新的数
this.feed = null;
this.heat?.setDataSet({ data: [], max: 1 }); this.heat?.setDataSet({ data: [], max: 1 });
} }
...@@ -190,6 +249,7 @@ export class HeatLayer { ...@@ -190,6 +249,7 @@ export class HeatLayer {
this.heat?.destroy(); this.heat?.destroy();
this.heat = null; this.heat = null;
this.dataset = null; this.dataset = null;
this.feed = null;
} }
} }
......
import { fmtCompact } from '@/utils/format'; import { fmtCompact } from '@/utils/format';
import { GRID } from '../aggregate/grid';
import type { HotspotRow } from '../aggregate/types'; import type { HotspotRow } from '../aggregate/types';
import { roundRectPath } from './canvasKit'; import { roundRectPath } from './canvasKit';
import { CLUSTER_LABEL, PALETTE, labelFont } from './palette'; import { CLUSTER_LABEL, PALETTE, labelFont } from './palette';
import { LABEL_MIN_R } from './ClusterLayer'; import { LABEL_MIN_R } from './ClusterLayer';
import { import { HOTSPOT_MAX_DRAW_PX, HOTSPOT_MIN_DRAW_PX } from './hotspotGeometry';
HOTSPOT_MAX_DRAW_PX, import { CanvasSurface, mercY, textWidth, type Frame } from './viewFrame';
HOTSPOT_MIN_DRAW_PX,
M_PER_EQUATOR,
} from './hotspotGeometry';
export interface HotspotLayerOptions { export interface HotspotLayerOptions {
/** 当前选中的黑点下标(清单与地图双向联动) */ /** 当前选中的黑点下标(清单与地图双向联动) */
...@@ -27,6 +23,10 @@ const COUNT_FONT_MAX = 18; ...@@ -27,6 +23,10 @@ const COUNT_FONT_MAX = 18;
const DISC_CENTER_HIT_R = 20; const DISC_CENTER_HIT_R = 20;
/** 盘径超过这个像素后整个盘都算命中,理由见 hitAt */ /** 盘径超过这个像素后整个盘都算命中,理由见 hitAt */
const FULL_HIT_R = 48; const FULL_HIT_R = 48;
/** 视口裁剪的外扩量:盘的描边、虚线外环与排名牌都在环外一点 */
const CULL_PAD = 40;
/** 拿不到画布时的一字兜底宽度(粗体数字约 6.2px)。只影响底衬大小,不参与任何数字口径 */
const FALLBACK_CHAR_W = 6.2;
/** /**
* 排名分档配色。前三红、4~8 橙、其余品牌靛 —— 用色相而不是深浅分档, * 排名分档配色。前三红、4~8 橙、其余品牌靛 —— 用色相而不是深浅分档,
...@@ -44,6 +44,30 @@ function rgba(hex: string, alpha: number): string { ...@@ -44,6 +44,30 @@ function rgba(hex: string, alpha: number): string {
} }
/** /**
* 一个黑点在一帧里要用到的、与缩放无关的东西。
*
* 全部在 setData 那一次算好:原先每帧每行都要拼 rgba 字符串、跑一次 fmtCompact、
* 做一次投影,几十个标记摊到每帧也是几百次调用加几百个临时字符串(颜色串每次都是新对象,
* 浏览器还得重新解析)。缩放一帧只算一次,这些数在整帧里都是同一个。
*/
interface Prepared {
/** 墨卡托纬度:与缩放无关,画时只剩减法和乘法 */
my: number;
lng: number;
lat: number;
/** 盘心的案量数字,与清单那一行同一个 fmtCompact */
countLabel: string;
/** 排名牌上的序号 */
rankLabel: string;
/** 分档色,以及它在「常态 / 选中」两档下的底面与环色 */
tier: string;
fill: string;
fillActive: string;
ring: string;
ringActive: string;
}
/**
* 黑点标记层 —— 画的是「分析结论」,不是原始数据。 * 黑点标记层 —— 画的是「分析结论」,不是原始数据。
* *
* 与聚合圆圈层的分工要说清楚,否则两层看起来功能重复: * 与聚合圆圈层的分工要说清楚,否则两层看起来功能重复:
...@@ -63,14 +87,23 @@ function rgba(hex: string, alpha: number): string { ...@@ -63,14 +87,23 @@ function rgba(hex: string, alpha: number): string {
* *
* 与 ClusterLayer 同样的实现方式(CustomLayer + canvas 自绘 + 自己算命中), * 与 ClusterLayer 同样的实现方式(CustomLayer + canvas 自绘 + 自己算命中),
* 理由也一致:几十个标记不值得为它们建 AMap.Marker 覆盖物。 * 理由也一致:几十个标记不值得为它们建 AMap.Marker 覆盖物。
*
* ⚠️ 帧预算(2026-10-15 性能调优):与缩放无关的那批数(投影纬度、盘心数字、排名、
* 三档色)在喂数据时一次算完;文字宽度按「字号 + 内容」缓存,缩放一动才作废一次,
* 平移途中一次都不量字。视图与本层都没变时整帧跳过(见 viewFrame.ts)。
* 画出来的还是同一批盘、同一个数、同一种颜色。
*/ */
export class HotspotLayer { export class HotspotLayer {
private layer: AMap.CustomLayer | null = null; private layer: AMap.CustomLayer | null = null;
private canvas: HTMLCanvasElement | null = null; private surface: CanvasSurface | null = null;
private ctx: CanvasRenderingContext2D | null = null;
private opts: HotspotLayerOptions = { active: null }; private opts: HotspotLayerOptions = { active: null };
private rows: HotspotRow[] = []; private rows: HotspotRow[] = [];
private prepared: Prepared[] = [];
/** 字号 → 文字宽度。盘心字号随缩放涨,逐帧量字最费,缓存后一帧只量一次 */
private widths = new Map<string, number>();
private widthZoom = Number.NaN;
/** 屏幕缓存,供命中检测复用(点一次不必重投影) */ /** 屏幕缓存,供命中检测复用(点一次不必重投影) */
private sx = new Float32Array(0); private sx = new Float32Array(0);
private sy = new Float32Array(0); private sy = new Float32Array(0);
...@@ -81,17 +114,14 @@ export class HotspotLayer { ...@@ -81,17 +114,14 @@ export class HotspotLayer {
private ensure() { private ensure() {
if (this.layer) return; if (this.layer) return;
const canvas = document.createElement('canvas'); const surface = new CanvasSurface();
canvas.style.position = 'absolute'; this.surface = surface;
canvas.style.left = '0';
canvas.style.top = '0';
canvas.style.pointerEvents = 'none';
this.canvas = canvas;
const layer = new AMap.CustomLayer(canvas, { const layer = new AMap.CustomLayer(surface.canvas, {
// 高于聚合层(130):黑点是结论,压住数字是合理的层级关系 // 高于聚合层(130):黑点是结论,压住数字是合理的层级关系
zIndex: 140, zIndex: 140,
zooms: [3, 20], zooms: [3, 20],
// 回调仍然每帧给(拖动时盘必须跟着走),画不画由 CanvasSurface.begin 判
alwaysRender: true, alwaysRender: true,
}); });
layer.render = () => this.draw(); layer.render = () => this.draw();
...@@ -110,6 +140,21 @@ export class HotspotLayer { ...@@ -110,6 +140,21 @@ export class HotspotLayer {
this.sx = new Float32Array(rows.length); this.sx = new Float32Array(rows.length);
this.sy = new Float32Array(rows.length); this.sy = new Float32Array(rows.length);
this.sr = new Float32Array(rows.length); this.sr = new Float32Array(rows.length);
this.prepared = rows.map((r, i) => {
const tier = tierColor(i);
return {
my: mercY(r.lat),
lng: r.lng,
lat: r.lat,
countLabel: fmtCompact(r.count),
rankLabel: String(i + 1),
tier,
fill: rgba(tier, 0.09),
fillActive: rgba(tier, 0.18),
ring: rgba(tier, 0.85),
ringActive: rgba(tier, 1),
};
});
this.scheduleDraw(); this.scheduleDraw();
} }
...@@ -119,74 +164,95 @@ export class HotspotLayer { ...@@ -119,74 +164,95 @@ export class HotspotLayer {
if (!v) return; if (!v) return;
this.ensure(); this.ensure();
} }
if (v) this.layer?.show(); if (v) {
else this.layer?.hide(); this.layer?.show();
this.surface?.invalidate();
} else {
this.layer?.hide();
// 黑点层是「偶尔出现」的层:收起期间不必占着一张全屏画布(DPR 2 下三十来兆)
this.surface?.release();
}
} }
private scheduled = false; /** 「数据变了但地图没动」的兜底重绘:合并到同一帧,并把本层标记为脏 */
private scheduleDraw() { private scheduleDraw() {
if (this.scheduled) return; this.surface?.schedule(() => this.draw());
this.scheduled = true;
requestAnimationFrame(() => {
this.scheduled = false;
if (this.layer && this.canvas) this.draw();
});
} }
private draw() { /**
const canvas = this.canvas; * 量一段落在盘上的文字(盘心案量、排名牌序号)。
const ctx = this.ctx ?? canvas?.getContext('2d') ?? null; *
if (!canvas || !ctx) return; * 按「字号|内容」缓存,只在缩放变化的那一帧清空 —— 平移途中字号一个都不变,
this.ctx = ctx; * 几十个标记如果每帧各量两遍,量字本身比画盘还贵。
* 量不到画布时(无 canvas 的环境)按字数估,只影响底衬与牌子大小,不参与任何数字口径。
*/
private measure(frame: Frame, font: string, label: string): number {
if (frame.zoom !== this.widthZoom) {
this.widthZoom = frame.zoom;
this.widths.clear();
}
const key = `${font}|${label}`;
let tw = this.widths.get(key);
if (tw === undefined) {
tw = textWidth(font, label) ?? label.length * FALLBACK_CHAR_W;
this.widths.set(key, tw);
}
return tw;
}
const size = this.map.getSize(); /** 盘心案量的底衬半径:与聚合数字同一套算法(字号 + 文字宽度) */
const dpr = Math.min(window.devicePixelRatio || 1, 2); private plateRadius(frame: Frame, fontPx: number, label: string): number {
if ( return Math.max(LABEL_MIN_R, this.measure(frame, labelFont(fontPx), label) / 2 + 3);
canvas.width !== Math.round(size.width * dpr) ||
canvas.height !== Math.round(size.height * dpr)
) {
canvas.width = Math.round(size.width * dpr);
canvas.height = Math.round(size.height * dpr);
canvas.style.width = `${size.width}px`;
canvas.style.height = `${size.height}px`;
} }
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, size.width, size.height);
if (!this.visible || this.rows.length === 0) return;
const zoom = this.map.getZoom(); private draw() {
const pxPerDeg = (GRID.tileSize * Math.pow(2, zoom)) / 360; const surface = this.surface;
const pxPerMeter = pxPerDeg / (M_PER_EQUATOR * Math.cos((22.5 * Math.PI) / 180)); if (!surface) return;
const frame = surface.begin(this.map);
// 视图与本层都没变 → 这一帧不必重画(CustomLayer 空闲时也每帧回调)
if (!frame || !this.visible || this.prepared.length === 0) return;
const ctx = surface.context;
if (!ctx) return;
const w = surface.width;
const h = surface.height;
// 米 → 像素每帧一次(原来是每行一次 cos 与乘法)
const pxPerMeter = frame.pxPerMeter;
const w = size.width; ctx.textAlign = 'center';
const h = size.height; ctx.textBaseline = 'middle';
for (let i = 0; i < this.rows.length; i += 1) { for (let i = 0; i < this.prepared.length; i += 1) {
const r = this.rows[i]; const p = this.prepared[i];
const p = this.map.lngLatToContainer([r.lng, r.lat]); const x = frame.x(p.lng);
const x = p.x; const y = frame.y(p.my);
const y = p.y;
const rad = Math.min( const rad = Math.min(
HOTSPOT_MAX_DRAW_PX, HOTSPOT_MAX_DRAW_PX,
Math.max(HOTSPOT_MIN_DRAW_PX, r.radiusM * pxPerMeter), Math.max(HOTSPOT_MIN_DRAW_PX, this.rows[i].radiusM * pxPerMeter),
); );
this.sx[i] = x; this.sx[i] = x;
this.sy[i] = y; this.sy[i] = y;
this.sr[i] = rad; this.sr[i] = rad;
if (x < -rad - 24 || y < -rad - 24 || x > w + rad + 24 || y > h + rad + 24) continue; if (
x < -rad - CULL_PAD ||
y < -rad - CULL_PAD ||
x > w + rad + CULL_PAD ||
y > h + rad + CULL_PAD
) {
continue;
}
const color = tierColor(i);
const active = this.opts.active === i; const active = this.opts.active === i;
// 范围盘 // 范围盘
ctx.beginPath(); ctx.beginPath();
ctx.arc(x, y, rad, 0, Math.PI * 2); ctx.arc(x, y, rad, 0, Math.PI * 2);
ctx.fillStyle = rgba(color, active ? 0.18 : 0.09); ctx.fillStyle = active ? p.fillActive : p.fill;
ctx.fill(); ctx.fill();
// 环 // 环
ctx.lineWidth = active ? 2.6 : 1.6; ctx.lineWidth = active ? 2.6 : 1.6;
ctx.strokeStyle = rgba(color, active ? 1 : 0.85); ctx.strokeStyle = active ? p.ringActive : p.ring;
ctx.stroke(); ctx.stroke();
// 选中时补一圈虚线外环:只加粗本身的话在热力暖色上仍然不明显 // 选中时补一圈虚线外环:只加粗本身的话在热力暖色上仍然不明显
...@@ -205,21 +271,18 @@ export class HotspotLayer { ...@@ -205,21 +271,18 @@ export class HotspotLayer {
// 用户才不会问「这两个数哪个算数」,也不会怀疑清单和地图各算了一遍。 // 用户才不会问「这两个数哪个算数」,也不会怀疑清单和地图各算了一遍。
// 字号随盘放大但只放大一档(11→18px):盘本身才是范围信息,字太大反而把盘撑满、 // 字号随盘放大但只放大一档(11→18px):盘本身才是范围信息,字太大反而把盘撑满、
// 看不清边界在哪儿。 // 看不清边界在哪儿。
const countLabel = fmtCompact(r.count);
const fontPx = Math.round(Math.min(COUNT_FONT_MAX, Math.max(COUNT_FONT_MIN, rad * 0.16))); const fontPx = Math.round(Math.min(COUNT_FONT_MAX, Math.max(COUNT_FONT_MIN, rad * 0.16)));
ctx.font = labelFont(fontPx); ctx.font = labelFont(fontPx);
ctx.textAlign = 'center'; const plateR = this.plateRadius(frame, fontPx, p.countLabel);
ctx.textBaseline = 'middle';
const plateR = Math.max(LABEL_MIN_R, ctx.measureText(countLabel).width / 2 + 3);
ctx.beginPath(); ctx.beginPath();
ctx.arc(x, y, plateR, 0, Math.PI * 2); ctx.arc(x, y, plateR, 0, Math.PI * 2);
ctx.fillStyle = CLUSTER_LABEL.plate; ctx.fillStyle = CLUSTER_LABEL.plate;
ctx.fill(); ctx.fill();
ctx.lineWidth = CLUSTER_LABEL.haloWidth; ctx.lineWidth = CLUSTER_LABEL.haloWidth;
ctx.strokeStyle = CLUSTER_LABEL.halo; ctx.strokeStyle = CLUSTER_LABEL.halo;
ctx.strokeText(countLabel, x, y + 0.5); ctx.strokeText(p.countLabel, x, y + 0.5);
ctx.fillStyle = CLUSTER_LABEL.color; ctx.fillStyle = CLUSTER_LABEL.color;
ctx.fillText(countLabel, x, y + 0.5); ctx.fillText(p.countLabel, x, y + 0.5);
// 排名牌放在右上 45°,并且落在环外一点点。 // 排名牌放在右上 45°,并且落在环外一点点。
// //
...@@ -230,9 +293,8 @@ export class HotspotLayer { ...@@ -230,9 +293,8 @@ export class HotspotLayer {
// 叠 2.5px 描边,描边比笔画还宽,字形边缘全被糊掉,看着就是一团发光的光斑。 // 叠 2.5px 描边,描边比笔画还宽,字形边缘全被糊掉,看着就是一团发光的光斑。
// 牌面本身是不透明的分档色,白字靠底色就有足够对比,所以描边整个去掉, // 牌面本身是不透明的分档色,白字靠底色就有足够对比,所以描边整个去掉,
// 只留一层很淡的投影把牌子从热力暖色上抬起来 —— 阴影给层次,不给虚边。 // 只留一层很淡的投影把牌子从热力暖色上抬起来 —— 阴影给层次,不给虚边。
const label = String(i + 1);
ctx.font = CHIP_FONT; ctx.font = CHIP_FONT;
const cw = Math.ceil(ctx.measureText(label).width) + 10; const cw = Math.ceil(this.measure(frame, CHIP_FONT, p.rankLabel)) + 10;
const ch = 15; const ch = 15;
const off = (rad + 11) * 0.7071; const off = (rad + 11) * 0.7071;
const cx = x + off - cw / 2; const cx = x + off - cw / 2;
...@@ -241,7 +303,7 @@ export class HotspotLayer { ...@@ -241,7 +303,7 @@ export class HotspotLayer {
ctx.shadowColor = 'rgba(16,24,40,.32)'; ctx.shadowColor = 'rgba(16,24,40,.32)';
ctx.shadowBlur = 4; ctx.shadowBlur = 4;
ctx.shadowOffsetY = 1; ctx.shadowOffsetY = 1;
ctx.fillStyle = color; ctx.fillStyle = p.tier;
ctx.fill(); ctx.fill();
ctx.shadowColor = 'transparent'; ctx.shadowColor = 'transparent';
ctx.shadowBlur = 0; ctx.shadowBlur = 0;
...@@ -250,10 +312,8 @@ export class HotspotLayer { ...@@ -250,10 +312,8 @@ export class HotspotLayer {
ctx.strokeStyle = 'rgba(255,255,255,.9)'; ctx.strokeStyle = 'rgba(255,255,255,.9)';
ctx.stroke(); ctx.stroke();
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = '#ffffff'; ctx.fillStyle = '#ffffff';
ctx.fillText(label, cx + cw / 2, cy + ch / 2 + 0.5); ctx.fillText(p.rankLabel, cx + cw / 2, cy + ch / 2 + 0.5);
} }
} }
...@@ -278,9 +338,7 @@ export class HotspotLayer { ...@@ -278,9 +338,7 @@ export class HotspotLayer {
// 指的都是这个黑点,而盘里的聚合数字本来就让位给黑点自己的案量了 // 指的都是这个黑点,而盘里的聚合数字本来就让位给黑点自己的案量了
// (见 ClusterLayer.setHotspotDiscs),不该留一个「看得见却点不动」的空洞。 // (见 ClusterLayer.setHotspotDiscs),不该留一个「看得见却点不动」的空洞。
const inDisc = const inDisc =
r >= FULL_HIT_R || r >= FULL_HIT_R || d2 >= (r - 12) * (r - 12) || d2 < DISC_CENTER_HIT_R * DISC_CENTER_HIT_R;
d2 >= (r - 12) * (r - 12) ||
d2 < DISC_CENTER_HIT_R * DISC_CENTER_HIT_R;
if (!inDisc) continue; if (!inDisc) continue;
if (d2 < bestDist) { if (d2 < bestDist) {
bestDist = d2; bestDist = d2;
...@@ -293,7 +351,7 @@ export class HotspotLayer { ...@@ -293,7 +351,7 @@ export class HotspotLayer {
destroy() { destroy() {
this.layer?.setMap(null); this.layer?.setMap(null);
this.layer = null; this.layer = null;
this.canvas = null; this.surface?.destroy();
this.ctx = null; this.surface = null;
} }
} }
import { fmtCompact } from '@/utils/format'; import { fmtCompact } from '@/utils/format';
import { GRID } from '../aggregate/grid';
import type { SpotlightCell } from '../aggregate/types'; import type { SpotlightCell } from '../aggregate/types';
import { pointInPolygon, type LngLat, type ShapePolygon } from '../geo/districtShapes'; import { pointInPolygon, type LngLat, type ShapePolygon } from '../geo/districtShapes';
import { ellipsize, roundRectPath } from './canvasKit'; import { ellipsizeBy, roundRectPath } from './canvasKit';
import { M_PER_EQUATOR } from './hotspotGeometry';
import { import {
MAP_LABEL_FONT, MAP_LABEL_FONT,
PALETTE, PALETTE,
...@@ -13,7 +11,8 @@ import { ...@@ -13,7 +11,8 @@ import {
paletteHexToRgb, paletteHexToRgb,
rgbCss, rgbCss,
} from './palette'; } from './palette';
import { corridorOf, hottestCell, type CorridorPath } from './spotlightGeometry'; import { corridorOf, hottestCell, type CorridorNode } from './spotlightGeometry';
import { CanvasSurface, mercY, textWidth, type Frame } from './viewFrame';
/** /**
* 聚焦展示的形状种类,与 store 的 SpotlightKind 同一张名单。 * 聚焦展示的形状种类,与 store 的 SpotlightKind 同一张名单。
...@@ -120,31 +119,80 @@ const CHIP_GAP = 6; ...@@ -120,31 +119,80 @@ const CHIP_GAP = 6;
const CHIP_MAX_TEXT_W = 230; const CHIP_MAX_TEXT_W = 230;
/** 命中判定给牌子补的余量:点名字和点色块是同一个意图 */ /** 命中判定给牌子补的余量:点名字和点色块是同一个意图 */
const HIT_PAD = 3; const HIT_PAD = 3;
/** 量不到画布时的一字兜底宽度。只影响牌子长短,不参与任何数字口径 */
const FALLBACK_CHAR_W = 10;
/** 一条环的画法位置:抽稀后的经纬度 + 每点的墨卡托纬度(与缩放无关,算一次) */
interface DrawRing {
pts: LngLat[];
my: Float64Array;
}
/** 一个多边形(第一条环是外沿,后面是洞) */
interface DrawPoly {
rings: DrawRing[];
}
/** 一条走廊:地理节点 + 每节点墨卡托纬度 + 每格与每段的深浅色 */
interface PreparedPath {
nodes: CorridorNode[];
my: Float64Array;
/** 这一格自己的深浅(单格走廊画圆点时用) */
nodeFill: string[];
/** 第 k 段取相邻两格的均值深浅 —— 逐段涂色才说得出「哪一段挤」 */
segFill: string[];
}
/** 牌子在一屏上占多大。只由文字与画布宽度决定,跟缩放无关 */
interface ChipMetrics {
text: string;
textW: number;
sub: string;
subW: number;
w: number;
/** 这套尺寸是按多宽的画布算的;画布没变就不必重算(重算要逐字量一遍) */
fittedW: number;
}
interface PreparedUnit { interface PreparedUnit {
label: string; label: string;
count: number; count: number;
sub: string | undefined; sub: string | undefined;
/** 档位身份色:牌子上的那颗点和描边 */ /** 档位身份色:牌子上的那颗点 */
color: string; color: string;
colorRgb: [number, number, number]; colorRgb: [number, number, number];
cells: SpotlightCell[]; cells: SpotlightCell[];
/** 这一档自己最多那一格的起数:深浅只在档内归一 */ /** 每格的墨卡托纬度(与 cells 同长):喂数据时算一次,每帧只剩减法与乘法 */
unitMax: number; cellMy: Float64Array;
/** 每格深浅的那支颜色:只由「本格起数 ÷ 档内最深」决定,与缩放无关 */
cellFill: string[];
/** 牌子锚点:起数最多那一格,也就是这一档最好认的地方;区界用边界自己的锚点 */ /** 牌子锚点:起数最多那一格,也就是这一档最好认的地方;区界用边界自己的锚点 */
anchor: SpotlightCell | null; anchor: { lng: number; my: number } | null;
/** 道路那一档的走廊(在地理坐标里算一次,缩放时每帧只投影) */ /** 道路那一档的走廊(在地理坐标里算一次,缩放时每帧只投影) */
paths: CorridorPath[]; paths: PreparedPath[];
/** 走廊深浅的分母:档内最挤那一段的起数 */
pathMax: number;
/** 区界那一档:原始边界几何,命中判定用它(完整的环,不抽稀) */ /** 区界那一档:原始边界几何,命中判定用它(完整的环,不抽稀) */
polys: ShapePolygon[]; polys: ShapePolygon[];
/** 区界那一档:面积(平方公里),深浅的分母 */ /** 区界那一档:面积(平方公里),深浅的分母 */
areaKm2: number; areaKm2: number;
/** 区界那一档:抽稀后的环,按多边形分组(第一条是外沿,后面是洞),只用于画法 */ /** 区界那一档:抽稀后的环,按多边形分组,只用于画法 */
drawPolys: LngLat[][][]; drawPolys: DrawPoly[];
/** 区界那一档的深浅:每平方公里起数 ÷ 这一屏最深那一块 */ /** 区界那一档的深浅:每平方公里起数 ÷ 这一屏最深那一块 */
fillU: number; fillU: number;
/**
* 这一档落笔要用的那几支颜色,喂数据时一次拼好(常态 / 选中各一套)。
*
* 原先每帧为每块区界现插值、现拼 rgba 字符串 —— 色阶插值本身不贵,
* 贵的是每帧几百个临时字符串(拖动时全在帧预算里,也全在垃圾回收的账单上)。
*/
fill: string;
fillActive: string;
ring: string;
ringActive: string;
glow: string;
/** 牌子描边:档位色,与形状填色那条色阶不是一回事,所以单独两支 */
chipStroke: string;
chipStrokeActive: string;
chip: ChipMetrics;
} }
/** /**
...@@ -162,37 +210,48 @@ interface PreparedUnit { ...@@ -162,37 +210,48 @@ interface PreparedUnit {
* 那么「高亮这条街」能诚实做到的只有照落点描出它们挤在哪儿;界面上那句说明 * 那么「高亮这条街」能诚实做到的只有照落点描出它们挤在哪儿;界面上那句说明
* (见 MapStage 的聚焦图例)就是把这一件事讲清,不含糊成边界。 * (见 MapStage 的聚焦图例)就是把这一件事讲清,不含糊成边界。
* 区界是唯一例外 —— 它有真的行政区边界,所以那一片涂的就是那个区本身。 * 区界是唯一例外 —— 它有真的行政区边界,所以那一片涂的就是那个区本身。
*
* ⚠️ 帧预算(2026-10-15 性能调优):这一层拖动时每帧要跑两千多个边界顶点、几百个格子
* 与几十段走廊。原先这些全是「每帧现算」—— 每个位置一次投影调用(每次都在高德内部新建
* 一个 LngLat 对象)、每格一次色阶插值加一次 rgba 拼串、每块牌子一次逐字量字。
* 现在与缩放无关的部分在喂数据时一次算完(每点的墨卡托纬度、深浅颜色、牌子文字与尺寸),
* 每帧只剩「两次乘加求位置 + 落笔」,视图与本层都没变时整帧跳过(见 viewFrame.ts)。
* 屏上还是同一片形状、同一个深浅、同一块牌子。
*/ */
export class SpotlightLayer { export class SpotlightLayer {
private layer: AMap.CustomLayer | null = null; private layer: AMap.CustomLayer | null = null;
private canvas: HTMLCanvasElement | null = null; private surface: CanvasSurface | null = null;
private ctx: CanvasRenderingContext2D | null = null;
private opts: SpotlightLayerOptions = { active: null }; private opts: SpotlightLayerOptions = { active: null };
private units: PreparedUnit[] = []; private units: PreparedUnit[] = [];
private variant: SpotlightVariant = 'streets'; private variant: SpotlightVariant = 'streets';
private cellM = 100; private cellM = 100;
/** 方格边长与走廊粗细只随缩放变,缩放没动的帧不必重算 */
private cellPx = CELL_MIN_PX;
private linePx = CORRIDOR_MIN_PX;
private metricZoom = Number.NaN;
private visible = false; private visible = false;
/** 命中判定用的屏幕范围,由 draw 每帧维护(与聚合层、黑点层同一套做法) */ /** 命中判定用的屏幕范围,由 draw 每帧维护(与聚合层、黑点层同一套做法) */
private boxes: Array<{ x0: number; y0: number; x1: number; y1: number }> = []; private boxes: Array<{ x0: number; y0: number; x1: number; y1: number }> = [];
/** 走廊位置的草稿缓冲:每帧每条走廊都要一份屏幕坐标,逐帧新建数组就是在拖动里造垃圾 */
private scratchX = new Float64Array(64);
private scratchY = new Float64Array(64);
constructor(private readonly map: AMap.Map) {} constructor(private readonly map: AMap.Map) {}
private ensure() { private ensure() {
if (this.layer) return; if (this.layer) return;
const canvas = document.createElement('canvas'); const surface = new CanvasSurface();
canvas.style.position = 'absolute'; this.surface = surface;
canvas.style.left = '0';
canvas.style.top = '0'; const layer = new AMap.CustomLayer(surface.canvas, {
canvas.style.pointerEvents = 'none';
this.canvas = canvas;
const layer = new AMap.CustomLayer(canvas, {
// 在黑点盘(140)之上、定位标记(150)之下:聚焦期间黑点盘本来就收起, // 在黑点盘(140)之上、定位标记(150)之下:聚焦期间黑点盘本来就收起,
// 而从清单里定位某一起案件时,那枚图钉要压得住这片形状 // 而从清单里定位某一起案件时,那枚图钉要压得住这片形状
zIndex: 145, zIndex: 145,
zooms: [3, 20], zooms: [3, 20],
// 回调仍然每帧给(聚焦时拖动要跟着走),画不画由 CanvasSurface.begin 判
alwaysRender: true, alwaysRender: true,
}); });
layer.render = () => this.draw(); layer.render = () => this.draw();
...@@ -233,18 +292,19 @@ export class SpotlightLayer { ...@@ -233,18 +292,19 @@ export class SpotlightLayer {
if (!v) return; if (!v) return;
this.ensure(); this.ensure();
} }
if (v) this.layer?.show(); if (v) {
else this.layer?.hide(); this.layer?.show();
this.surface?.invalidate();
} else {
this.layer?.hide();
// 这一层只在聚焦期间出现,退出聚焦就把整块全屏画布交回去(DPR 2 下三十来兆)
this.surface?.release();
}
} }
private scheduled = false; /** 「数据变了但地图没动」的兜底重绘:合并到同一帧,并把本层标记为脏 */
private scheduleDraw() { private scheduleDraw() {
if (this.scheduled) return; this.surface?.schedule(() => this.draw());
this.scheduled = true;
requestAnimationFrame(() => {
this.scheduled = false;
if (this.layer && this.canvas) this.draw();
});
} }
/** /**
...@@ -253,6 +313,9 @@ export class SpotlightLayer { ...@@ -253,6 +313,9 @@ export class SpotlightLayer {
* 走廊必须在地理坐标里算(corridorOf 用的是米制局部平面):按屏幕像素算的话, * 走廊必须在地理坐标里算(corridorOf 用的是米制局部平面):按屏幕像素算的话,
* 缩放一次走向就变一次,同一条路在两个级别上画出两种形状 —— 那就不是在说走向。 * 缩放一次走向就变一次,同一条路在两个级别上画出两种形状 —— 那就不是在说走向。
* 区界同理:抽稀在地理坐标里按环长做,画法与命中用的还是同一份边界,只是笔划少绕几个弯。 * 区界同理:抽稀在地理坐标里按环长做,画法与命中用的还是同一份边界,只是笔划少绕几个弯。
*
* 顺带把「与缩放无关的画法」一并算完:每个位置的墨卡托纬度、每一格与每一段的深浅色。
* 牌子上的字要等画布宽度知道才能截断,那一步在 fitChip 里按宽度缓存。
*/ */
private prepare( private prepare(
u: SpotlightUnitPaint, u: SpotlightUnitPaint,
...@@ -262,13 +325,40 @@ export class SpotlightLayer { ...@@ -262,13 +325,40 @@ export class SpotlightLayer {
): PreparedUnit { ): PreparedUnit {
let unitMax = 0; let unitMax = 0;
for (const c of u.cells) if (c.n > unitMax) unitMax = c.n; for (const c of u.cells) if (c.n > unitMax) unitMax = c.n;
// 归一到 1 而不是 0:全是 1 起的一档若按 0 归一,整片会涂成色阶左端之外
const cap = Math.max(unitMax, 1);
const cellMy = new Float64Array(u.cells.length);
const cellFill: string[] = new Array(u.cells.length);
for (let k = 0; k < u.cells.length; k += 1) {
const c = u.cells[k];
cellMy[k] = mercY(c.lat);
cellFill[k] = densityCellFill(c.n / cap);
}
const paths = variant === 'roads' ? corridorOf(u.cells, cellM) : []; let pathCap = 1;
let pathMax = 0; const corridors = variant === 'roads' ? corridorOf(u.cells, cellM) : [];
for (const p of paths) for (const nd of p.nodes) if (nd.n > pathMax) pathMax = nd.n; for (const p of corridors) for (const nd of p.nodes) if (nd.n > pathCap) pathCap = nd.n;
// 分母取档内最挤那一段(不是全市最挤),与街道那一档同一把尺:只看自己内部。
// 逐段颜色在这里定好:段深浅只由两格起数与档内分母决定,缩放一帧都不该重算它。
const paths: PreparedPath[] = corridors.map((p) => {
const segFill: string[] = [];
for (let k = 1; k < p.nodes.length; k += 1) {
segFill.push(densityCellFill((p.nodes[k - 1].n + p.nodes[k].n) / 2 / pathCap));
}
return {
nodes: p.nodes,
my: Float64Array.from(p.nodes, (nd) => mercY(nd.lat)),
nodeFill: p.nodes.map((nd) => densityCellFill(nd.n / pathCap)),
segFill,
};
});
const polys = variant === 'districts' ? (u.polys ?? []) : []; const polys = variant === 'districts' ? (u.polys ?? []) : [];
const color = RANK_COLORS[i % RANK_COLORS.length]; const color = RANK_COLORS[i % RANK_COLORS.length];
const pin = u.pin;
const hot = pin ? null : hottestCell(u.cells);
return { return {
label: u.label, label: u.label,
count: u.count, count: u.count,
...@@ -276,17 +366,33 @@ export class SpotlightLayer { ...@@ -276,17 +366,33 @@ export class SpotlightLayer {
color, color,
colorRgb: paletteHexToRgb(color), colorRgb: paletteHexToRgb(color),
cells: u.cells, cells: u.cells,
// 归一到 1 而不是 0:全是 1 起的一档若按 0 归一,整片会涂成色阶左端之外 cellMy,
unitMax: Math.max(unitMax, 1), cellFill,
// 区界那块牌子要钉在区域自己身上(这一档可能一个落点都不在屏上,但区界照样要涂出来) // 区界那块牌子要钉在区域自己身上(这一档可能一个落点都不在屏上,但区界照样要涂出来)
anchor: u.pin ? { lng: u.pin.lng, lat: u.pin.lat, n: u.count } : hottestCell(u.cells), anchor: pin
? { lng: pin.lng, my: mercY(pin.lat) }
: hot
? { lng: hot.lng, my: mercY(hot.lat) }
: null,
paths, paths,
pathMax: Math.max(pathMax, 1),
polys, polys,
areaKm2: Math.max(u.areaKm2 ?? 0, 0.01), areaKm2: Math.max(u.areaKm2 ?? 0, 0.01),
drawPolys: polys.map((p) => p.rings.map(decimateRing)), drawPolys: polys.map((p) => ({
// 分母由 setData 在这一屏全部备好后统一给(榜首归一),这里先留 0 rings: p.rings.map((ring) => {
const pts = decimateRing(ring);
return { pts, my: Float64Array.from(pts, (pt) => mercY(pt[1])) };
}),
})),
// 深浅的分母与由它派生的那几支颜色在 normalizeFills 里统一给(榜首归一),这里先留空
fillU: 0, fillU: 0,
fill: '',
fillActive: '',
ring: '',
ringActive: '',
glow: '',
chipStroke: '',
chipStrokeActive: '',
chip: { text: '', textW: 0, sub: '', subW: 0, w: 0, fittedW: -1 },
}; };
} }
...@@ -298,48 +404,60 @@ export class SpotlightLayer { ...@@ -298,48 +404,60 @@ export class SpotlightLayer {
* 每个区各按自己最深那一格涂,就变成「六个区都是最深的那一档」,深浅不再传递任何信息。 * 每个区各按自己最深那一格涂,就变成「六个区都是最深的那一档」,深浅不再传递任何信息。
*/ */
private normalizeFills(variant: SpotlightVariant) { private normalizeFills(variant: SpotlightVariant) {
if (variant !== 'districts') return;
let maxDensity = 0; let maxDensity = 0;
if (variant === 'districts') {
for (const u of this.units) { for (const u of this.units) {
const density = u.count / u.areaKm2; const density = u.count / u.areaKm2;
if (density > maxDensity) maxDensity = density; if (density > maxDensity) maxDensity = density;
} }
}
for (const u of this.units) { for (const u of this.units) {
u.fillU = maxDensity > 0 ? u.count / u.areaKm2 / maxDensity : 1; u.fillU = variant === 'districts' && maxDensity > 0 ? u.count / u.areaKm2 / maxDensity : 1;
// 区界走密度色阶,其余三档的形状用档位色:一处就是一处,没有「比邻格浓多少」可读,
// 色阶在那里反而会把「一处出过案」说成「这一片很挤」
const rgb = variant === 'districts' ? gradientAt(u.fillU) : u.colorRgb;
u.fill =
variant === 'districts' ? rgbCss(rgb, districtFillAlpha(u.fillU)) : rgbCss(rgb, 0.15);
u.fillActive =
variant === 'districts'
? // 选中时比常态再浓 .08:一整片淡色区界里,只加粗边界分不出点了哪一块
rgbCss(rgb, Math.min(0.92, districtFillAlpha(u.fillU) + 0.08))
: rgbCss(rgb, 0.26);
u.ring = rgbCss(rgb, variant === 'districts' ? 1 : 0.85);
u.ringActive = rgbCss(rgb, 1);
u.glow =
variant === 'districts'
? rgbCss(rgb, 0.22)
: rgbCss(paletteHexToRgb(PALETTE.primaryDeep), 0.5);
u.chipStroke = rgbCss(u.colorRgb, 0.7);
u.chipStrokeActive = rgbCss(u.colorRgb, 1);
} }
} }
private draw() { private draw() {
const canvas = this.canvas; const surface = this.surface;
const ctx = this.ctx ?? canvas?.getContext('2d') ?? null; if (!surface) return;
if (!canvas || !ctx) return; const frame = surface.begin(this.map);
this.ctx = ctx; // 视图与本层都没变 → 这一帧不必重画(CustomLayer 空闲时也每帧回调)
if (!frame || !this.visible || this.units.length === 0) return;
const size = this.map.getSize(); const ctx = surface.context;
const dpr = Math.min(window.devicePixelRatio || 1, 2); if (!ctx) return;
if (
canvas.width !== Math.round(size.width * dpr) || const w = surface.width;
canvas.height !== Math.round(size.height * dpr) const h = surface.height;
) {
canvas.width = Math.round(size.width * dpr);
canvas.height = Math.round(size.height * dpr);
canvas.style.width = `${size.width}px`;
canvas.style.height = `${size.height}px`;
}
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, size.width, size.height);
if (!this.visible || this.units.length === 0) return;
const zoom = this.map.getZoom();
const pxPerDeg = (GRID.tileSize * Math.pow(2, zoom)) / 360;
// 米↔像素按参考纬度换算,与黑点层、热力的口径一致(见 MapStage 的 LAT_CENTER)
const pxPerMeter = pxPerDeg / (M_PER_EQUATOR * Math.cos((22.5 * Math.PI) / 180));
const isPlace = this.variant === 'places'; const isPlace = this.variant === 'places';
const side = clamp( if (frame.zoom !== this.metricZoom) {
this.cellM * pxPerMeter, this.metricZoom = frame.zoom;
this.cellPx = clamp(
this.cellM * frame.pxPerMeter,
isPlace ? PLACE_MIN_PX : CELL_MIN_PX, isPlace ? PLACE_MIN_PX : CELL_MIN_PX,
isPlace ? PLACE_MAX_PX : CELL_MAX_PX, isPlace ? PLACE_MAX_PX : CELL_MAX_PX,
); );
// 粗细跟着缩放走,但夹进看得见的那一段:全市视图下 100 米只有 1 像素,
// 那一条线会退化成 hairline,读不出「这是一条路」
this.linePx = clamp(this.cellM * frame.pxPerMeter, CORRIDOR_MIN_PX, CORRIDOR_MAX_PX);
}
const side = this.cellPx;
ctx.lineJoin = 'round'; ctx.lineJoin = 'round';
ctx.lineCap = 'round'; ctx.lineCap = 'round';
...@@ -352,44 +470,40 @@ export class SpotlightLayer { ...@@ -352,44 +470,40 @@ export class SpotlightLayer {
let x1 = -Infinity; let x1 = -Infinity;
let y1 = -Infinity; let y1 = -Infinity;
const add = (left: number, top: number, w: number, h: number) => {
x0 = Math.min(x0, left);
y0 = Math.min(y0, top);
x1 = Math.max(x1, left + w);
y1 = Math.max(y1, top + h);
};
if (this.variant === 'districts') { if (this.variant === 'districts') {
const box = this.drawDistrict(ctx, unit, size.width, size.height, active); const box = this.drawDistrict(ctx, unit, frame, w, h, active);
x0 = box.x0; x0 = box.x0;
y0 = box.y0; y0 = box.y0;
x1 = box.x1; x1 = box.x1;
y1 = box.y1; y1 = box.y1;
} else if (this.variant === 'roads') { } else if (this.variant === 'roads') {
const box = this.drawCorridors(ctx, unit, pxPerMeter, active); const box = this.drawCorridors(ctx, unit, frame, active);
x0 = box.x0; x0 = box.x0;
y0 = box.y0; y0 = box.y0;
x1 = box.x1; x1 = box.x1;
y1 = box.y1; y1 = box.y1;
} else { } else {
const half = side / 2; const half = side / 2;
for (const c of unit.cells) { for (let k = 0; k < unit.cells.length; k += 1) {
const p = this.map.lngLatToContainer([c.lng, c.lat]); const c = unit.cells[k];
const left = p.x - half; const px = frame.x(c.lng);
const top = p.y - half; const py = frame.y(unit.cellMy[k]);
const left = px - half;
const top = py - half;
// 屏幕外的格子不落笔,但范围照旧并进来:命中表要说的是这一档真正占的地方, // 屏幕外的格子不落笔,但范围照旧并进来:命中表要说的是这一档真正占的地方,
// 少算的话「把形状拖到屏幕边上时点不动」会被读成按钮坏了 // 少算的话「把形状拖到屏幕边上时点不动」会被读成按钮坏了
add(left, top, side, side); if (left < x0) x0 = left;
if (p.x < -side || p.y < -side || p.x > size.width + side || p.y > size.height + side) { if (top < y0) y0 = top;
continue; if (left + side > x1) x1 = left + side;
} if (top + side > y1) y1 = top + side;
if (px < -side || py < -side || px > w + side || py > h + side) continue;
if (isPlace) { if (isPlace) {
this.drawPlaceSquare(ctx, unit, left, top, side, active); this.drawPlaceSquare(ctx, unit, left, top, side, active);
} else { } else {
// 深浅按「这一档自己最多那一格」归一,不按全市、也不按这一屏: // 深浅按「这一档自己最多那一格」归一,不按全市、也不按这一屏:
// 一条街道内部哪一段最挤才是这张图要读的,全局归一会把案件少的街道整片压成冷端, // 一条街道内部哪一段最挤才是这张图要读的,全局归一会把案件少的街道整片压成冷端,
// 看着像没有时间特征也没有空间特征,而它只是量小(同一道理见抽屉那张时段矩阵) // 看着像没有时间特征也没有空间特征,而它只是量小(同一道理见抽屉那张时段矩阵)
ctx.fillStyle = densityCellFill(c.n / unit.unitMax); ctx.fillStyle = unit.cellFill[k];
ctx.fillRect(left, top, side, side); ctx.fillRect(left, top, side, side);
// 白细线只管分格,不编码任何数:没有它相邻格子会糊成一块, // 白细线只管分格,不编码任何数:没有它相邻格子会糊成一块,
// 而这一层恰恰靠「哪几格连成一片」读形状 // 而这一层恰恰靠「哪几格连成一片」读形状
...@@ -400,22 +514,38 @@ export class SpotlightLayer { ...@@ -400,22 +514,38 @@ export class SpotlightLayer {
} }
} }
let chipBox: { x0: number; y0: number; x1: number; y1: number } | null = null; let chipLeft = 0;
let chipTop = 0;
let chipW = 0;
let chipDrawn = false;
if (unit.anchor) { if (unit.anchor) {
const a = this.map.lngLatToContainer([unit.anchor.lng, unit.anchor.lat]);
// 区界那一档的锚点在区域自己身上,牌子放在它正上方; // 区界那一档的锚点在区域自己身上,牌子放在它正上方;
// 方格与走廊那三档放在最深那一格的顶边上方,牌子才像是从那一片里长出来的 // 方格与走廊那三档放在最深那一格的顶边上方,牌子才像是从那一片里长出来的
const lift = this.variant === 'districts' ? 0 : side / 2; const lift = this.variant === 'districts' ? 0 : side / 2;
chipBox = this.drawChip(ctx, unit, a.x, a.y - lift, size.width, size.height, active); const box = this.drawChip(
ctx,
unit,
frame.x(unit.anchor.lng),
frame.y(unit.anchor.my) - lift,
w,
h,
active,
);
if (box) {
chipLeft = box.x0;
chipTop = box.y0;
chipW = box.x1 - box.x0;
chipDrawn = true;
}
} }
const box = this.boxes[i]; const box = this.boxes[i];
if (!box) continue; if (!box) continue;
if (chipBox) { if (chipDrawn) {
x0 = Math.min(x0, chipBox.x0); if (chipLeft < x0) x0 = chipLeft;
y0 = Math.min(y0, chipBox.y0); if (chipTop < y0) y0 = chipTop;
x1 = Math.max(x1, chipBox.x1); if (chipLeft + chipW > x1) x1 = chipLeft + chipW;
y1 = Math.max(y1, chipBox.y1); if (chipTop + this.chipH(unit) > y1) y1 = chipTop + this.chipH(unit);
} }
// 一格都没有(该档在这次筛选里没有落点)时留一个空范围,hitAt 会跳过它 // 一格都没有(该档在这次筛选里没有落点)时留一个空范围,hitAt 会跳过它
box.x0 = Number.isFinite(x0) ? x0 - HIT_PAD : 0; box.x0 = Number.isFinite(x0) ? x0 - HIT_PAD : 0;
...@@ -425,6 +555,11 @@ export class SpotlightLayer { ...@@ -425,6 +555,11 @@ export class SpotlightLayer {
} }
} }
/** 牌子高度:两行还是单行只由「有没有第二行读数」决定 */
private chipH(unit: PreparedUnit): number {
return unit.sub ? CHIP_H + CHIP_SUB_H : CHIP_H;
}
/** /**
* 区界那一档:真实的行政区多边形。 * 区界那一档:真实的行政区多边形。
* *
...@@ -436,6 +571,7 @@ export class SpotlightLayer { ...@@ -436,6 +571,7 @@ export class SpotlightLayer {
private drawDistrict( private drawDistrict(
ctx: CanvasRenderingContext2D, ctx: CanvasRenderingContext2D,
unit: PreparedUnit, unit: PreparedUnit,
frame: Frame,
canvasW: number, canvasW: number,
canvasH: number, canvasH: number,
active: boolean, active: boolean,
...@@ -445,51 +581,57 @@ export class SpotlightLayer { ...@@ -445,51 +581,57 @@ export class SpotlightLayer {
let x1 = -Infinity; let x1 = -Infinity;
let y1 = -Infinity; let y1 = -Infinity;
const rgb = gradientAt(unit.fillU); for (const poly of unit.drawPolys) {
for (const rings of unit.drawPolys) {
ctx.beginPath(); ctx.beginPath();
for (const ring of rings) { for (const ring of poly.rings) {
for (let k = 0; k < ring.length; k += 1) { for (let k = 0; k < ring.pts.length; k += 1) {
const p = this.map.lngLatToContainer([ring[k][0], ring[k][1]]); const px = frame.x(ring.pts[k][0]);
if (p.x < x0) x0 = p.x; const py = frame.y(ring.my[k]);
if (p.y < y0) y0 = p.y; if (px < x0) x0 = px;
if (p.x > x1) x1 = p.x; if (py < y0) y0 = py;
if (p.y > y1) y1 = p.y; if (px > x1) x1 = px;
if (k === 0) ctx.moveTo(p.x, p.y); if (py > y1) y1 = py;
else ctx.lineTo(p.x, p.y); if (k === 0) ctx.moveTo(px, py);
else ctx.lineTo(px, py);
} }
ctx.closePath(); ctx.closePath();
} }
ctx.fillStyle = rgbCss(rgb, districtFillAlpha(unit.fillU) + (active ? 0.08 : 0)); ctx.fillStyle = active ? unit.fillActive : unit.fill;
ctx.fill('evenodd'); ctx.fill('evenodd');
ctx.lineJoin = 'round'; ctx.lineJoin = 'round';
ctx.lineWidth = active ? 3 : 1.8; ctx.lineWidth = active ? 3 : 1.8;
ctx.strokeStyle = rgbCss(rgb, 1); ctx.strokeStyle = active ? unit.ringActive : unit.ring;
ctx.stroke(); ctx.stroke();
} }
// 点中这一档时把边界再描一遍浅色宽线:填色本身已经很淡,只加宽 1.2 像素在 // 点中这一档时把边界再描一遍浅色宽线:填色本身已经很淡,只加宽 1.2 像素在
// 一整片区界上根本分不出「哪一块是刚点的那块」,而清单正是从这一块的点击里打开的 // 一整片区界上根本分不出「哪一块是刚点的那块」,而清单正是从这一块的点击里打开的
if (active) { if (active) {
for (const rings of unit.drawPolys) { for (const poly of unit.drawPolys) {
ctx.beginPath(); ctx.beginPath();
for (const ring of rings) { for (const ring of poly.rings) {
for (let k = 0; k < ring.length; k += 1) { for (let k = 0; k < ring.pts.length; k += 1) {
const p = this.map.lngLatToContainer([ring[k][0], ring[k][1]]); const px = frame.x(ring.pts[k][0]);
if (k === 0) ctx.moveTo(p.x, p.y); const py = frame.y(ring.my[k]);
else ctx.lineTo(p.x, p.y); if (k === 0) ctx.moveTo(px, py);
else ctx.lineTo(px, py);
} }
ctx.closePath(); ctx.closePath();
} }
ctx.lineWidth = 8; ctx.lineWidth = 8;
ctx.strokeStyle = rgbCss(rgb, 0.22); ctx.strokeStyle = unit.glow;
ctx.stroke(); ctx.stroke();
} }
} }
// 一片都没画到(区界整体在屏幕外)时给一个空范围,取景靠地理坐标而不是这里 // 一片都没画到(区界整体在屏幕外)时给一个空范围,取景靠地理坐标而不是这里
if (!Number.isFinite(x0)) return { x0: 0, y0: 0, x1: 0, y1: 0 }; if (!Number.isFinite(x0)) return { x0: 0, y0: 0, x1: 0, y1: 0 };
return { x0: Math.max(x0, 0), y0: Math.max(y0, 0), x1: Math.min(x1, canvasW), y1: Math.min(y1, canvasH) }; return {
x0: Math.max(x0, 0),
y0: Math.max(y0, 0),
x1: Math.min(x1, canvasW),
y1: Math.min(y1, canvasH),
};
} }
/** 位置那一档:榜上那一格本身 */ /** 位置那一档:榜上那一格本身 */
...@@ -501,18 +643,15 @@ export class SpotlightLayer { ...@@ -501,18 +643,15 @@ export class SpotlightLayer {
side: number, side: number,
active: boolean, active: boolean,
) { ) {
// 这一档用档位色而不是密度色阶:一处就是一处,没有「比邻格浓多少」可读, ctx.fillStyle = active ? unit.fillActive : unit.fill;
// 色阶在这里反而会把「一处出过案」说成「这一片很挤」。
// 起数和天数都在牌子上念 —— 深浅仍然只讲密度,那一维在这里没有可比的邻格。
ctx.fillStyle = rgbCss(unit.colorRgb, active ? 0.26 : 0.15);
ctx.fillRect(left, top, side, side); ctx.fillRect(left, top, side, side);
ctx.lineWidth = active ? 2.4 : 1.6; ctx.lineWidth = active ? 2.4 : 1.6;
ctx.strokeStyle = rgbCss(unit.colorRgb, active ? 1 : 0.85); ctx.strokeStyle = active ? unit.ringActive : unit.ring;
ctx.strokeRect(left + 0.5, top + 0.5, side - 1, side - 1); ctx.strokeRect(left + 0.5, top + 0.5, side - 1, side - 1);
if (active) { if (active) {
ctx.setLineDash([4, 4]); ctx.setLineDash([4, 4]);
ctx.lineWidth = 1.2; ctx.lineWidth = 1.2;
ctx.strokeStyle = rgbCss(paletteHexToRgb(PALETTE.primaryDeep), 0.5); ctx.strokeStyle = unit.glow;
ctx.strokeRect(left - 4.5, top - 4.5, side + 9, side + 9); ctx.strokeRect(left - 4.5, top - 4.5, side + 9, side + 9);
ctx.setLineDash([]); ctx.setLineDash([]);
} }
...@@ -528,59 +667,63 @@ export class SpotlightLayer { ...@@ -528,59 +667,63 @@ export class SpotlightLayer {
private drawCorridors( private drawCorridors(
ctx: CanvasRenderingContext2D, ctx: CanvasRenderingContext2D,
unit: PreparedUnit, unit: PreparedUnit,
pxPerMeter: number, frame: Frame,
active: boolean, active: boolean,
): { x0: number; y0: number; x1: number; y1: number } { ): { x0: number; y0: number; x1: number; y1: number } {
let x0 = Infinity; let x0 = Infinity;
let y0 = Infinity; let y0 = Infinity;
let x1 = -Infinity; let x1 = -Infinity;
let y1 = -Infinity; let y1 = -Infinity;
// 粗细跟着缩放走,但夹进看得见的那一段:全市视图下 100 米只有 1 像素, const lineW = this.linePx + (active ? 2 : 0);
// 那一条线会退化成 hairline,读不出「这是一条路」
const lineW = clamp(this.cellM * pxPerMeter, CORRIDOR_MIN_PX, CORRIDOR_MAX_PX) + (active ? 2 : 0);
for (const path of unit.paths) { for (const path of unit.paths) {
const pts = path.nodes.map((nd) => { const nodes = path.nodes;
const p = this.map.lngLatToContainer([nd.lng, nd.lat]); const n = nodes.length;
x0 = Math.min(x0, p.x - lineW); if (this.scratchX.length < n) {
y0 = Math.min(y0, p.y - lineW); this.scratchX = new Float64Array(n + 32);
x1 = Math.max(x1, p.x + lineW); this.scratchY = new Float64Array(n + 32);
y1 = Math.max(y1, p.y + lineW); }
return { x: p.x, y: p.y, n: nd.n }; for (let k = 0; k < n; k += 1) {
}); const px = frame.x(nodes[k].lng);
const py = frame.y(path.my[k]);
if (pts.length === 1) { this.scratchX[k] = px;
this.scratchY[k] = py;
if (px - lineW < x0) x0 = px - lineW;
if (py - lineW < y0) y0 = py - lineW;
if (px + lineW > x1) x1 = px + lineW;
if (py + lineW > y1) y1 = py + lineW;
}
if (n === 1) {
// 只有一格的走廊描不出走向,就画一格:那是这条路此刻唯一说得清的地方 // 只有一格的走廊描不出走向,就画一格:那是这条路此刻唯一说得清的地方
ctx.beginPath(); ctx.beginPath();
ctx.arc(pts[0].x, pts[0].y, lineW / 2, 0, Math.PI * 2); ctx.arc(this.scratchX[0], this.scratchY[0], lineW / 2, 0, Math.PI * 2);
ctx.fillStyle = 'rgba(255,255,255,.72)'; ctx.fillStyle = 'rgba(255,255,255,.72)';
ctx.fill(); ctx.fill();
ctx.beginPath(); ctx.beginPath();
ctx.arc(pts[0].x, pts[0].y, lineW / 2 - 1, 0, Math.PI * 2); ctx.arc(this.scratchX[0], this.scratchY[0], lineW / 2 - 1, 0, Math.PI * 2);
ctx.fillStyle = densityCellFill(pts[0].n / unit.pathMax); ctx.fillStyle = path.nodeFill[0];
ctx.fill(); ctx.fill();
continue; continue;
} }
strokePolyline(ctx, pts); polyline(ctx, this.scratchX, this.scratchY, n);
ctx.lineWidth = lineW + 4; ctx.lineWidth = lineW + 4;
ctx.strokeStyle = 'rgba(255,255,255,.72)'; ctx.strokeStyle = 'rgba(255,255,255,.72)';
ctx.stroke(); ctx.stroke();
// 逐段涂色:一条路上「哪一段挤」正是这一档要读的东西,整条涂同一个深浅就白归一次格。 // 逐段涂色:一条路上「哪一段挤」正是这一档要读的东西,整条涂同一个深浅就白归一次格。
// 分母取档内最挤那一段(不是全市最挤),与街道那一档同一把尺:只看自己内部。 for (let k = 1; k < n; k += 1) {
for (let k = 1; k < pts.length; k += 1) {
const u = (pts[k - 1].n + pts[k].n) / 2 / unit.pathMax;
ctx.beginPath(); ctx.beginPath();
ctx.moveTo(pts[k - 1].x, pts[k - 1].y); ctx.moveTo(this.scratchX[k - 1], this.scratchY[k - 1]);
ctx.lineTo(pts[k].x, pts[k].y); ctx.lineTo(this.scratchX[k], this.scratchY[k]);
ctx.lineWidth = lineW; ctx.lineWidth = lineW;
ctx.strokeStyle = densityCellFill(u); ctx.strokeStyle = path.segFill[k - 1];
ctx.stroke(); ctx.stroke();
} }
if (active) { if (active) {
strokePolyline(ctx, pts); polyline(ctx, this.scratchX, this.scratchY, n);
ctx.lineWidth = lineW + 8; ctx.lineWidth = lineW + 8;
ctx.strokeStyle = rgbCss(unit.colorRgb, 0.25); ctx.strokeStyle = rgbCss(unit.colorRgb, 0.25);
ctx.stroke(); ctx.stroke();
...@@ -607,37 +750,22 @@ export class SpotlightLayer { ...@@ -607,37 +750,22 @@ export class SpotlightLayer {
canvasH: number, canvasH: number,
active: boolean, active: boolean,
): { x0: number; y0: number; x1: number; y1: number } | null { ): { x0: number; y0: number; x1: number; y1: number } | null {
const twoLines = !!unit.sub; const chip = this.fitChip(unit, canvasW);
const h = twoLines ? CHIP_H + CHIP_SUB_H : CHIP_H; const h = this.chipH(unit);
const maxTextW = Math.min(CHIP_MAX_TEXT_W, canvasW - 40); const left = Math.max(4, Math.min(x - chip.w / 2, canvasW - chip.w - 4));
ctx.font = CHIP_FONT;
const text = `${unit.label} · ${fmtCompact(unit.count)} 起`;
const label = ellipsize(ctx, text, maxTextW - CHIP_DOT_R * 2 - 6);
const labelW = ctx.measureText(label).width;
let subLabel = '';
let subW = 0;
if (twoLines && unit.sub) {
ctx.font = CHIP_SUB_FONT;
subLabel = ellipsize(ctx, unit.sub, maxTextW);
subW = ctx.measureText(subLabel).width;
}
const w = Math.max(labelW, subW) + CHIP_DOT_R * 2 + 6 + CHIP_PAD_X * 2;
const left = Math.max(4, Math.min(x - w / 2, canvasW - w - 4));
const top = Math.max(4, Math.min(y - h - CHIP_GAP, canvasH - h - 4)); const top = Math.max(4, Math.min(y - h - CHIP_GAP, canvasH - h - 4));
ctx.shadowColor = 'rgba(16,24,40,.26)'; ctx.shadowColor = 'rgba(16,24,40,.26)';
ctx.shadowBlur = 5; ctx.shadowBlur = 5;
ctx.shadowOffsetY = 1; ctx.shadowOffsetY = 1;
roundRectPath(ctx, left, top, w, h, 6); roundRectPath(ctx, left, top, chip.w, h, 6);
ctx.fillStyle = 'rgba(255,255,255,.94)'; ctx.fillStyle = 'rgba(255,255,255,.94)';
ctx.fill(); ctx.fill();
ctx.shadowColor = 'transparent'; ctx.shadowColor = 'transparent';
ctx.shadowBlur = 0; ctx.shadowBlur = 0;
ctx.shadowOffsetY = 0; ctx.shadowOffsetY = 0;
ctx.lineWidth = active ? 2 : 1; ctx.lineWidth = active ? 2 : 1;
ctx.strokeStyle = rgbCss(unit.colorRgb, active ? 1 : 0.7); ctx.strokeStyle = active ? unit.chipStrokeActive : unit.chipStroke;
ctx.stroke(); ctx.stroke();
ctx.beginPath(); ctx.beginPath();
...@@ -649,13 +777,39 @@ export class SpotlightLayer { ...@@ -649,13 +777,39 @@ export class SpotlightLayer {
ctx.textBaseline = 'middle'; ctx.textBaseline = 'middle';
ctx.font = CHIP_FONT; ctx.font = CHIP_FONT;
ctx.fillStyle = PALETTE.primaryDeep; ctx.fillStyle = PALETTE.primaryDeep;
ctx.fillText(label, left + CHIP_PAD_X + CHIP_DOT_R * 2 + 6, top + CHIP_H / 2 + 0.5); ctx.fillText(chip.text, left + CHIP_PAD_X + CHIP_DOT_R * 2 + 6, top + CHIP_H / 2 + 0.5);
if (twoLines && unit.sub) { if (chip.sub) {
ctx.font = CHIP_SUB_FONT; ctx.font = CHIP_SUB_FONT;
ctx.fillStyle = 'rgba(34, 43, 95, 0.72)'; ctx.fillStyle = 'rgba(34, 43, 95, 0.72)';
ctx.fillText(subLabel, left + CHIP_PAD_X, top + CHIP_H + CHIP_SUB_H / 2 - 0.5); ctx.fillText(chip.sub, left + CHIP_PAD_X, top + CHIP_H + CHIP_SUB_H / 2 - 0.5);
} }
return { x0: left, y0: top, x1: left + w, y1: top + h }; return { x0: left, y0: top, x1: left + chip.w, y1: top + h };
}
/**
* 牌子上那两行字:截断 + 尺寸。
*
* 画布宽度没变就沿用上一次的结果 —— 地址最长那档一次截断要逐字量几十遍,
* 五块牌子每帧来一遍就是每帧几百次量字,而它跟地图动不动没有半点关系。
*/
private fitChip(unit: PreparedUnit, canvasW: number): ChipMetrics {
const chip = unit.chip;
if (chip.fittedW === canvasW) return chip;
const maxTextW = Math.min(CHIP_MAX_TEXT_W, canvasW - 40);
const measureMain = (t: string) => textWidth(CHIP_FONT, t) ?? t.length * FALLBACK_CHAR_W;
const measureSub = (t: string) => textWidth(CHIP_SUB_FONT, t) ?? t.length * FALLBACK_CHAR_W;
chip.text = ellipsizeBy(
measureMain,
`${unit.label} · ${fmtCompact(unit.count)} 起`,
maxTextW - CHIP_DOT_R * 2 - 6,
);
chip.textW = measureMain(chip.text);
chip.sub = unit.sub ? ellipsizeBy(measureSub, unit.sub, maxTextW) : '';
chip.subW = chip.sub ? measureSub(chip.sub) : 0;
chip.w = Math.max(chip.textW, chip.subW) + CHIP_DOT_R * 2 + 6 + CHIP_PAD_X * 2;
chip.fittedW = canvasW;
return chip;
} }
/** /**
...@@ -703,8 +857,8 @@ export class SpotlightLayer { ...@@ -703,8 +857,8 @@ export class SpotlightLayer {
destroy() { destroy() {
this.layer?.setMap(null); this.layer?.setMap(null);
this.layer = null; this.layer = null;
this.canvas = null; this.surface?.destroy();
this.ctx = null; this.surface = null;
this.units = []; this.units = [];
this.boxes = []; this.boxes = [];
} }
...@@ -717,7 +871,9 @@ function clamp(v: number, min: number, max: number): number { ...@@ -717,7 +871,9 @@ function clamp(v: number, min: number, max: number): number {
/** 区界填色的透明度:按深浅那一档在 DISTRICT_FILL_* 那一段里线性走 */ /** 区界填色的透明度:按深浅那一档在 DISTRICT_FILL_* 那一段里线性走 */
function districtFillAlpha(u: number): number { function districtFillAlpha(u: number): number {
const x = Math.min(Math.max(u, 0), 1); const x = Math.min(Math.max(u, 0), 1);
return Math.round((DISTRICT_FILL_FLOOR + (DISTRICT_FILL_CEIL - DISTRICT_FILL_FLOOR) * x) * 1000) / 1000; return (
Math.round((DISTRICT_FILL_FLOOR + (DISTRICT_FILL_CEIL - DISTRICT_FILL_FLOOR) * x) * 1000) / 1000
);
} }
/** /**
...@@ -736,11 +892,14 @@ function decimateRing(ring: LngLat[]): LngLat[] { ...@@ -736,11 +892,14 @@ function decimateRing(ring: LngLat[]): LngLat[] {
return out; return out;
} }
function strokePolyline( /** 走廊折线:位置在草稿缓冲里,按点数取前 n 个 */
function polyline(
ctx: CanvasRenderingContext2D, ctx: CanvasRenderingContext2D,
pts: Array<{ x: number; y: number }>, xs: Float64Array,
ys: Float64Array,
n: number,
): void { ): void {
ctx.beginPath(); ctx.beginPath();
ctx.moveTo(pts[0].x, pts[0].y); ctx.moveTo(xs[0], ys[0]);
for (let k = 1; k < pts.length; k += 1) ctx.lineTo(pts[k].x, pts[k].y); for (let k = 1; k < n; k += 1) ctx.lineTo(xs[k], ys[k]);
} }
...@@ -38,10 +38,22 @@ export function roundRectPath( ...@@ -38,10 +38,22 @@ export function roundRectPath(
* 按字数切会在同样宽度下截出长短不一的两截,牌子看着就在抖。 * 按字数切会在同样宽度下截出长短不一的两截,牌子看着就在抖。
*/ */
export function ellipsize(ctx: CanvasRenderingContext2D, text: string, maxW: number): string { export function ellipsize(ctx: CanvasRenderingContext2D, text: string, maxW: number): string {
if (maxW <= 0 || ctx.measureText(text).width <= maxW) return text; return ellipsizeBy((t) => ctx.measureText(t).width, text, maxW);
}
/**
* 同一件事的「自带量字方法」版本。
*
* 单独拆出来是因为截断可以在喂数据时做一次,不必每帧现算:聚焦层的牌子上是一段完整地址,
* 一次截断要从头把每个前缀都量一遍,几十个字就是几十次 measureText,而画布上的字宽
* 只与字体和文字本身有关(跟缩放、屏幕都无关)。画布拿不到时(无 canvas 的环境)
* 调用方可以传一个按字数估的函数,截出来的牌子只是长短略有差别。
*/
export function ellipsizeBy(measure: (text: string) => number, text: string, maxW: number): string {
if (maxW <= 0 || measure(text) <= maxW) return text;
const dots = '…'; const dots = '…';
const dotsW = ctx.measureText(dots).width; const dotsW = measure(dots);
let end = text.length; let end = text.length;
while (end > 1 && ctx.measureText(text.slice(0, end)).width + dotsW > maxW) end -= 1; while (end > 1 && measure(text.slice(0, end)) + dotsW > maxW) end -= 1;
return `${text.slice(0, end)}${dots}`; return `${text.slice(0, end)}${dots}`;
} }
import { describe, expect, it } from 'vitest';
import { HeatLayer } from './HeatLayer';
/**
* 热力「喂数据」这一步的守卫(2026-10-15 性能调优时补)。
*
* setDataset 为了不再每次 moveend 都重建两万多个点对象,加了一层按引用判同的缓存:
* 底数(那批桶的三列 + 过滤器)没换就沿用上次算好的点表,只按当前视野重算深浅的分母。
* 这个优化一旦出错,坏法很难看穿 —— 屏上不是空白也不是报错,而是「深浅对了、位置却是上一批点」,
* 正是这个项目最不能出现的那类乌龙。所以把三条不变量钉在这里:
* 1. 每次喂进去的点表,必须等于按 (lng, lat, count, keep) 现算出来的那一份;
* 2. 只换视野(缩放 / 中心)时点数与坐标一个都不许变,但归一化上限要跟着视野走;
* 3. 换过滤器(新的掩码引用)必须重算,不许拿旧点表画新范围。
*/
interface Feed {
data: Array<{ lng: number; lat: number; count: number }>;
max: number;
}
/** 高德那块热力画布在测试里只需要记下「喂进来了什么」 */
function stubAmap(feeds: Feed[]) {
(window as unknown as Record<string, unknown>).AMap = {
HeatMap: class {
setDataSet(d: Feed) {
feeds.push(d);
}
setOptions() {}
show() {}
hide() {}
destroy() {}
},
};
}
/**
* 一个够用的假地图:投影按线性近似给(本测试只关心「同一视野两次喂的数一致、
* 换视野后仍然等于现算的那一份」,不校核真实墨卡托常数)。
*/
function fakeMap(view: { zoom: number; lng: number; lat: number; w: number; h: number }) {
return {
getSize: () => ({ width: view.w, height: view.h }),
getCenter: () => ({ getLng: () => view.lng, getLat: () => view.lat }),
getZoom: () => view.zoom,
lngLatToContainer: () => ({ x: view.w / 2, y: view.h / 2 }),
} as unknown as AMap.Map;
}
/** 测试数据:一圈在视野内的桶 + 一圈在视野外的(模拟聚合请求带的缓冲区) */
const LNG = Int32Array.from([114.0, 114.01, 114.02, 114.2, 114.3, 113.8].map((v) => v * 1e6));
const LAT = Int32Array.from([22.6, 22.6, 22.61, 22.62, 22.55, 22.6].map((v) => v * 1e6));
const COUNT = Int32Array.from([10, 20, 30, 40, 50, 60]);
/** 现算一份期望的点表:与实现同一口径(keep 为 1 才进图),断言用它,不抄常数 */
function expected(keep: Uint8Array | null) {
const out: Array<{ lng: number; lat: number; count: number }> = [];
for (let i = 0; i < LNG.length; i += 1) {
if (keep && keep[i] !== 1) continue;
out.push({ lng: LNG[i] / 1e6, lat: LAT[i] / 1e6, count: COUNT[i] });
}
return out;
}
describe('HeatLayer.setDataset · 缓存后的点表仍然等于现算的那一份', () => {
it('无过滤器时全量进图;只换视野不改变点表,深浅分母却跟着视野走', () => {
const feeds: Feed[] = [];
stubAmap(feeds);
const city = { zoom: 11, lng: 114.05, lat: 22.6, w: 12000, h: 9000 };
const heat = new HeatLayer(fakeMap(city));
heat.setDataset(LNG, LAT, COUNT);
heat.setDataset(LNG, LAT, COUNT);
expect(feeds).toHaveLength(2);
expect(feeds[0].data).toEqual(expected(null));
// 第二次拿到的是同一份点表(缓存生效),但内容必须仍然等于现算结果
expect(feeds[1].data).toEqual(expected(null));
const cityMax = feeds[0].max;
// 收到街区视野:屏幕外那几个桶不再参与深浅的归一,点表本身却一个都不能少
const hood = { zoom: 15, lng: 114.01, lat: 22.6, w: 400, h: 300 };
const heat2 = new HeatLayer(fakeMap(hood));
heat2.setDataset(LNG, LAT, COUNT);
expect(heat2.count).toBe(6);
expect(heat2.maxWeight).toBeLessThan(cityMax);
});
it('换过滤器掩码时必须重算点表,不能拿旧点表画新范围', () => {
const feeds: Feed[] = [];
stubAmap(feeds);
const heat = new HeatLayer(fakeMap({ zoom: 11, lng: 114.05, lat: 22.6, w: 12000, h: 9000 }));
const keepAll = new Uint8Array(LNG.length).fill(1);
heat.setDataset(LNG, LAT, COUNT, keepAll);
// 只留前两档:掩码是新建的引用,缓存必须作废
const keepTwo = new Uint8Array(LNG.length).fill(0);
keepTwo[0] = 1;
keepTwo[1] = 1;
heat.setDataset(LNG, LAT, COUNT, keepTwo);
expect(feeds[0].data).toEqual(expected(keepAll));
expect(feeds[1].data).toEqual(expected(keepTwo));
expect(heat.count).toBe(2);
});
it('掩码引用不变、只换底数(聚合换了结果)时同样重算', () => {
const feeds: Feed[] = [];
stubAmap(feeds);
const heat = new HeatLayer(fakeMap({ zoom: 11, lng: 114.05, lat: 22.6, w: 12000, h: 9000 }));
heat.setDataset(LNG, LAT, COUNT);
const shiftedLng = Int32Array.from(LNG);
shiftedLng[0] = 114.05 * 1e6;
heat.setDataset(shiftedLng, LAT, COUNT);
expect(feeds[1].data[0].lng).toBeCloseTo(114.05, 6);
expect(feeds[0].data[0].lng).toBeCloseTo(114.0, 6);
});
it('清空之后不留缓存:下一次喂的仍是现算结果', () => {
const feeds: Feed[] = [];
stubAmap(feeds);
const heat = new HeatLayer(fakeMap({ zoom: 11, lng: 114.05, lat: 22.6, w: 12000, h: 9000 }));
heat.setDataset(LNG, LAT, COUNT);
heat.clear();
expect(feeds[1].data).toEqual([]);
heat.setDataset(LNG, LAT, COUNT);
expect(feeds[2].data).toEqual(expected(null));
});
});
import { describe, expect, it } from 'vitest';
import { GRID, pxPerDegLat } from '../aggregate/grid';
import { mercY } from './viewFrame';
/**
* 投影换算的守卫。
*
* 自绘层原先逐帧调用 map.lngLatToContainer 求屏幕位置,现在改成「每一点的墨卡托纬度
* 在喂数据时算一次,每帧只做乘加」。这个替换只有在**两者是同一种投影**时才不会让
* 屏幕上的方格、黑点盘、聚焦形状整体错位一截 —— 而观感问题在构建期测不出来,所以钉在这里。
*
* 用项目自己那份网格公式(grid.ts)当基准:聚合网格、热力半径、黑点盘径全部由它换算,
* 也就是说界面上「48 像素一格」这套直觉的尺子就是它。mercY 是同一投影的积分形式,
* 两者必须对得上:把 mercY 在某个纬度上做微分,得到的像素/度数应与 pxPerDegLat 一致。
*/
const ZOOM = 12;
function pixelY(latDeg: number): number {
const world = GRID.tileSize * Math.pow(2, ZOOM);
return ((1 - mercY(latDeg) / Math.PI) * world) / 2;
}
describe('mercY 与聚合网格用的是同一支墨卡托', () => {
it('中心纬度上下各取一点,像素差除以纬度差就是每度像素', () => {
const lat = 22.55;
const d = 0.01;
const measured = (pixelY(lat - d) - pixelY(lat + d)) / (2 * d);
const expected = pxPerDegLat(ZOOM, lat);
// 中心差分对 0.01° 的量级误差远小于 0.1%
expect(measured).toBeCloseTo(expected, 2);
});
it('纬度越高,同一纬度差占的像素越多(墨卡托拉伸)', () => {
const span = (a: number, b: number) => Math.abs(pixelY(a) - pixelY(b));
expect(span(20, 21)).toBeLessThan(span(30, 31));
expect(span(30, 31)).toBeLessThan(span(40, 41));
});
it('纬度增大时屏幕 y 减小(北上、下为正向)', () => {
expect(pixelY(22.6)).toBeLessThan(pixelY(22.5));
});
it('经度方向是线性的:每度像素只由缩放决定', () => {
const world = GRID.tileSize * Math.pow(2, ZOOM);
expect(world / 360).toBeCloseTo((GRID.tileSize * Math.pow(2, ZOOM)) / 360, 6);
});
it('超出墨卡托区间时按 ±85° 封顶,不会算出无穷大', () => {
expect(Number.isFinite(mercY(89))).toBe(true);
expect(mercY(89)).toBe(mercY(85));
expect(mercY(-89)).toBe(mercY(-85));
});
});
import { GRID } from '../aggregate/grid';
import { M_PER_EQUATOR } from './hotspotGeometry';
/**
* 自绘层的每帧开场:视图变化判定、画布尺寸对齐、投影基准。
*
* 为什么单独成模块 —— 这四个数(每帧是否要重画、一个经纬度落在屏幕哪儿)原先在四个
* 自绘层里各写了一份,而其中「每度多少像素」这一份还都写成调用 `map.lngLatToContainer`:
* 一次调用要在高德内部造一个 LngLat、做一次投影、再返回一个新对象,一帧里几百到两千次
* 就是这个数量级的分配与调用。拖动地图时这一项是逐帧付的钱,空闲时也在付(CustomLayer
* 每帧回调),于是「地图拖着拖着就越来越沉」。
*
* 改法是把投影拆成「一次换算 + 每帧两次乘加」:
* 墨卡托下屏幕位置只由 (缩放, 中心, 尺寸) 决定,
* x = 中心像素x + (经度 − 中心经度) × 每度像素,
* y = 中心像素y + (中心的那一支墨卡托纬度 − 这一点的) × 每像素纬度因子。
* 其中每一点的纬度因子(mercY)与缩放无关,所以在喂数据时一次算好存起来,
* 每帧只剩减法和乘法。
*
* ⚠️ 中心那一点的位置仍然向 `lngLatToContainer` 问一次(每帧一次,不是每桶一次):
* 这样原点由高德自己说,而不是我们假设它在画布正中。地图带偏移、容器尺寸与
* getSize() 不一致时,画出来的东西不会整屏错位。
*
* 纬度换算与 grid.ts 的 pxPerDegLat 是同一支公式(那边是微分形式,这里是积分形式),
* 两者对得上这一点由 viewFrame.test.ts 盯着。
*/
/**
* 墨卡托纬度:tan(π/4 + φ/2) 的自然对数。
*
* 存这个数而不是存像素,是因为它与缩放无关 —— 喂一次数据算一次,缩放时只需换比例尺。
* 纬度截到 ±85°,与墨卡托 Web 瓦片的可用区间一致(超出会趋向无穷,深圳用不到)。
*/
export function mercY(latDeg: number): number {
const phi = (Math.max(-85, Math.min(85, latDeg)) * Math.PI) / 180;
return Math.log(Math.tan(Math.PI / 4 + phi / 2));
}
/**
* 量一段文字在画布上占多少像素。
*
* 用的是一块专门的量字画布(64×64,只建一次),不是各层自己那块绘制画布:
* 底衬半径要在喂数据时算好(见 ClusterLayer.recomputeLabels),而那一趟常常发生在
* 绘制画布还没尺寸的时候(层刚建、或收起后交还过 backing store)。
* 拿 0×0 的画布去 measureText 是「也许还给宽度」的灰区,量不到就只能按字数估,
* 表现是底衬集体缩到最小一档 —— 一类没人会去查的视觉退化。专门一块就没这个问题。
*
* 返回 null 表示量不了(无 canvas 的环境,例如测试里的 jsdom),调用方自备估算值。
*/
let measurer: CanvasRenderingContext2D | null = null;
let measurerTried = false;
export function textWidth(font: string, text: string): number | null {
if (!measurerTried) {
measurerTried = true;
const canvas = document.createElement('canvas');
canvas.width = 64;
canvas.height = 64;
measurer = canvas.getContext('2d');
}
if (!measurer) return null;
measurer.font = font;
return measurer.measureText(text).width;
}
/** 一帧的投影基准。由 CanvasSurface 维护,调用方只在本次同步绘制里使用 */
export class Frame {
/** 缩放级别(动画途中是小数) */
zoom = 0;
/** 每度经度的像素 */
pxPerDegLng = 0;
/** 米 → 屏幕像素(按参考纬度,与黑点盘、聚焦方格、热力半径同一口径) */
pxPerMeter = 0;
private originX = 0;
private originY = 0;
private centerLng = 0;
private centerMercY = 0;
private pxPerMercY = 0;
set(
map: AMap.Map,
zoom: number,
centerLng: number,
centerLat: number,
width: number,
height: number,
): void {
this.zoom = zoom;
this.centerLng = centerLng;
this.centerMercY = mercY(centerLat);
const world = GRID.tileSize * Math.pow(2, zoom);
this.pxPerDegLng = world / 360;
this.pxPerMercY = world / (2 * Math.PI);
this.pxPerMeter = this.pxPerDegLng / (M_PER_EQUATOR * Math.cos((22.5 * Math.PI) / 180));
// 每帧唯一的一次投影调用:把原点交给地图本身
const p = map.lngLatToContainer([centerLng, centerLat]);
this.originX = p.x;
this.originY = p.y;
// 尺寸不参与换算(原点已经带上了容器信息),只留给调用方做裁剪
void width;
void height;
}
/** 经度 → 屏幕 x */
x(lng: number): number {
return this.originX + (lng - this.centerLng) * this.pxPerDegLng;
}
/** mercY(纬度) → 屏幕 y。纬度值请在喂数据时用 mercY() 算好存下来 */
y(mercLatitude: number): number {
return this.originY + (this.centerMercY - mercLatitude) * this.pxPerMercY;
}
}
/**
* 一块自绘画布:尺寸对齐、空闲跳过、收起时交还显存。
*
* 三件事各自都值一点钱,合在一起才看得出为什么放在一处:
* 1) **空闲不重画**。CustomLayer 用 alwaysRender: true 时地图每帧都回调,
* 原先四个层每帧都把整屏 clearRect + 重投几百个点 + 重绘,页面停在那里不动也在满帧烧 CPU;
* 烧掉的主线程与合成时间正是「拖动之外,操作界面也卡」的来源。现在视图与数据都没变就整帧跳过,
* 画布内容原样留着(高德不会清它)。会自己动的层走 beginAnimated:它照样出帧,
* 但只清自己那一小块,损坏区域不扩到全屏。
* 2) **画布尺寸**。DPR 上限 2 保持原样;尺寸没变时不再赋值 width(赋值会清空整块画布并重建 backing store)。
* 3) **收起即交还**。一张全屏画布在 DPR 2 下约占 30MB,四层就是 120MB,
* 而聚焦层与定位层在多数会话里根本不会出现,出现过的用完也该收起来。
*/
export class CanvasSurface {
readonly canvas: HTMLCanvasElement;
readonly frame = new Frame();
private ctx: CanvasRenderingContext2D | null = null;
private zoom = Number.NaN;
private lng = Number.NaN;
private lat = Number.NaN;
private w = -1;
private h = -1;
private dpr = -1;
/** 视图没变但数据/选项变了,下一帧仍要重画 */
private dirty = true;
constructor() {
const canvas = document.createElement('canvas');
canvas.style.position = 'absolute';
canvas.style.left = '0';
canvas.style.top = '0';
// 必须让地图继续接收鼠标事件,否则 canvas 会把拖动、缩放全部吃掉
canvas.style.pointerEvents = 'none';
this.canvas = canvas;
}
/** 数据、选项、可见性等本层自己的变化:即使视图一动没动,下一帧也得重画 */
invalidate(): void {
this.dirty = true;
}
/**
* 每帧开场。
*
* @returns null 表示这一帧什么都不必重画(视图与本层都没变),调用方直接 return;
* 非 null 时画布已经对齐尺寸、设好 DPR 变换并清空,附带这一帧的投影基准。
*/
begin(map: AMap.Map): Frame | null {
return this.open(map, false)?.frame ?? null;
}
/**
* 每帧开场(会自己动的层专用,见 CasePinLayer 的光圈)。
*
* 与 begin 的差别只有一处:视图没变时也把投影基准交回来,让调用方继续画下一帧动画,
* 但**不清屏** —— 整屏清空会把这块画布的损坏区域扩到全屏,浏览器每帧就得重传一整张
* 全屏纹理,三十帧一秒下来「一个小小的呼吸光圈」就能变成整个页面的合成负担。
* 视图真的变了才整屏清空(那时画面本来就要重排),否则由调用方只清自己那一小块。
*
* @returns null 只在拿不到 2d 上下文时出现;clearedAll 告诉调用方这一帧要不要自己局部清屏。
*/
beginAnimated(map: AMap.Map): { frame: Frame; clearedAll: boolean } | null {
return this.open(map, true);
}
private open(map: AMap.Map, animated: boolean): { frame: Frame; clearedAll: boolean } | null {
const size = map.getSize();
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const center = map.getCenter();
const zoom = map.getZoom();
const lng = center.getLng();
const lat = center.getLat();
const unchanged =
!this.dirty &&
zoom === this.zoom &&
lng === this.lng &&
lat === this.lat &&
size.width === this.w &&
size.height === this.h &&
dpr === this.dpr;
if (unchanged) {
// 动画层继续用上一帧的投影基准:视图一动没动,原点与比例尺还是那一套
if (!animated || !this.ctx) return null;
return { frame: this.frame, clearedAll: false };
}
this.dirty = false;
this.zoom = zoom;
this.lng = lng;
this.lat = lat;
this.w = size.width;
this.h = size.height;
this.dpr = dpr;
const ctx = this.ctx ?? this.canvas.getContext('2d');
if (!ctx) return null;
this.ctx = ctx;
const px = Math.round(size.width * dpr);
const py = Math.round(size.height * dpr);
if (this.canvas.width !== px || this.canvas.height !== py) {
this.canvas.width = px;
this.canvas.height = py;
this.canvas.style.width = `${size.width}px`;
this.canvas.style.height = `${size.height}px`;
}
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, size.width, size.height);
this.frame.set(map, zoom, lng, lat, size.width, size.height);
return { frame: this.frame, clearedAll: true };
}
/** 画布宽高。裁剪判定用它,省得每层再问一次 getSize */
get width(): number {
return this.w;
}
get height(): number {
return this.h;
}
/** 本层绘制用的 2d 上下文。begin() 给出非 null 的投影基准时,它一定已经就位 */
get context(): CanvasRenderingContext2D | null {
return this.ctx;
}
/**
* 收起这一层时把 backing store 交还给浏览器。
*
* 层的 show/hide 由高德负责,画布像素却还占着内存并参与合成;聚焦层、定位层、黑点层
* 都是「偶尔出现」的层,用完不放手就会攒出好几张全屏画布。
* 重新展开时 begin() 会因为尺寸对不上而整帧重画,不需要额外处理。
*/
release(): void {
if (this.canvas.width !== 0 || this.canvas.height !== 0) {
this.canvas.width = 0;
this.canvas.height = 0;
this.w = -1;
this.h = -1;
}
this.dirty = true;
}
/**
* 把「数据变了但地图没动」这类重绘请求合并到同一帧。
*
* 每个层原先各写一份 requestAnimationFrame + 布尔标志,行为必须一致(同一批变化只画一次),
* 所以这里连 invalidate 一起收:调用方只需 surface.schedule()。
*/
private scheduled = false;
schedule(draw: () => void): void {
this.invalidate();
if (this.scheduled) return;
this.scheduled = true;
requestAnimationFrame(() => {
this.scheduled = false;
draw();
});
}
destroy(): void {
this.ctx = null;
this.canvas.width = 0;
this.canvas.height = 0;
}
}
...@@ -2,8 +2,9 @@ import { Panel, Field } from '@hm/ui'; ...@@ -2,8 +2,9 @@ import { Panel, Field } from '@hm/ui';
import { useHeatmapStore } from '@/store/useHeatmapStore'; import { useHeatmapStore } from '@/store/useHeatmapStore';
import { fmtCompact, fmtInt, fmtMs } from '@/utils/format'; import { fmtCompact, fmtInt, fmtMs } from '@/utils/format';
import type { AnalysisParams } from '@/features/heatmap/aggregate/types'; import type { AnalysisParams } from '@/features/heatmap/aggregate/types';
import { Button, Segmented, Slider, Switch, Tag, Tooltip } from 'antd'; import { Button, Segmented, Switch, Tag, Tooltip } from 'antd';
import { useState } from 'react'; import { useState } from 'react';
import { ParamSlider } from './ParamSlider';
import { DownOutlined, QuestionCircleOutlined, ReloadOutlined } from '@ant-design/icons'; import { DownOutlined, QuestionCircleOutlined, ReloadOutlined } from '@ant-design/icons';
/** /**
...@@ -66,12 +67,12 @@ export function AnalysisPanel() { ...@@ -66,12 +67,12 @@ export function AnalysisPanel() {
label="降噪强度" label="降噪强度"
tooltip={`仅保留案件密度最高的前 ${params.keepPercent}% 方格作为黑点候选:数值越小,保留的点位越少、越典型`} tooltip={`仅保留案件密度最高的前 ${params.keepPercent}% 方格作为黑点候选:数值越小,保留的点位越少、越典型`}
> >
<Slider <ParamSlider
min={2} min={2}
max={30} max={30}
step={1} step={1}
value={params.keepPercent} value={params.keepPercent}
onChange={(v) => patch({ keepPercent: v })} onCommit={(v) => patch({ keepPercent: v })}
marks={{ 2: '从严', 8: '默认', 30: '从宽' }} marks={{ 2: '从严', 8: '默认', 30: '从宽' }}
tooltip={{ formatter: (v) => `保留密度最高的前 ${v}% 方格` }} tooltip={{ formatter: (v) => `保留密度最高的前 ${v}% 方格` }}
/> />
...@@ -89,7 +90,7 @@ export function AnalysisPanel() { ...@@ -89,7 +90,7 @@ export function AnalysisPanel() {
options={[ options={[
{ label: '案件总数', value: 'count' }, { label: '案件总数', value: 'count' },
{ label: '超出案量', value: 'excess' }, { label: '超出案量', value: 'excess' },
{ label: '重复发生', value: 'recurrence' }, // { label: '重复发生', value: 'recurrence' },
{ label: '近期活跃', value: 'recent' }, { label: '近期活跃', value: 'recent' },
]} ]}
/> />
...@@ -101,47 +102,47 @@ export function AnalysisPanel() { ...@@ -101,47 +102,47 @@ export function AnalysisPanel() {
<span title="单个方格的地面尺寸:越小识别越细,零散的小堆也越容易被判为黑点"> <span title="单个方格的地面尺寸:越小识别越细,零散的小堆也越容易被判为黑点">
方格边长 方格边长
</span> </span>
<Slider <ParamSlider
min={30} min={30}
max={300} max={300}
step={10} step={10}
value={params.cellMeters} value={params.cellMeters}
onChange={(v) => patch({ cellMeters: v })} onCommit={(v) => patch({ cellMeters: v })}
tooltip={{ formatter: (v) => `每格 ${v} 米见方` }} tooltip={{ formatter: (v) => `每格 ${v} 米见方` }}
/> />
</div> </div>
<div className="hm-adv__row"> {/* <div className="hm-adv__row">
<span title="统计某个方格时,并入多大范围内的案件一起比较,决定「集中」按多大一片计算"> <span title="统计某个方格时,并入多大范围内的案件一起比较,决定「集中」按多大一片计算">
集中范围 集中范围
</span> </span>
<Slider <ParamSlider
min={params.cellMeters} min={params.cellMeters}
max={1200} max={1200}
step={50} step={50}
value={params.smoothMeters} value={params.smoothMeters}
onChange={(v) => patch({ smoothMeters: v })} onCommit={(v) => patch({ smoothMeters: v })}
tooltip={{ formatter: (v) => `并入周围 ${v} 米` }} tooltip={{ formatter: (v) => `并入周围 ${v} 米` }}
/> />
</div> </div> */}
<div className="hm-adv__row"> <div className="hm-adv__row">
<span title="一处至少要这么多案件才计入黑点,用于排除零星聚集">单片最少案件数</span> <span title="一处至少要这么多案件才计入黑点,用于排除零星聚集">单片最少案件数</span>
<Slider <ParamSlider
min={5} min={5}
max={80} max={80}
step={5} step={5}
value={params.minCount} value={params.minCount}
onChange={(v) => patch({ minCount: v })} onCommit={(v) => patch({ minCount: v })}
tooltip={{ formatter: (v) => `≥ ${v} 起` }} tooltip={{ formatter: (v) => `≥ ${v} 起` }}
/> />
</div> </div>
<div className="hm-adv__row"> <div className="hm-adv__row">
<span title="左侧清单最多显示的条数">清单条数</span> <span title="左侧清单最多显示的条数">清单条数</span>
<Slider <ParamSlider
min={6} min={6}
max={60} max={60}
step={2} step={2}
value={params.topN} value={params.topN}
onChange={(v) => patch({ topN: v })} onCommit={(v) => patch({ topN: v })}
tooltip={{ formatter: (v) => `显示前 ${v} 条` }} tooltip={{ formatter: (v) => `显示前 ${v} 条` }}
/> />
</div> </div>
......
...@@ -2,8 +2,10 @@ import { Panel, Field } from '@hm/ui'; ...@@ -2,8 +2,10 @@ import { Panel, Field } from '@hm/ui';
import { useHeatmapStore, isFilterDirty, type TimePreset } from '@/store/useHeatmapStore'; import { useHeatmapStore, isFilterDirty, type TimePreset } from '@/store/useHeatmapStore';
import { BASEMAP_OPTIONS } from '@/features/heatmap/map/palette'; import { BASEMAP_OPTIONS } from '@/features/heatmap/map/palette';
import { UNRESOLVED_LABEL } from '@/features/heatmap/aggregate/types'; import { UNRESOLVED_LABEL } from '@/features/heatmap/aggregate/types';
import { DatePicker, Input, Segmented, Select, Slider, Switch, Button } from 'antd'; import { DatePicker, Input, Segmented, Select, Switch, Button } from 'antd';
import dayjs, { type Dayjs } from 'dayjs'; import dayjs, { type Dayjs } from 'dayjs';
import { useEffect, useMemo, useRef, useState } from 'react';
import { ParamSlider } from './ParamSlider';
import { ReloadOutlined } from '@ant-design/icons'; import { ReloadOutlined } from '@ant-design/icons';
const DAY = 86400; const DAY = 86400;
...@@ -26,21 +28,32 @@ export function FilterPanel() { ...@@ -26,21 +28,32 @@ export function FilterPanel() {
const timePreset = useHeatmapStore((s) => s.timePreset); const timePreset = useHeatmapStore((s) => s.timePreset);
const basemap = useHeatmapStore((s) => s.basemap); const basemap = useHeatmapStore((s) => s.basemap);
const layerVisible = useHeatmapStore((s) => s.layerVisible); const layerVisible = useHeatmapStore((s) => s.layerVisible);
const heatRadius = useHeatmapStore((s) => s.heatRadius);
const heatOpacity = useHeatmapStore((s) => s.heatOpacity);
const showNumbers = useHeatmapStore((s) => s.showNumbers); const showNumbers = useHeatmapStore((s) => s.showNumbers);
const setTimeRange = useHeatmapStore((s) => s.setTimeRange); const setTimeRange = useHeatmapStore((s) => s.setTimeRange);
const setDistricts = useHeatmapStore((s) => s.setDistricts); const setDistricts = useHeatmapStore((s) => s.setDistricts);
const setKeyword = useHeatmapStore((s) => s.setKeyword);
const setBasemap = useHeatmapStore((s) => s.setBasemap); const setBasemap = useHeatmapStore((s) => s.setBasemap);
const toggleLayer = useHeatmapStore((s) => s.toggleLayer); const toggleLayer = useHeatmapStore((s) => s.toggleLayer);
const setHeatStyle = useHeatmapStore((s) => s.setHeatStyle);
const setShowNumbers = useHeatmapStore((s) => s.setShowNumbers); const setShowNumbers = useHeatmapStore((s) => s.setShowNumbers);
const resetFilter = useHeatmapStore((s) => s.resetFilter); const resetFilter = useHeatmapStore((s) => s.resetFilter);
const dirty = isFilterDirty({ meta, filter }); const dirty = isFilterDirty({ meta, filter });
/**
* 区名单的选项表。
*
* 名单只在「换了一刀数据」时才变,所以留一份就够:每次渲染现 map 一遍的话,
* Select 会把整列选项从头比一遍,而这一栏正挨着那两根会连发几十次的控件。
*/
const districtOptions = useMemo(
() =>
(meta?.dict.districts ?? []).map((name, idx) => ({
label: name === UNRESOLVED_LABEL ? '未标注行政区' : name,
value: idx,
})),
[meta],
);
const onPreset = (value: string) => { const onPreset = (value: string) => {
if (!meta) return; if (!meta) return;
const max = meta.timeRange.max; const max = meta.timeRange.max;
...@@ -123,20 +136,12 @@ export function FilterPanel() { ...@@ -123,20 +136,12 @@ export function FilterPanel() {
} }
value={filter.districts} value={filter.districts}
onChange={(v) => setDistricts(v as number[])} onChange={(v) => setDistricts(v as number[])}
options={(meta?.dict.districts ?? []).map((name, idx) => ({ options={districtOptions}
label: name === UNRESOLVED_LABEL ? '未标注行政区' : name,
value: idx,
}))}
/> />
</Field> </Field>
<Field label="关键词检索" tooltip="匹配案件号 / 出险地点"> <Field label="关键词检索" tooltip="匹配案件号 / 出险地点">
<Input.Search <KeywordField />
allowClear
placeholder="如:道路、大厦、车牌片段"
value={filter.keyword}
onChange={(e) => setKeyword(e.target.value)}
/>
</Field> </Field>
<Field label="热力图层" active={layerVisible.heat}> <Field label="热力图层" active={layerVisible.heat}>
...@@ -152,31 +157,7 @@ export function FilterPanel() { ...@@ -152,31 +157,7 @@ export function FilterPanel() {
</div> </div>
</Field> </Field>
{layerVisible.heat && ( {layerVisible.heat && <HeatStyleFields />}
<>
<Field label="热力扩散范围" tooltip={`单个案件向周边扩散的像素范围:${heatRadius} 像素`}>
<Slider
min={12}
max={90}
step={2}
value={heatRadius}
onChange={(v) => setHeatStyle({ radius: v })}
/>
</Field>
<Field
label="热力底色强度"
tooltip={`${Math.round(heatOpacity * 100)}% —— 数值越低,底图路网越清晰`}
>
<Slider
min={0.2}
max={1}
step={0.02}
value={heatOpacity}
onChange={(v) => setHeatStyle({ opacity: v })}
/>
</Field>
</>
)}
<Field label="屏幕方格计数" active={layerVisible.cluster}> <Field label="屏幕方格计数" active={layerVisible.cluster}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}> <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
...@@ -203,9 +184,108 @@ export function FilterPanel() { ...@@ -203,9 +184,108 @@ export function FilterPanel() {
style={{ width: '100%' }} style={{ width: '100%' }}
value={basemap} value={basemap}
onChange={setBasemap} onChange={setBasemap}
options={BASEMAP_OPTIONS.map((o) => ({ label: o.label, value: o.value }))} options={BASEMAP_SELECT_OPTIONS}
/> />
</Field> </Field>
</Panel> </Panel>
); );
} }
/** 选项表留在模块层:每次渲染现 map 一份,antd 会把整列选项重新比一遍 */
const BASEMAP_SELECT_OPTIONS = BASEMAP_OPTIONS.map((o) => ({ label: o.label, value: o.value }));
/**
* 关键词那一栏。
*
* 打字不停不筛:命中判据是把每条记录的案件号与地点文本都扫一遍,几十万记录扫一次是
* 实打实的几百毫秒主线程占用,而「深圳」刚打了第一个字时那批结果没人要看 ——
* 它只是把界面按在那里。停顿之后自动生效,不必按回车;点 ✕ 是撤销这个条件,当场生效。
*
* 输入框自己不写进 store:它写进去的是「已经生效的条件」,屏上显示的才是打字中的那一截。
* 「回到全市」那种外部清空会经由 value 跟回来。
*/
function KeywordField() {
const keyword = useHeatmapStore((s) => s.filter.keyword);
const setKeyword = useHeatmapStore((s) => s.setKeyword);
const [text, setText] = useState(keyword);
const timer = useRef<number | null>(null);
// 外部改了条件(回到全市 / 清空筛选)时输入框要跟上
useEffect(() => setText(keyword), [keyword]);
useEffect(
() => () => {
if (timer.current) window.clearTimeout(timer.current);
},
[],
);
/** 停顿多久才去扫一遍。比统计那 160ms 的防抖长一点:打字的速度本来就比这个慢 */
const commit = (next: string, immediate = false) => {
if (timer.current) window.clearTimeout(timer.current);
timer.current = null;
if (immediate) {
setKeyword(next);
return;
}
timer.current = window.setTimeout(() => {
timer.current = null;
setKeyword(next);
}, 320);
};
return (
<Input.Search
allowClear
placeholder="如:道路、大厦、车牌片段"
value={text}
onChange={(e) => {
setText(e.target.value);
// ✕ 清空是「撤销这个条件」,不该再等半秒
commit(e.target.value, e.target.value === '');
}}
onSearch={() => commit(text.trim(), true)}
/>
);
}
/**
* 热力扩散范围 / 底色强度两根滑杆。
*
* 用 ParamSlider(松手才写出去)的理由在这里格外实在:每一次改动都要高德那块热力底色
* 把半径或透明度整个换一遍、整片重画,而底色是铺满全屏的那一层。
* 拖动的过程里屏上的数字照走,底色松手才换。
*/
function HeatStyleFields() {
const heatRadius = useHeatmapStore((s) => s.heatRadius);
const heatOpacity = useHeatmapStore((s) => s.heatOpacity);
const setHeatStyle = useHeatmapStore((s) => s.setHeatStyle);
return (
<>
<Field
label="热力扩散范围"
tooltip={`单个案件向周边扩散的像素范围:${heatRadius} 像素(松手后生效)`}
>
<ParamSlider
min={12}
max={90}
step={2}
value={heatRadius}
onCommit={(v) => setHeatStyle({ radius: v })}
/>
</Field>
<Field
label="热力底色强度"
tooltip={`${Math.round(heatOpacity * 100)}% —— 数值越低,底图路网越清晰(松手后生效)`}
>
<ParamSlider
min={0.2}
max={1}
step={0.02}
value={heatOpacity}
onCommit={(v) => setHeatStyle({ opacity: v })}
/>
</Field>
</>
);
}
import { memo } from 'react';
import { Panel } from '@hm/ui'; import { Panel } from '@hm/ui';
import { useHeatmapStore } from '@/store/useHeatmapStore'; import { useHeatmapStore } from '@/store/useHeatmapStore';
import { fmtCompact, fmtInt, placeNameOf } from '@/utils/format'; import { fmtCompact, fmtInt, placeNameOf } from '@/utils/format';
...@@ -229,8 +230,23 @@ export function HotspotPanel() { ...@@ -229,8 +230,23 @@ export function HotspotPanel() {
); );
} }
/** 迷你趋势线。用 svg 而不是 antd 图表:一行只有几像素高,任何图表库的默认边距都会撑破列表 */ /**
function Spark({ values, color, max }: { values: number[]; color: string; max: number }) { * 迷你趋势线。用 svg 而不是 antd 图表:一行只有几像素高,任何图表库的默认边距都会撑破列表
*
* memo 过一次:一张线要按 `values` 逐点算一遍字符串(统计期半年就是一行 180 次),
* 而清单几十行摆在一起就是几千次。点一行选中别的黑点时,整栏都会重渲染,
* 但这一批 values / max 还是那一份分析结果里的同一个数组 —— 引用没变就不必重画。
* 少了这一层,「点一行、整栏顿一下」是必然的。
*/
const Spark = memo(function Spark({
values,
color,
max,
}: {
values: number[];
color: string;
max: number;
}) {
const n = values.length; const n = values.length;
if (n < 2 || max <= 0) return null; if (n < 2 || max <= 0) return null;
const w = 132; const w = 132;
...@@ -255,4 +271,4 @@ function Spark({ values, color, max }: { values: number[]; color: string; max: n ...@@ -255,4 +271,4 @@ function Spark({ values, color, max }: { values: number[]; color: string; max: n
/> />
</svg> </svg>
); );
} });
import { Slider } from 'antd';
import { useState, type ComponentProps } from 'react';
/**
* 一根「拖的时候只改自己、松手才交出去」的滑杆。
*
* 为什么不边拖边写全局状态:这类杆子一次拖到底能连发几十到上百次读数,
* 而每一次写进去都带着「把几十万点重算一遍」或者「把整片热力底色重画一遍」。
* 界面上看着只是动了一根细条,主线程那边却排了几十到上百次重活 ——
* 这正是「动哪儿都卡」里最容易被忽略的一种,因为它只在拖的时候发生,截图看不出来。
*
* 屏上那个跟随手指的读数照旧(本地这一截),代价是底图上的效果松手才换。
* 换来的是滑杆本身跟手、地图不再被反复打断。
*
* 两条既有的说法因此写进了悬浮提示里(「松手后生效」),不让人以为杆子坏了。
*/
export function ParamSlider({
value,
onCommit,
min,
max,
step,
marks,
tooltip,
}: {
value: number;
onCommit: (v: number) => void;
min: number;
max: number;
step: number;
marks?: ComponentProps<typeof Slider>['marks'];
tooltip?: ComponentProps<typeof Slider>['tooltip'];
}) {
// null = 没在拖。拖的那一段用本地值,松手写出去之后清掉,此后以 store 为准
const [draft, setDraft] = useState<number | null>(null);
return (
<Slider
min={min}
max={max}
step={step}
marks={marks}
tooltip={tooltip}
value={draft ?? value}
onChange={(v) => setDraft(v)}
onChangeComplete={(v) => {
setDraft(null);
onCommit(v);
}}
/>
);
}
import { useMemo } from 'react';
import { useHeatmapStore, type SpotlightKind, type StatsBoard } from '@/store/useHeatmapStore'; import { useHeatmapStore, type SpotlightKind, type StatsBoard } from '@/store/useHeatmapStore';
import { UnresolvedRow } from './StatsPanel'; import { UnresolvedRow } from './StatsPanel';
import { TimeBoard } from './TimeBoard'; import { TimeBoard } from './TimeBoard';
...@@ -134,7 +135,14 @@ export function StatsBoardDrawer() { ...@@ -134,7 +135,14 @@ export function StatsBoardDrawer() {
const cfg = rankKey ? RANKINGS[rankKey] : null; const cfg = rankKey ? RANKINGS[rankKey] : null;
const matched = stats?.matched ?? 0; const matched = stats?.matched ?? 0;
const rows: Row[] = (() => { /**
* 榜的行只在这三样任一真的换了时才算一遍。
*
* 「查看全部」铺的是整张表的全部条目:街道榜几千条是常态,每条都要取字典、拆区名。
* 这张抽屉还挂在别的状态上(翻一页、开关聚焦、进度回报),放在 render 里就是
* 每翻一页把几千条重铺一遍 —— 表格里明明只看得见 20 行。
*/
const rows: Row[] = useMemo(() => {
if (!rankKey || !meta) return []; if (!rankKey || !meta) return [];
if (rankKey === 'districts') { if (rankKey === 'districts') {
return (stats?.districtCounts ?? []).map(([idx, n], i) => ({ return (stats?.districtCounts ?? []).map(([idx, n], i) => ({
...@@ -172,7 +180,7 @@ export function StatsBoardDrawer() { ...@@ -172,7 +180,7 @@ export function StatsBoardDrawer() {
parent: '', parent: '',
count: n, count: n,
})); }));
})(); }, [rankKey, meta, stats]);
// 条形只在这张榜排出的名次里归一(榜首 = 满格);榜末「读不出名字」那一档不进这把尺子, // 条形只在这张榜排出的名次里归一(榜首 = 满格);榜末「读不出名字」那一档不进这把尺子,
// 它也只报起数 —— 与面板三条榜同一口径,理由见 design.css 的 .hm-splitbar__unresolved // 它也只报起数 —— 与面板三条榜同一口径,理由见 design.css 的 .hm-splitbar__unresolved
...@@ -240,7 +248,12 @@ export function StatsBoardDrawer() { ...@@ -240,7 +248,12 @@ export function StatsBoardDrawer() {
openRoster(roadRoster(stats?.road?.names ?? [], r.idx)); openRoster(roadRoster(stats?.road?.names ?? [], r.idx));
}; };
const unresolvedDistrictIdx = meta ? meta.dict.districts.indexOf(UNRESOLVED_LABEL) : -1; const unresolvedDistrictIdx = meta ? meta.dict.districts.indexOf(UNRESOLVED_LABEL) : -1;
const unresolvedStreets = meta ? unresolvedStreetIdx(meta.dict.streets) : []; // 街道字典里「未标注」那一组下标:要扫完整份字典才数得齐(每个区都可能有一项),
// 而它只由 meta 决定 —— 放在 render 里就是这张榜每翻一页重扫一遍几千条街名
const unresolvedStreets = useMemo(
() => (meta ? unresolvedStreetIdx(meta.dict.streets) : []),
[meta],
);
const openUnresolvedRoster = () => { const openUnresolvedRoster = () => {
if (rankKey === 'districts') { if (rankKey === 'districts') {
if (unresolvedDistrictIdx < 0) return; if (unresolvedDistrictIdx < 0) return;
......
...@@ -58,8 +58,6 @@ export function StatsPanel() { ...@@ -58,8 +58,6 @@ export function StatsPanel() {
const detailReady = useHeatmapStore((s) => s.detailReady); const detailReady = useHeatmapStore((s) => s.detailReady);
const openStatsBoard = useHeatmapStore((s) => s.openStatsBoard); const openStatsBoard = useHeatmapStore((s) => s.openStatsBoard);
const openRoster = useHeatmapStore((s) => s.openRoster); const openRoster = useHeatmapStore((s) => s.openRoster);
const openPointRoster = useHeatmapStore((s) => s.openPointRoster);
const perf = useHeatmapStore((s) => s.perf);
if (!meta) { if (!meta) {
return ( return (
...@@ -195,16 +193,9 @@ export function StatsPanel() { ...@@ -195,16 +193,9 @@ export function StatsPanel() {
tip="点开看这些案件的清单,可在清单里再按区、街道、时间、关键词收窄" tip="点开看这些案件的清单,可在清单里再按区、街道、时间、关键词收窄"
/> />
{/* 点位数说的是屏幕上划了多少个方格,点进去列的就该是方格本身(一行一格), {/* 点位数说的是屏幕上划了多少个方格,点进去列的就该是方格本身(一行一格),
而不是案件 —— 拿这两个数去对一份案件清单,永远对不上 */} 而不是案件 —— 拿这两个数去对一份案件清单,永远对不上。
<StatTile 这一块自己订阅自己换数,理由见文件末尾的 HeatPointTile */}
label="热力点位数" <HeatPointTile />
value={fmtInt(perf.clusterBuckets)}
hint={`平均 ${perf.avgPerBucket} 起/点位`}
onClick={
perf.clusterBuckets > 0 ? () => openPointRoster('热力点位 · 屏幕上的方格') : undefined
}
tip="点开看屏幕上这批方格,一行一个格子,报的是格子里的案件数"
/>
</StatGrid> </StatGrid>
<div style={{ marginTop: 16 }}> <div style={{ marginTop: 16 }}>
...@@ -347,8 +338,8 @@ export function StatsPanel() { ...@@ -347,8 +338,8 @@ export function StatsPanel() {
各区的时段形状(案件最多的 {crossRows.length} 个区) 各区的时段形状(案件最多的 {crossRows.length} 个区)
</SectionTitle> </SectionTitle>
<div className="hm-field__tip" style={{ marginBottom: 8 }}> <div className="hm-field__tip" style={{ marginBottom: 8 }}>
格子里的数字是这一段占本区全天案件的比重; 格子里的数字是这一段占本区全天案件的比重; 最后一列是夜间(晚 10 点到次日早 6
最后一列是夜间(晚 10 点到次日早 6 点)占本区的比重。没有案子的格子不涂色。 点)占本区的比重。没有案子的格子不涂色。
读不出行政区的那些记录不在表内,起数在上一张榜末单列。点一格看这一区这一时段的清单。 读不出行政区的那些记录不在表内,起数在上一张榜末单列。点一格看这一区这一时段的清单。
</div> </div>
<div className="hm-cross"> <div className="hm-cross">
...@@ -703,15 +694,60 @@ export function StatsPanel() { ...@@ -703,15 +694,60 @@ export function StatsPanel() {
)} )}
</div> </div>
<PerfFootlines />
</Panel>
);
}
/**
* 「热力点位数」那一块。
*
* 它单独成一个组件,只为一件事:这个数每拖一次地图、每改一次筛选就换一次。
* 面板原先整份订阅 perf,于是每次聚合回来,这七块榜(区、街道、道路、反复出险的位置、
* 时段矩阵、24 小时柱)连同一个骨架屏判定全部重画一遍 ——
* 用户在那边拖地图,这边跟着一起沉,而它俩根本不在说同一件事:
* 榜上的账跟筛选走,方格数跟屏幕走。
* 拆出来之后换数的只有这一块。
*
* 订阅按字段拆开、不整份拿 perf:perf 每次 patch 都换一个新对象,整份订阅等于
* 「别处任何一个数变了这里也重画」。
*/
function HeatPointTile() {
const clusterBuckets = useHeatmapStore((s) => s.perf.clusterBuckets);
const avgPerBucket = useHeatmapStore((s) => s.perf.avgPerBucket);
const openPointRoster = useHeatmapStore((s) => s.openPointRoster);
return (
<StatTile
label="热力点位数"
value={fmtInt(clusterBuckets)}
hint={`平均 ${avgPerBucket} 起/点位`}
onClick={clusterBuckets > 0 ? () => openPointRoster('热力点位 · 屏幕上的方格') : undefined}
tip="点开看屏幕上这批方格,一行一个格子,报的是格子里的案件数"
/>
);
}
/**
* 底部那两行耗时。
*
* 与上面同一套理由:重算耗时跟着聚合走,统计耗时跟着筛选走,两样都不该拖着整屏榜重画。
*/
function PerfFootlines() {
const aggregateMs = useHeatmapStore((s) => s.perf.aggregateMs);
const statsMs = useHeatmapStore((s) => s.perf.statsMs);
return (
<>
<div className="hm-kv" style={{ marginTop: 16 }}> <div className="hm-kv" style={{ marginTop: 16 }}>
<span className="hm-kv__k">重算耗时</span> <span className="hm-kv__k">重算耗时</span>
<span className="hm-kv__v">{fmtMs(perf.aggregateMs)}</span> <span className="hm-kv__v">{fmtMs(aggregateMs)}</span>
</div> </div>
<div className="hm-kv"> <div className="hm-kv">
<span className="hm-kv__k">统计耗时</span> <span className="hm-kv__k">统计耗时</span>
<span className="hm-kv__v">{fmtMs(perf.statsMs)}</span> <span className="hm-kv__v">{fmtMs(statsMs)}</span>
</div> </div>
</Panel> </>
); );
} }
......
...@@ -105,9 +105,9 @@ export function HeaderBar() { ...@@ -105,9 +105,9 @@ export function HeaderBar() {
<BrandMark /> <BrandMark />
<div className="hm-header__divider" /> <div className="hm-header__divider" />
<div className="hm-header__context"> <div className="hm-header__context">
<div className="hm-header__context-title">风险热力图</div> <div className="hm-header__context-title">深圳车险出险位置-9月风险热力图</div>
<div className="hm-header__context-sub"> <div className="hm-header__context-sub">
智能网联监管平台 · 事故出险点位分析(热力底色 + 方格计数) 智能网联监管平台 · 事故出险点位分析
</div> </div>
</div> </div>
</div> </div>
......
...@@ -33,12 +33,12 @@ const TABS: TabDef[] = [ ...@@ -33,12 +33,12 @@ const TABS: TabDef[] = [
icon: <BarChartOutlined />, icon: <BarChartOutlined />,
hint: '区域、街道、时段的案件分布统计', hint: '区域、街道、时段的案件分布统计',
}, },
{ // {
key: 'filter', // key: 'filter',
label: '筛选与图层', // label: '筛选与图层',
icon: <FilterOutlined />, // icon: <FilterOutlined />,
hint: '时间 / 行政区 / 关键词,以及热力底色与方格数字的显示方式', // hint: '时间 / 行政区 / 关键词,以及热力底色与方格数字的显示方式',
}, // },
{ {
key: 'analysis', key: 'analysis',
label: '黑点降噪', label: '黑点降噪',
......
...@@ -6,12 +6,7 @@ import { useFullscreen } from '@/layout/useFullscreen'; ...@@ -6,12 +6,7 @@ import { useFullscreen } from '@/layout/useFullscreen';
function isTyping(el: EventTarget | null): boolean { function isTyping(el: EventTarget | null): boolean {
if (!(el instanceof HTMLElement)) return false; if (!(el instanceof HTMLElement)) return false;
const tag = el.tagName; const tag = el.tagName;
return ( return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || el.isContentEditable;
tag === 'INPUT' ||
tag === 'TEXTAREA' ||
tag === 'SELECT' ||
el.isContentEditable
);
} }
/** /**
......
...@@ -65,6 +65,33 @@ ...@@ -65,6 +65,33 @@
); );
} }
/*
* 拖动 / 缩放地图期间的那一拍:整页玻璃换成「少模糊 + 底色压实」。
*
* 为什么要单独开这一档:backdrop-filter 的开销是「每帧把它身后那块区域重新采样、
* 再按半径卷积一遍」,而这个项目底下一整块全屏 WebGL 地图。地图一动,顶栏(整屏宽)、
* 右栏面板、左侧清单、三个把手、图例、读数胶囊、抽屉全都要各自重模糊一次,
* 半径还是 20px —— 这是拖动卡顿里最大的一笔单项开销,而且它跟数据量无关,空图也卡。
*
* 类名由地图的手势事件挂 / 摘(见 MapStage 的 hm-map-busy 那段),松手后过一拍才恢复,
* 因为松手紧接着就是重新聚合与重喂热力。静止时的外观与原来完全一致,这一档只在按住时存在。
*
* 底色同步压实是必要的:只把模糊拿掉会让玻璃在移动中的地图上读成「变透明」,
* 而移动中的底色本来就读不出细节 —— 宁可玻璃实在一点。
* 4px 而不是 0:留着这一档,静止与拖动之间不会跳成两种材质。
*/
html.hm-map-busy {
--hm-glass-blur: blur(4px) saturate(150%);
--hm-glass-side: rgba(255, 255, 255, 0.84);
--hm-glass-side-strong: rgba(255, 255, 255, 0.9);
--hm-glass-drawer: rgba(255, 255, 255, 0.88);
--hm-glass-header: linear-gradient(
180deg,
rgba(30, 41, 82, 0.93) 0%,
rgba(38, 50, 96, 0.86) 100%
);
}
* { * {
box-sizing: border-box; box-sizing: border-box;
} }
......
...@@ -53,7 +53,11 @@ export const themeConfig: ThemeConfig = { ...@@ -53,7 +53,11 @@ export const themeConfig: ThemeConfig = {
Card: { borderRadiusLG: 14 }, Card: { borderRadiusLG: 14 },
Slider: { railBg: PALETTE.divider, railHoverBg: PALETTE.primarySoft, trackBg: PALETTE.primary }, Slider: { railBg: PALETTE.divider, railHoverBg: PALETTE.primarySoft, trackBg: PALETTE.primary },
Segmented: { itemSelectedBg: PALETTE.primary, itemSelectedColor: '#fff' }, Segmented: { itemSelectedBg: PALETTE.primary, itemSelectedColor: '#fff' },
Table: { headerBg: PALETTE.surfaceSunken ?? '#FAFBFD', headerColor: PALETTE.text2, rowHoverBg: 'rgba(70,83,162,.05)' }, Table: {
headerBg: PALETTE.surfaceSunken ?? '#FAFBFD',
headerColor: PALETTE.text2,
rowHoverBg: 'rgba(70,83,162,.05)',
},
Drawer: { paddingLG: 16 }, Drawer: { paddingLG: 16 },
Select: { optionSelectedBg: 'rgba(70,83,162,.1)' }, Select: { optionSelectedBg: 'rgba(70,83,162,.1)' },
Tag: { defaultBg: 'rgba(70,83,162,.08)', defaultColor: PALETTE.primary }, Tag: { defaultBg: 'rgba(70,83,162,.08)', defaultColor: PALETTE.primary },
......
...@@ -67,7 +67,12 @@ declare namespace AMap { ...@@ -67,7 +67,12 @@ declare namespace AMap {
setCenter(center: [number, number]): void; setCenter(center: [number, number]): void;
getCenter(): LngLat; getCenter(): LngLat;
setMapStyle(style: string): void; setMapStyle(style: string): void;
setFitView(overlays?: unknown[], immediately?: boolean, avoid?: number[], maxZoom?: number): void; setFitView(
overlays?: unknown[],
immediately?: boolean,
avoid?: number[],
maxZoom?: number,
): void;
getBounds(): Bounds; getBounds(): Bounds;
getSize(): Size; getSize(): Size;
getContainer(): HTMLElement; getContainer(): HTMLElement;
......
...@@ -36,8 +36,18 @@ export function spanDays(from: number, to: number): number { ...@@ -36,8 +36,18 @@ export function spanDays(from: number, to: number): number {
return Math.max(0, dayOf(to) - dayOf(from) + 1); return Math.max(0, dayOf(to) - dayOf(from) + 1);
} }
/**
* 千分位。
*
* 底下那台 Intl 格式化器只建一次:`n.toLocaleString('zh-CN')` 每次调用都要现查一遍
* 当前语言环境的数字规则,而这一支是全屏最热的格式化函数 —— 地图上每一格的数字
* (每拖一次地图重算几百到两千个)、每一条榜、抽屉里每一行都走它。
* 实测把格式化器留着复用,同样的数排下来省掉的是「每行一次环境查找」。
*/
const INT_FORMATTER = new Intl.NumberFormat('zh-CN');
export function fmtInt(n: number): string { export function fmtInt(n: number): string {
return n.toLocaleString('zh-CN'); return INT_FORMATTER.format(n);
} }
/** 大数压缩:图上数字与指标块共用同一套压缩规则,避免同页出现 12,345 与 1.2万 两种写法 */ /** 大数压缩:图上数字与指标块共用同一套压缩规则,避免同页出现 12,345 与 1.2万 两种写法 */
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!