core.uts
2.81 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
import { logger } from "@/services/logger/index.uts";
import { IResolutionAdapter, resolutionAdapters } from "./adapter.uts";
import { initRegistry, isRegistryInitialized } from "./registry.uts";
import { resolutionState } from "./store.uts";
import { AppResolutionConfig, ResponsiveImage } from "./types/index.uts";
// ========================================================================
// 5. 核心适配逻辑 (Core Logic)
// ========================================================================
export function updateResolutionConfig() {
initRegistry();
const info = uni.getWindowInfo();
// 优先取 windowWidth,如果为 0 则取 screenWidth (物理屏幕宽)
let w = info.windowWidth;
let h = info.windowHeight;
const pr = info.pixelRatio;
// 兜底逻辑...
if (w == 0 && info.screenWidth > 0) {
w = info.screenWidth;
if (info.screenHeight > 0) h = info.screenHeight;
}
if (w == 0 || h == 0) {
return;
}
const key = `${Math.round(w)}x${Math.round(h)}`;
// 使用适配器模式匹配
let adapter: IResolutionAdapter | null = null;
for (const a of resolutionAdapters) {
if (a.match(w, h)) {
adapter = a;
break;
}
}
if (adapter === null) {
// 使用 logger 服务记录日志
logger.debug(`[ResolutionAdapt] 未找到适配器,跳过配置更新`);
return;
}
// 执行适配
let target = adapter.getConfig(key);
let usedKey = key;
if (target === null) {
target = adapter.getFallback();
usedKey = `${adapter.getPrefix()}/common`;
}
if (target !== null) {
resolutionState.config = target;
resolutionState.currentKey = usedKey;
// 更新 CSS 类名
resolutionState.cssClass = adapter.getCssClass(key);
resolutionState.pixelRatio = pr;
resolutionState.windowWidth = w;
resolutionState.windowHeight = h;
logger.info(`[ResolutionAdapt] Applied config: ${usedKey}, cssClass: ${resolutionState.cssClass}`);
}
}
// ========================================================================
// 5. 钩子函数 (Hooks)
// ========================================================================
export function useResolutionConfig() : AppResolutionConfig {
// 如果尚未初始化(比如在 App.uvue 之前调用),尝试初始化一次
if (!isRegistryInitialized) {
updateResolutionConfig();
}
return resolutionState.config;
}
/**
* 根据当前设备的 pixelRatio 自动选择最佳图片
* @param img 响应式图片配置对象
* @returns 最佳图片路径
*/
export function getResponsiveImage(img: ResponsiveImage): string {
const pr = resolutionState.pixelRatio;
// 3x 屏优先找 x3 -> x2 -> x1
if (pr >= 3) {
if (img.x3 !== null) return img.x3;
if (img.x2 !== null) return img.x2;
}
// 2x 屏优先找 x2 -> x3 -> x1
if (pr >= 2) {
if (img.x2 !== null) return img.x2;
if (img.x3 !== null) return img.x3;
}
// 默认返回 1倍图
return img.x1;
}