core.uts 2.81 KB
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;
}