TimeBoard.tsx
20.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
import { useMemo } from 'react';
import { Segmented, Table } from 'antd';
import { useHeatmapStore, type TimeDim, type TimeShape } from '@/store/useHeatmapStore';
import { StatGrid, StatTile } from '@hm/ui';
import { TimeChart, type ChartSlot } from './TimeChart';
import { HelpDot } from './HelpDot';
import { RANK_COLORS } from '@/features/heatmap/map/palette';
import { weekdayBaseline } from '@/features/heatmap/aggregate/weekdayBaseline';
import type { StatsResult } from '@/features/heatmap/aggregate/types';
import { fmtCompact, fmtDate, fmtInt, fmtPercent, hourLabel } from '@/utils/format';
const DAY = 86400;
/** 与 Worker 的 weekdayHist 同一套下标:0 = 周日(推算方式见 aggregate.worker 的按日注释) */
const WEEKDAYS = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
const DIM_OPTIONS: Array<{ label: string; value: TimeDim }> = [
{ label: '按天', value: 'day' },
{ label: '按星期', value: 'weekday' },
{ label: '按小时', value: 'hour' },
];
/** 顺序照默认值排:折线是默认(store 里写了为什么),要换形态时它不该藏在第二格 */
const SHAPE_OPTIONS: Array<{ label: string; value: TimeShape }> = [
{ label: '折线图', value: 'line' },
{ label: '柱状图', value: 'bar' },
{ label: '清单', value: 'list' },
];
/** 图里的一档,外加清单要用的两列文字 */
interface Slot extends ChartSlot {
/** 清单第一列:日期 / 星期几 / 时段起点 */
name: string;
/** 清单第二列:只有按天有内容(那天是星期几),其余维度留空并把整列隐掉 */
sub: string;
}
/** 一种切法的全部说法:档位、参照平均、列头、两句解释 */
interface DimView {
slots: Slot[];
mean: number;
/** 虚线的名字,同时也是「比多少倍」的参照物 */
meanWord: string;
/** 清单第一列的表头 */
nameColumn: string;
/** 单位量词:清单表脚「共 N 天 / 7 档 / 24 档」 */
unit: string;
/** 没人悬停时读数行说什么 */
idle: string;
/** 图下面那句口径说明 */
foot: string;
}
/**
* 时间规律:把命中记录按天 / 按星期 / 按小时重排,让人能读数、能点进去。
*
* 它就长在「风险概览 · 时间规律」那个页签里(compact = true,右栏 372px)。
* 原先面板上只画 24 小时的形状、完整读数要另开「查看全部」抽屉 —— 抽屉要跳一次、
* 面板那一块又说不出数,等于同一件事分两处说。现在整块搬进页签,不再有那颗入口。
*
* 一次只看一种切法。372px 更放不下第二种维度并排:一次只有一个问题,切换比并列好用。
*
* 形态(柱状 / 折线 / 清单)读的是同一批数字,柱子长短、折线起伏、清单条目三者可互相印证:
* 觉得图上有异常,切清单逐个确认;想看清走势,切折线。
* 所以维度和形态都存在 store 里,换抽屉、开关抽屉都不重置(见 store 的 timeDim / timeShape)——
* 排查一个时段要看几十次,每次都从默认值重来是纯粹的打扰。
*
* 条形与柱子的高度只在本维度内归一(本维度最高的一档 = 满格):一天和一小时不是同一把尺子,
* 跨维度比长短会读成「按天的柱子更高,所以按天更要紧」。
* 占比的分母三处都一样,都是当前筛选的命中数,所以任何一档都能和「命中案件」那个数对上。
*
* 每一档都点得开:图在说的是「这一段时间里出了几起」,而看到这句话的下一句一定是
* 「那这几起是什么」,所以它们都接到同一份案件清单上。只有 0 起的那一档不接 ——
* 那里没有清单可列,点了给一张空抽屉不如不给那只手型。
*/
export function TimeBoard({ compact = false }: { compact?: boolean }) {
const stats = useHeatmapStore((s) => s.stats);
const dim = useHeatmapStore((s) => s.timeDim);
const shape = useHeatmapStore((s) => s.timeShape);
const setTimeDim = useHeatmapStore((s) => s.setTimeDim);
const setTimeShape = useHeatmapStore((s) => s.setTimeShape);
const openRoster = useHeatmapStore((s) => s.openRoster);
// 建档位要打开清单的回调,回调又来自 openRoster,所以整段放一个 useMemo 里;
// 放在组件顶层写的话,每次渲染都重建几百个箭头函数,抽屉里的 hover 会跟着变钝
const view = useMemo(
() => (stats ? buildView(stats, dim, openRoster) : null),
[stats, dim, openRoster],
);
if (!stats || !view) return null;
const matched = stats.matched;
const dayCount = stats.daily.length;
const avgPerDay = dayCount ? matched / dayCount : 0;
// daily 下标 0 是北京时间哪一天:dayStart 里已经折过时区偏移,再对时间戳除一次就会错一天
const dayBase = Math.floor((stats.dayStart + 8 * 3600) / DAY);
const daySec = (dayNumber: number) => dayNumber * DAY - 8 * 3600;
// 「最多的一天」讲的是按天那一档,不跟着上面的切换变,所以标签自己从 daily 推:
// 拿 view.slots 的下标去取会串到星期/时段的档位上,念出来就是「最多的一天:周三」
const peakDayIndex = stats.daily.reduce((best, n, i) => (n > stats.daily[best] ? i : best), 0);
const peakDayCount = stats.daily[peakDayIndex] ?? 0;
const peakDayNumber = dayBase + peakDayIndex;
const peakDayLabel =
peakDayCount > 0
? `${fmtDate(daySec(peakDayNumber))} ${WEEKDAYS[(peakDayNumber + 4) % 7]}`
: '';
const peakHourCount = stats.hourHist[stats.peakHour] ?? 0;
const peakHourLabel = `${hourLabel(stats.peakHour)}—${hourLabel((stats.peakHour + 1) % 24)}`;
/**
* 「最近这一周比上一周多还是少」—— 日均只回答平均水平,决策要的是方向:
* 同样日均 550 起,一路在爬和一路在退是两件事。数据里已经有逐日计数,
* 不必回 Worker 再扫一遍,所以就在这一块读数上补一句。
*
* 窗口跟着数据走、上限 7 天;凑不满两个窗口就只报这一段的量,不报百分比 ——
* 拿 3 天和 6 天比出来的数只是噪声,宁可少说一句。
*/
const recentDays = Math.min(7, dayCount);
const sum = (arr: number[]) => arr.reduce((a, b) => a + b, 0);
const recentCount = sum(stats.daily.slice(-recentDays));
const priorSlice = stats.daily.slice(-2 * recentDays, -recentDays);
const hasPrior = priorSlice.length === recentDays;
const priorCount = sum(priorSlice);
const trendWord = (() => {
if (!hasPrior) return '';
if (priorCount === 0) return recentCount > 0 ? '此前为 0' : '持平';
const ratio = recentCount / priorCount - 1;
if (Math.abs(ratio) < 0.05) return '基本持平';
return `${ratio > 0 ? '多' : '少'}${Math.round(Math.abs(ratio) * 100)}%`;
})();
const avgHint = trendWord
? `近 ${recentDays} 天 ${fmtInt(recentCount)} 起,比前 ${recentDays} 天${trendWord}`
: `${fmtInt(matched)} 起 ÷ ${fmtInt(dayCount)} 天`;
/**
* 顶上这四块读数和下面的图同源(都是同一份 stats),所以它们也点得开:
* 「最多的一天 412 起」看完,下一句一定是「这几起是什么」—— 与图上一列的点法完全一致,
* 切法(pick / where)也一致,不会出现「从数字点进去和从柱子上点进去是两份名单」。
*/
const openPeakDay = () => {
const from = daySec(peakDayNumber);
const to = from + DAY - 1;
openRoster({
source: `时间分布 · ${peakDayLabel}`,
pick: { from, to },
mapScope: { from, to },
});
};
const openPeakHour = () =>
openRoster({ source: `时间分布 · ${peakHourLabel}`, where: { hours: [stats.peakHour] } });
return (
<>
{/* 窄处(右栏 372px)两块一行:四块横排在 372 里每块只剩 80 多,
数字与其说明会挤成两行,扫读时反而找不到「最多的一天」在哪儿 */}
<StatGrid columns={compact ? 2 : 4}>
<StatTile
label="统计天数"
value={fmtInt(dayCount)}
unit="天"
hint={
dayCount
? `${fmtDate(daySec(dayBase))} ~ ${fmtDate(daySec(dayBase + dayCount - 1))}`
: '当前筛选没有记录'
}
onClick={
dayCount > 0
? () => {
// 点它不是再开一份清单,而是把下面那块图换成「一天一行」的表:
// 想知道的已经是这些天分别是谁,抽屉里换形态比另开一张窗少一步跳转
setTimeDim('day');
setTimeShape('list');
}
: undefined
}
tip="这段数据的起止日期(按北京时间自然日);点开逐日罗列,一天一行,可排序可翻页"
/>
<StatTile
label="日均案件"
value={fmtCompact(Math.round(avgPerDay))}
unit="起"
tone="primary"
hint={avgHint}
tip={
hasPrior
? `整段数据的平均量;后半句是最近 ${recentDays} 天与前面同样长一段时间的比较`
: `整段数据的平均量;数据不满 ${recentDays * 2} 天,先不给增减方向`
}
/>
<StatTile
label="最多的一天"
value={peakDayCount > 0 ? fmtCompact(peakDayCount) : '—'}
unit="起"
hint={peakDayLabel}
onClick={peakDayCount > 0 ? openPeakDay : undefined}
tip="点开看这一天的案件清单,可以在清单里再按区、街道、关键词收窄"
/>
<StatTile
label="最集中的时段"
value={hourLabel(stats.peakHour)}
hint={`${fmtInt(peakHourCount)} 起 · 占命中 ${fmtPercent(peakHourCount, matched)}`}
onClick={peakHourCount > 0 ? openPeakHour : undefined}
tip={`点开看 ${peakHourLabel} 这一小时的案件清单`}
/>
</StatGrid>
{/* 两组切换:一行一个问题(怎么切 / 怎么看),标签定宽在左、分段铺满右侧。
竖排而不是并排:右栏只有 372px,两组并排时每组剩不到 150px,
三个选项会互相挤;竖排让每一组独占整行,点击面积也更大。
整块装进一张白卡、两行之间用一条发丝线分开 —— 它是一组「读法设置」,
不是又一段正文,卡片的边界把这句话说清楚。 */}
<div className="hm-time-ctl">
<div className="hm-time-ctl__row">
<span className="hm-time-ctl__label">怎么切</span>
<Segmented
className="hm-time-ctl__seg"
size="small"
options={DIM_OPTIONS}
value={dim}
onChange={(v) => setTimeDim(v as TimeDim)}
/>
</div>
<div className="hm-time-ctl__row">
<span className="hm-time-ctl__label">怎么看</span>
<Segmented
className="hm-time-ctl__seg"
size="small"
options={SHAPE_OPTIONS}
value={shape}
onChange={(v) => setTimeShape(v as TimeShape)}
/>
{/* 读法说明原先常驻在图下面,占掉两三行、把图往下压。收进「怎么看」这一行
右端的问号:它解释的是这张图怎么读,放在「怎么看」旁边正好。 */}
<HelpDot text={view.foot} label="图表读法" />
</div>
</div>
{shape === 'list' ? (
<SlotTable matched={matched} view={view} />
) : (
<div className="hm-tccard">
<TimeChart
slots={view.slots}
shape={shape}
matched={matched}
mean={view.mean}
meanWord={view.meanWord}
idle={view.idle}
/>
</div>
)}
</>
);
}
/**
* 把 stats 里的三份直方图摊成「一种切法」。
*
* 这里只负责说话和摆数,不重新统计:daily / weekdayHist / hourHist 都是 Worker 一次算完的
* (见 aggregate.worker),三份加起来都等于命中总数,所以换维度不会出现「数字自己变了」。
*/
function buildView(
stats: StatsResult,
dim: TimeDim,
openRoster: ReturnType<typeof useHeatmapStore.getState>['openRoster'],
): DimView {
const matched = stats.matched;
if (dim === 'weekday') {
// 期望按「这个星期几在这段窗口里出现了几天」摊,不是 matched / 7(推导见 weekdayBaseline)
const expected = weekdayBaseline(matched, stats.weekdayDays);
const slots: Slot[] = stats.weekdayHist.map((count, w) => ({
key: `w${w}`,
name: WEEKDAYS[w],
sub: '',
label: WEEKDAYS[w],
tick: WEEKDAYS[w],
count,
baseline: expected[w],
// 星期不是时间区间,右侧筛选表达不了,只能作为清单的固定约束(见 RosterWhere)
open: () => openRoster({ source: `时间分布 · ${WEEKDAYS[w]}`, where: { weekdays: [w] } }),
}));
return {
slots,
mean: matched / 7,
meanWord: '各星期平均',
nameColumn: '星期',
unit: '档',
idle: `一周七档,合计 ${fmtInt(matched)} 起`,
foot:
'柱子长短只与星期里最高的一档比;虚线是「这种星期几平时多少起」——' +
'按这段时间里各星期几出现的天数折算,不是七档平分。跨过它就是比这种日子平时多。' +
'点一列看那个星期几的案件清单。',
};
}
if (dim === 'hour') {
const slots: Slot[] = stats.hourHist.map((count, h) => {
// 一整小时说成「08:00—09:00」,只写 08:00 会读成一个时刻而不是一个区间
const label = `${hourLabel(h)}—${hourLabel((h + 1) % 24)}`;
return {
key: `h${h}`,
name: hourLabel(h),
sub: '',
label,
tick: hourLabel(h),
count,
open: () => openRoster({ source: `时间分布 · ${label}`, where: { hours: [h] } }),
};
});
return {
slots,
mean: matched / 24,
meanWord: '时段平均',
nameColumn: '时段',
unit: '档',
idle: `一天二十四档,合计 ${fmtInt(matched)} 起`,
foot:
'柱子长短只与一天里最高的那个时段比;虚线是时段平均,跨过它就是比平均多。' +
'点一列看那个时段的案件清单。',
};
}
// 按天:daily 下标 0 对应 dayStart 那一天的「北京时间日号」,往回推日期就用它 ——
// 时区偏移在 Worker 里已经折进 dayStart,这里再对时间戳除一次就会错一天
const dayBase = Math.floor((stats.dayStart + 8 * 3600) / DAY);
let prevMonth = '';
const slots: Slot[] = stats.daily.map((count, i) => {
const dayNumber = dayBase + i;
// 北京时间自然日的起止折回 epoch 秒:日号 × 一天 − 8 小时是那天的 00:00,
// 与 Worker 按日归集用的同一条轴,清单切出来的那一天的记录才和柱子完全一致
const from = dayNumber * DAY - 8 * 3600;
const to = from + DAY - 1;
const date = fmtDate(from);
const weekday = WEEKDAYS[(dayNumber + 4) % 7];
const month = date.slice(5, 7);
const tick = month !== prevMonth ? `${Number(month)}月` : '';
prevMonth = month;
const label = `${date} ${weekday}`;
return {
key: `day-${i}`,
name: date,
sub: weekday,
label,
tick,
count,
// 按天给的是时间区间,右侧筛选有这一项,所以清单里能给「在地图上看这一天」
open: () =>
openRoster({
source: `时间分布 · ${label}`,
pick: { from, to },
mapScope: { from, to },
}),
};
});
const first = slots[0]?.label ?? '—';
const last = slots[slots.length - 1]?.label ?? '—';
return {
slots,
mean: stats.daily.length ? matched / stats.daily.length : 0,
meanWord: '日均',
nameColumn: '日期',
unit: '天',
idle: `${first} ~ ${last},每列一天`,
foot:
'柱子长短只与这段时间里最高的一天比;虚线是日均,跨过它就是比平时多。' +
'点一列看当天的案件清单。',
};
}
/**
* 清单形态:逐档读数。
*
* 用真表格而不是把图上的标签一个个写下来,是因为这里要的是「可比」:
* 表脚能排序、能翻页、每行有精确数字,图上放不下这些。
* 行的点法与图完全一致(同一份 open),所以切形态不会换语义。
*/
/** 清单的一行:档位 + 「与平均相比」这一列 */
interface SlotRow extends Slot {
ratio: number;
}
function SlotTable({ matched, view }: { matched: number; view: DimView }) {
const max = view.slots.reduce((m, s) => Math.max(m, s.count), 0);
// 分母与图上那条参照线同一份:按星期是「这种星期几平时多少起」,其余维度是全体平均。
// 表和图各算一次的话,「与各星期平均相比 0.86 倍」的同一行会在图上看起来跨过了虚线。
const baseOf = (s: Slot) => s.baseline ?? view.mean;
const rows: SlotRow[] = view.slots.map((s) => {
const b = baseOf(s);
return { ...s, ratio: b > 0 ? s.count / b : 0 };
});
return (
<Table<SlotRow>
size="small"
rowKey="key"
dataSource={rows}
pagination={{
pageSize: 20,
size: 'small',
showSizeChanger: false,
showTotal: (t) => `共 ${fmtInt(t)} ${view.unit}`,
}}
// 整行可点:这一档的名称、起数、条形说的都是同一件事,只让某一小块能点会被读成巧合
onRow={(r) => ({
onClick: () => {
// 0 起的那一档没有清单可列,但这一档必须还在表里(否则「周三一起都没有」这个事实
// 就成了「周三没统计」),所以留着行、留着 0,只是不接成能点的样子
if (r.count > 0) r.open();
},
title: r.count > 0 ? `查看${r.label}的案件清单` : `${r.label}:没有记录`,
})}
rowClassName={(r) => (r.count > 0 ? 'hm-row--link' : '')}
columns={[
{
title: view.nameColumn,
dataIndex: 'name',
width: 118,
render: (v: string) => (
<span style={{ color: 'var(--hm-text-1)', fontVariantNumeric: 'tabular-nums' }}>
{v}
</span>
),
},
// 只有按天有第二列:星期几能帮人认出「这一天是不是周末」,
// 星期、时段那两种切法这一列整列一样或整列空着,不如不收
...(view.nameColumn === '日期'
? [
{
title: '星期',
dataIndex: 'sub',
width: 72,
render: (v: string) => (
<span style={{ color: 'var(--hm-text-3)', fontSize: 12 }}>{v}</span>
),
},
]
: []),
{
title: '案件数',
dataIndex: 'count',
width: 96,
align: 'right',
sorter: (a: SlotRow, b: SlotRow) => a.count - b.count,
render: (v: number) => (
<span style={{ color: 'var(--hm-primary)', fontVariantNumeric: 'tabular-nums' }}>
{fmtCompact(v)}
</span>
),
},
{
title: '占命中',
dataIndex: 'count',
key: 'share',
width: 84,
align: 'right',
render: (v: number) => (
<span style={{ color: 'var(--hm-text-3)', fontSize: 12 }}>
{fmtPercent(v, matched)}
</span>
),
},
{
// 「与日均/七天平均/时段平均相比」:名字跟着维度走,同一把尺子才有同一个说法
title: `与${view.meanWord}相比`,
dataIndex: 'ratio',
width: 128,
align: 'right',
sorter: (a: SlotRow, b: SlotRow) => a.ratio - b.ratio,
render: (v: number) => (
<span
style={{
// 高于平均的那几行才值得跳出来:整列一样粗的话,
// 一屏几十行全是数字,眼睛找不到「哪几天不对」
color: v >= 1 ? 'var(--hm-text-1)' : 'var(--hm-text-3)',
fontVariantNumeric: 'tabular-nums',
}}
>
{v.toFixed(2)}
<em style={{ fontStyle: 'normal', fontSize: 11, marginLeft: 2 }}>倍</em>
</span>
),
},
{
title: '长短',
dataIndex: 'count',
key: 'bar',
width: 132,
render: (v: number) => (
<div className="hm-board__bar">
<div
style={{
width: `${max ? Math.max((v / max) * 100, 1.5) : 0}%`,
// 长短是这里唯一的名次编码,所以整表一种墨色(与图上的柱子同色)
background: RANK_COLORS[0],
}}
/>
</div>
),
},
]}
/>
);
}