File size: 2,202 Bytes
494c9e4
 
 
 
 
 
17037b0
494c9e4
ef04721
17037b0
 
 
3c2da0a
5b1c2f9
494c9e4
 
 
 
 
 
 
3f516d0
 
494c9e4
 
 
 
 
 
 
 
 
 
 
ef04721
 
494c9e4
3c2da0a
5b1c2f9
ef04721
494c9e4
ef04721
3c2da0a
494c9e4
 
 
 
 
 
3c2da0a
3f516d0
494c9e4
 
 
 
 
 
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
/**
 * 应用公共初始化逻辑
 * 提供 start.ts 和 compare.ts 共享的基础初始化功能
 */

import * as d3 from 'd3';
import { SimpleEventHandler } from './core/SimpleEventHandler';
import { TextAnalysisAPI } from './api/GLTR_API';
import { resolveApiBase } from './api/resolveApiBase';
import { initForceNarrowFromStorage } from './core/responsive';
import { getTokenSurprisalColor, getByteSurprisalColor, HISTOGRAM_MIN_ALPHA } from './cross/SurprisalColorConfig';
import { initClientActivityPing } from './core/clientActivityPing';
import { initOnlineCountDisplay } from './cross/onlineCountDisplay';
import { initFrontendBuildTimeDisplay } from './cross/buildTimeDisplay';

/**
 * 公共初始化返回对象
 */
export interface CommonAppContext {
    eventHandler: SimpleEventHandler;
    api: TextAnalysisAPI;
    /** 本页 API 根(meta / ?api= / 同源 '');与 TextAnalysisAPI 实例一致 */
    apiBase: string;
    tokenSurprisalColorScale: (value: number) => string;
    byteSurprisalColorScale: (value: number) => string;
    totalSurprisalFormat: (n: number | null) => string;
}

/**
 * 初始化公共应用组件
 * @param apiPrefix API 前缀(默认为空字符串)
 * @param element 事件处理器绑定的元素(默认为 document.body)
 * @returns 初始化后的公共对象
 */
export function initializeCommonApp(apiPrefix?: string, element?: Element): CommonAppContext {
    const base = apiPrefix ?? resolveApiBase();
    initForceNarrowFromStorage();
    initOnlineCountDisplay();
    initFrontendBuildTimeDisplay();
    initClientActivityPing(base);

    const api = new TextAnalysisAPI(base);

    // 使用传入的元素或默认 body 元素
    const targetElement = element || document.body;
    
    const format = d3.format('.2f');
    return {
        eventHandler: new SimpleEventHandler(targetElement),
        api,
        apiBase: base,
        tokenSurprisalColorScale: (v) => getTokenSurprisalColor(v, HISTOGRAM_MIN_ALPHA),
        byteSurprisalColorScale: (v) => getByteSurprisalColor(v, 1, HISTOGRAM_MIN_ALPHA),
        totalSurprisalFormat: (n: number | null) => n !== null && Number.isFinite(n) ? format(n) : String(n)
    };
}