detailLoader.ts
2.47 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
import { aggregateClient } from '../aggregate/aggregateClient';
import { loadDetail } from './loadData';
import { readImportedDetail } from './importedDb';
/**
* 详情列(案件号 + 详细地址)的共享加载器。
*
* 触发时机有两个,必须收敛到同一个 Promise,否则会出现「用户先点了弹窗、
* 空闲加载又跑一遍」的重复请求:
* 1) 首屏画完之后,浏览器空闲时预热(useBootstrap);
* 2) 用户点开聚合圆圈但详情还没到位时的按需加载。
*
* 数据源随导入切换:示例数据走 public/detail.json 的带进度 fetch,
* 导入数据走 IndexedDB 里的二进制列(读出来直接 transfer 给 Worker)。
* 两条路都只需要在「点开弹窗或空闲时」发生,首屏不为它买单。
*/
let inflight: Promise<void> | null = null;
let loaded = false;
let source: 'sample' | 'imported' = 'sample';
export const DETAIL_BYTES_HINT = '约 1 MB(20W 量级数据约 5 MB)';
export function setDetailSource(next: 'sample' | 'imported'): void {
source = next;
}
export async function ensureDetailLoaded(onProgress?: (ratio: number) => void): Promise<void> {
if (loaded) return;
if (inflight) return inflight;
inflight = (async () => {
if (source === 'imported') {
const detail = await readImportedDetail();
if (!detail) throw new Error('本地导入数据里没有详情列');
onProgress?.(1);
await aggregateClient.loadDetailFromColumns(detail);
} else {
const file = await loadDetail((p) => onProgress?.(p.ratio));
await aggregateClient.loadDetail(file);
}
loaded = true;
})().finally(() => {
inflight = null;
});
return inflight;
}
/** 详情列已随首屏一起就绪时(例如导入路径)直接标记完成,避免再去拉 public 文件 */
export function markDetailLoaded(): void {
loaded = true;
inflight = null;
}
/**
* 换了数据集:上一份的详情列不能算「已加载」。
*
* 聚合 Worker 换数据是重建的(见 aggregateClient.postInit),新 Worker 里案件号与
* 地址下标列都是空的。这个模块的 `loaded` 是模块级状态,不清掉的话
* `ensureDetailLoaded` 会直接返回 —— 于是清单里每一行的案件号与地址永远空着,
* 而界面没有任何地方能看出「详情列没送到」。
*/
export function resetDetailLoaded(): void {
loaded = false;
inflight = null;
}
export function isDetailLoaded(): boolean {
return loaded;
}