Commit 2c4cba59 by liimin

refactor(layout): 优化布局服务和分辨率适配系统

- 将分辨率适配模块从 config 目录迁移至 services/adapter 目录
- 移除不必要的适配器抽象层,简化分辨率配置匹配逻辑
- 在屏幕方向锁定后同步更新分辨率适配配置
- 优化 LayoutService 初始化逻辑,防止重复初始化
- 调整 FinishStep 组件 z-index 值避免层级冲突
- 修改 ToolBox 组件位置从右上角调整为中心顶部
- 重构分辨率配置注册表,提升初始化性能
- 更新全局状态管理,确保配置加载的一致性
1 parent e2bcabda
......@@ -20,6 +20,7 @@ export default {
// 锁定后延迟刷新屏幕尺寸,此时已旋转为横屏,getSystemInfoSync() 会返回 1174x768
setTimeout(() => {
layoutService.refreshScreenInfo();
updateResolutionConfig(); // 同步更新分辨率适配配置
}, 400);
// 启动阶段多次重试锁定,避免首屏/框架稍后把方向改回竖屏(不做按页面锁定)
setTimeout(() => { lockOrientation("landscape-primary"); }, 600);
......
......@@ -4,7 +4,7 @@
:is-footer="false"
position="center"
:title="step == 1 ? '客户信息完善' : '结果反馈'"
:z-index="10075"
:z-index="10074"
@close="onMessageBoxClose">
<view class="popup-content">
<!-- 内容区域 -->
......
......@@ -8,7 +8,7 @@
inactive-icon="folder"
:offset-right="20"
:offset-top="120"
position="top-right"
position="top-center"
:size="56"
type="primary"
@click="handleFabClick">
......
import { createSSRApp } from "vue";
// 引入分辨率适配模块
import { resolutionState, useResponsiveImage } from "@/config/resolution-adapt/index.uts";
import { resolutionState, useResponsiveImage } from "@/services/adapter/index.uts";
import { logger } from "@/services/logger";
import DBRecord from "@/services/recorder/DBRecord.uts";
......
......@@ -5,13 +5,11 @@
* - 计算一次,缓存结果,供全局使用
*/
import type { LayoutMode, LayoutModeConfig } from "@/config/layout.config.uts";
import { ref } from "vue";
import type { LayoutMode, LayoutModeConfig } from "@/config/layout.config.uts";
import { LAYOUT_VARS } from "@/config/layout-vars.uts";
import { LAYOUT_MODES } from "@/config/layout.config.uts";
import { updateResolutionConfig } from "@/services/adapter/core.uts";
class LayoutService {
private cssVariables = ref<UTSJSONObject>({});
......@@ -34,7 +32,7 @@ class LayoutService {
/**
* 获取当前模式
*/
getCurrentMode() {
getCurrentMode(): Ref<LayoutMode> {
return this.currentMode;
}
......@@ -78,7 +76,7 @@ class LayoutService {
/**
* 获取缩放比例
*/
getScaleRatio() {
getScaleRatio(): Ref<number> {
return this.scaleRatio;
}
......@@ -96,12 +94,11 @@ class LayoutService {
* 初始化(App 启动时调用一次)
*/
init(): void {
if (this.initialized.value) {
return; // 防止重复初始化
}
this.updateScreenInfo();
this.initialized.value = true;
const w = this.screenWidth.value;
const h = this.screenHeight.value;
const minDim = Math.min(w, h);
console.log(`[LayoutService] init | 短边minDim=${ minDim } | mode=${ this.currentMode.value } | ratio=${ this.scaleRatio.value.toFixed(3) } | w=${ w } h=${ h}`);
}
/**
......@@ -115,12 +112,11 @@ class LayoutService {
* 刷新屏幕信息并重新计算(如锁定横屏后需延迟调用以拿到旋转后的尺寸)
*/
refreshScreenInfo(): void {
if (!this.initialized.value) {
this.init();
return;
}
this.updateScreenInfo();
// 重新计算分辨率适配配置
updateResolutionConfig();
const w = this.screenWidth.value;
const h = this.screenHeight.value;
console.log(`[LayoutService] refreshScreenInfo | w=${ w } h=${ h } | mode=${ this.currentMode.value } | ratio=${ this.scaleRatio.value.toFixed(3)}`);
}
/**
......@@ -140,21 +136,15 @@ class LayoutService {
* - 手机:物理长边 < 1024,用 portrait 布局(竖屏)
*/
private detectMode(): LayoutMode {
const w = this.screenWidth.value;
const h = this.screenHeight.value;
const minDim = Math.min(w, h); // 物理短边
const maxDim = Math.max(w, h); // 物理长边
const maxDim = Math.max(this.screenWidth.value, this.screenHeight.value);
let mode: LayoutMode = "pad";
if (maxDim >= 1440) {
mode = "desktop";
} else if (maxDim >= 1024) {
mode = "pad"; // 平板:长边>=1024 即视为 pad,保证 pad 端为横屏布局
} else {
mode = "portrait"; // 手机:长边<1024,用竖屏布局
return "desktop";
}
if (maxDim >= 1024) {
return "pad";
}
console.log(`[LayoutService] detectMode: 长边=${ maxDim }, 短边=${ minDim }, w=${ w }, h=${ h }, mode=${ mode}`);
return mode;
return "portrait";
}
/**
......@@ -173,58 +163,62 @@ class LayoutService {
* baseValue 优先取 values[baseWidth],否则取最小 key 对应的值
*/
private resolveValue(values: UTSJSONObject, w: number, baseWidth: number): number {
const wStr = w.toString();
const direct = values[wStr];
if (direct != null && typeof direct === "number") {
return direct;
// 1. 尝试直接匹配当前宽度
const directValue = values[w.toString()];
if (directValue != null && typeof directValue === "number") {
return directValue;
}
// 2. 尝试使用基准宽度查找
const baseValue = values[baseWidth.toString()];
if (baseValue != null && typeof baseValue === "number") {
return baseValue * (w / baseWidth);
}
const baseStr = baseWidth.toString();
const baseFromWidth = values[baseStr];
let baseVal: number = 0;
let scaleDenom: number = baseWidth;
if (baseFromWidth != null && typeof baseFromWidth === "number") {
baseVal = baseFromWidth;
} else {
let minKey: number = 99_999;
for (const k in values) {
const n = Number.parseInt(k, 10);
if (!isNaN(n) && n < minKey) {
minKey = n;
}
// 3. 使用最小 key 作为基准
let minKey: number = Number.MAX_SAFE_INTEGER;
for (const k in values) {
const n = Number.parseInt(k, 10);
if (!isNaN(n) && n < minKey) {
minKey = n;
}
if (minKey < 99_999) {
const v = values[minKey.toString()];
if (v != null && typeof v === "number") {
baseVal = v;
scaleDenom = minKey;
}
}
if (minKey < Number.MAX_SAFE_INTEGER) {
const minValue = values[minKey.toString()];
if (minValue != null && typeof minValue === "number") {
return minValue * (w / minKey);
}
}
return baseVal * (w / scaleDenom);
// 兜底返回 0
return 0;
}
/**
* 更新 CSS 变量缓存(遍历 LAYOUT_VARS)
*/
private updateCSSVariables(): void {
// 对于 portrait 模式,使用物理短边参与缩放,避免横屏手机出现非常大的宽度(例如 800x360),
// 造成与 H5 模拟器(390x844)视觉比例差异过大
const sw = this.screenWidth.value;
const sh = this.screenHeight.value;
const isPortraitMode = this.currentMode.value == "portrait";
const w = isPortraitMode ? (Math.min(sw, sh)) : sw;
const isPortraitMode = this.currentMode.value === "portrait";
// portrait 模式使用短边,避免横屏手机视觉比例异常
const w = isPortraitMode ? Math.min(sw, sh) : sw;
const baseWidth = this.getBaseWidth();
const out: UTSJSONObject = {};
for (const key in LAYOUT_VARS) {
const def = LAYOUT_VARS[key] as null | UTSJSONObject;
if (def == null) continue;
const cssName = def.css as null | string;
if (cssName == null) continue;
const vals = def.values as null | UTSJSONObject;
if (vals == null) continue;
const resolved = this.resolveValue(vals, w, baseWidth);
out[cssName] = `${Math.round(resolved).toString() }px`;
out[cssName] = `${Math.round(resolved)}px`;
}
this.cssVariables.value = out;
}
......@@ -234,28 +228,22 @@ class LayoutService {
*/
private updateScreenInfo(): void {
const systemInfo = uni.getSystemInfoSync();
// 使用 UTS 内置的 screenWidth/screenHeight,避免对 GetSystemInfoResult 进行不安全类型转换
const w = systemInfo.screenWidth;
const h = systemInfo.screenHeight;
let { screenWidth: w, screenHeight: h } = systemInfo;
// 如果获取到的值为 0,尝试使用 windowWidth/windowHeight
if (w == 0 || h == 0) {
// 容错处理:如果 screen 尺寸为 0,使用 window 尺寸
if (w === 0 || h === 0) {
const winInfo = uni.getWindowInfo();
if (w == 0 && winInfo.windowWidth > 0) {
this.screenWidth.value = winInfo.windowWidth;
}
if (h == 0 && winInfo.windowHeight > 0) {
this.screenHeight.value = winInfo.windowHeight;
}
} else {
this.screenWidth.value = w;
this.screenHeight.value = h;
w = w === 0 ? winInfo.windowWidth : w;
h = h === 0 ? winInfo.windowHeight : h;
}
this.screenWidth.value = w;
this.screenHeight.value = h;
// 级联更新:模式 -> 缩放比 -> CSS 变量
this.currentMode.value = this.detectMode();
const baseWidth = this.getBaseWidth();
this.scaleRatio.value = this.screenWidth.value / baseWidth;
this.scaleRatio.value = w / baseWidth;
this.updateCSSVariables();
}
}
......
import { landscapeMap, portraitMap } from "./registry.uts";
import { AppResolutionConfig } from "./types/index.uts";
// ========================================================================
// 4. 适配器定义 (Adapter Definition)
// ========================================================================
export interface IResAdapter {
match(w: number, h: number): boolean
getConfig(key: string): AppResolutionConfig | null
getFallback(): AppResolutionConfig | null
getPrefix(): string
getCssClass(key: string): string
}
class ResolutionAdapterImpl implements IResAdapter {
private map: Map<string, AppResolutionConfig>;
private matcher: (w: number, h: number) => boolean;
private prefix: string;
constructor(prefix: string, map: Map<string, AppResolutionConfig>, matcher: (w: number, h: number) => boolean) {
this.prefix = prefix;
this.map = map;
this.matcher = matcher;
}
getConfig(key: string): AppResolutionConfig | null { return this.map.get(key); }
getCssClass(key: string): string {
// 生成 CSS 类名规则:layout-{prefix}-{width}x{height}
// 例如:layout-landscape-1920x1080
// 如果未匹配到具体分辨率,使用 layout-{prefix}-common
if (this.map.has(key)) {
return `layout-${this.prefix}-${key}`;
}
return `layout-${this.prefix}-common`;
}
getFallback(): AppResolutionConfig | null { return this.map.get("common"); }
getPrefix(): string { return this.prefix; }
match(w: number, h: number): boolean { return this.matcher(w, h); }
}
export const resolutionAdapters: IResAdapter[] = [
new ResolutionAdapterImpl("landscape", landscapeMap, (w, h) => w > h),
new ResolutionAdapterImpl("portrait", portraitMap, (w, h) => w <= h)
];
import { logger } from "@/services/logger/index.uts";
import { IResAdapter, resolutionAdapters } from "./adapter.uts";
import { initRegistry, isRegistryInitialized } from "./registry.uts";
import type { AppResolutionConfig, ResponsiveImage } from "./types/index.uts";
import { initRegistry, landscapeMap, portraitMap } from "./registry.uts";
import { resolutionState } from "./store.uts";
import { AppResolutionConfig, ResponsiveImage } from "./types/index.uts";
import { layoutService } from "@/services/LayoutService.uts";
// ========================================================================
// 5. 核心适配逻辑 (Core Logic)
// 核心适配逻辑
// ========================================================================
export function updateResolutionConfig() {
console.log('[ResolutionAdapt] updateResolutionConfig 开始执行');
/**
* 更新分辨率适配配置
* - 根据屏幕尺寸和方向自动匹配配置
* - 优先精确匹配,失败则使用 common 作为 fallback
*/
export function updateResolutionConfig(): void {
// 确保注册表已初始化
initRegistry();
// 确保 LayoutService 已初始化
if (!layoutService.isInitialized()) {
console.log('[ResolutionAdapt] LayoutService 未初始化,开始初始化');
layoutService.init();
} else {
console.log('[ResolutionAdapt] LayoutService 已初始化');
}
// 使用 LayoutService 获取屏幕信息
const w = layoutService.getScreenWidth();
const h = layoutService.getScreenHeight();
const pr = uni.getSystemInfoSync().pixelRatio;
console.log(`[ResolutionAdapt] 获取屏幕信息:w=${w}, h=${h}, pr=${pr}`);
if (w == 0 || h == 0) {
console.warn('[ResolutionAdapt] 屏幕尺寸为 0,跳过配置更新');
const systemInfo = uni.getSystemInfoSync();
const { screenWidth: w, screenHeight: h, pixelRatio: pr } = systemInfo;
if (w === 0 || h === 0) {
logger.warn('[ResolutionAdapt] 屏幕尺寸为 0,跳过配置更新');
return;
}
const key = `${Math.round(w)}x${Math.round(h)}`;
const isLandscape = w > h;
const configMap = isLandscape ? landscapeMap : portraitMap;
const prefix = isLandscape ? 'landscape' : 'portrait';
// 使用适配器模式匹配
let adapter: IResAdapter | 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);
// 查找配置:优先精确匹配,其次 common
let target = configMap.get(key);
let usedKey = key;
let cssClass = `layout-${prefix}-${key}`;
if (target === null) {
target = adapter.getFallback();
usedKey = `${adapter.getPrefix()}/common`;
if (target == null) {
target = configMap.get('common');
usedKey = `${prefix}/common`;
cssClass = `layout-${prefix}-common`;
}
console.log('target', pr,w,h)
if (target !== null) {
resolutionState.config = target as AppResolutionConfig;
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}`);
if (target != null) {
applyResolutionConfig(target, usedKey, cssClass, pr, w, h);
}
}
/**
* 应用分辨率配置到状态
*/
function applyResolutionConfig(
cfg: AppResolutionConfig,
key: string,
cssCls: string,
pxRatio: number,
winWidth: number,
winHeight: number
): void {
resolutionState.config = cfg;
resolutionState.currentKey = key;
resolutionState.cssClass = cssCls;
resolutionState.pixelRatio = pxRatio;
resolutionState.windowWidth = winWidth;
resolutionState.windowHeight = winHeight;
logger.info(`[ResolutionAdapt] Applied config: ${key}, cssClass: ${cssCls}`);
}
// ========================================================================
// 5. 钩子函数 (Hooks)
// Hooks
// ========================================================================
export function useResolutionConfig() : AppResolutionConfig {
// 如果尚未初始化(比如在 App.uvue 之前调用),尝试初始化一次
if (!isRegistryInitialized) {
/**
* 获取分辨率配置(惰性加载)
*/
export function useResolutionConfig(): AppResolutionConfig {
if (!resolutionState.config) {
updateResolutionConfig();
}
return resolutionState.config;
}
/**
* 获取当前分辨率配置的 CSS 类名(响应式)
* @returns CSS 类名字符串
* 获取当前布局的 CSS 类名
*/
export function useLayoutCssClass(): string {
return resolutionState.cssClass;
}
/**
* 根据当前设备的 pixelRatio 自动选择最佳图片
* @param img 响应式图片配置对象
* 根据 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;
if (img.x3) return img.x3;
if (img.x2) return img.x2;
return img.x1;
}
// 2x 屏优先找 x2 -> x3 -> x1
if (pr >= 2) {
if (img.x2 !== null) return img.x2;
if (img.x3 !== null) return img.x3;
if (img.x2) return img.x2;
if (img.x3) return img.x3;
return img.x1;
}
// 默认返回 1倍图
// 默认返回 1 倍图
return img.x1;
}
// 导出适配器
export { IResolutionAdapter, resolutionAdapters } from "./adapter.uts";
// 导出核心逻辑和工具函数
export { getResponsiveImage, updateResolutionConfig, useResolutionConfig } from "./core.uts";
......
// ========================================================================
// 1. 静态导入所有支持的分辨率配置 (Static Import)
// 新增分辨率时,请在此处导入并在 initRegistry 中注册
// 静态导入所有支持的分辨率配置
// 新增分辨率时,请在此处导入并在 initRegistry 中注册
// ========================================================================
import { config as ls_1174 } from "./landscape/1174x768/index.uts";
import { config as ls_1920 } from "./landscape/1920x1080/index.uts";
// Landscape (横屏)
import { config as ls_common } from "./landscape/common/index.uts";
// Portrait (竖屏)
import { config as pt_common } from "./portrait/common/index.uts";
import { AppResolutionConfig } from "./types/index.uts";
import type { AppResolutionConfig } from "./types/index.uts";
// ========================================================================
// 2. 配置注册表 (Registry)
// 配置注册表
// ========================================================================
export const landscapeMap = new Map<string, AppResolutionConfig>();
export const portraitMap = new Map<string, AppResolutionConfig>();
// eslint-disable-next-line import/no-mutable-exports
let isRegistryInitialized = false;
const landscapeMap = new Map<string, AppResolutionConfig>();
const portraitMap = new Map<string, AppResolutionConfig>();
// 定义配置映射表,方便统一管理和循环注册
const landscapeConfigs = {
......@@ -28,26 +24,32 @@ const landscapeConfigs = {
const portraitConfigs = {
"common": pt_common
// "768x1024": pt_768
} as UTSJSONObject;
export function initRegistry() {
if (isRegistryInitialized) return;
// 导出 Map(只读)
export { landscapeMap, portraitMap };
// 导出初始化函数(内部使用)
export { initRegistry };
/**
* 初始化分辨率配置注册表
* - 懒加载模式,首次调用时初始化
*/
function initRegistry(): void {
if (landscapeMap.size > 0 && portraitMap.size > 0) {
return; // 已初始化,避免重复
}
// 批量注册横屏配置
// UTS 遍历 JSONObject
for (const key in landscapeConfigs) {
const conf = landscapeConfigs[key] as AppResolutionConfig;
landscapeMap.set(key, conf);
}
// 批量注册竖屏配置
for (const key in portraitConfigs) {
const conf = portraitConfigs[key] as AppResolutionConfig;
portraitMap.set(key, conf);
}
isRegistryInitialized = true;
}
export { isRegistryInitialized };
import { reactive } from "vue";
import { config as ls_common } from "./landscape/common/index.uts";
import { AppResolutionConfig } from "./types/index.uts";
import type { AppResolutionConfig } from "./types/index.uts";
// ========================================================================
// 3. 全局状态 (Global State)
// ========================================================================
// 使用 reactive 包装,以便在 Vue 模板中自动更新
/**
* 分辨率适配状态
*/
export type ResolutionState = {
config: AppResolutionConfig
cssClass: string // 新增:用于根元素的 CSS 类名
currentKey: string
pixelRatio: number
windowHeight: number
windowWidth: number
config: AppResolutionConfig | null
cssClass: string
currentKey: string
pixelRatio: number
windowWidth: number
windowHeight: number
}
// 纯数据对象,不包含逻辑,避免循环依赖
export const resolutionState = reactive({
config: ls_common, // 初始默认值
currentKey: "init",
cssClass: "layout-default",
/**
* 全局分辨率状态 (响应式)
* - 使用 Object.assign 确保类型正确
*/
const initialState: ResolutionState = {
config: null,
currentKey: '',
cssClass: 'layout-default',
pixelRatio: 1,
windowWidth: 0,
windowHeight: 0
} as ResolutionState);
};
export const resolutionState = reactive(initialState);
......@@ -6,6 +6,7 @@
// #ifdef APP
import { layoutService } from '@/services/LayoutService.uts'
import { lockOrientation } from '@/utils/plus-screen.uts'
import { updateResolutionConfig } from '@/services/adapter/index.uts'
// #endif
// 防抖:仅保留最后一次延迟刷新,避免快速切页时多次刷新
......@@ -29,6 +30,7 @@ export function applyScreenOrientationLock(): void {
}
refreshTimer = setTimeout((): void => {
layoutService.refreshScreenInfo()
updateResolutionConfig() // 同步更新分辨率适配配置
refreshTimer = 0
}, 800)
} else {
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!