Commit 77e6d431 by liimin

feat(layout): 实现屏幕适配和方向检测功能

- 添加 useOrientation 和 useScreenVars 钩子用于屏幕方向检测
- 在 LayoutRoot 组件中集成屏幕变量适配功能
- 添加全局屏幕变量配置文件和页面样式变量
- 在 App.vue 中添加 onResize 事件监听屏幕变化
- 修改 HBuilderX 启动配置为自定义模式
- 移除页面组件中的旧布局逻辑和注释代码
- 添加屏幕旋转时的方向更新机制
- 实现全局屏幕方向锁定和解锁功能
- 优化分辨率检测和适配配置映射
- 添加测试视图样式和适配类名应用
1 parent 3b2d2699
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
"version" : "1.0", "version" : "1.0",
"configurations" : [ "configurations" : [
{ {
"playground" : "standard", "playground" : "custom",
"type" : "uni-app:app-android" "type" : "uni-app:app-android"
} }
] ]
......
<template> <template>
<un-page class="layout-root" :class="[modeClass, resolutionClass, adapterClass]" :style="styleObj"> <un-page class="layout-root" :style="styleObject">
<slot></slot> <slot></slot>
</un-page> </un-page>
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
import { computed, onMounted, onUnmounted, type Ref } from 'vue' import { computed, onMounted, onUnmounted, type Ref, ref } from 'vue'
import { useLayout } from '@/composables/useLayout' // import { useLayout } from '@/composables/useLayout'
import { cssClassRef, updateResolutionConfig, useResolutionConfig } from '@/services/adapter' // import { cssClassRef, updateResolutionConfig, useResolutionConfig } from '@/services/adapter'
import { layoutService } from '@/services/LayoutService.uts' import { updateOrientation, useScreenVars } from '@/services/adapter/hooks/index.uts'
// import { layoutService } from '@/services/LayoutService.uts'
// import pageVars from '@/pages/common/accountItems/index.vars'
const layout = useLayout() const props = defineProps<{
const rawCssVars = (layout as UTSJSONObject)['cssVars'] as Ref<UTSJSONObject> | null pageVars?: UTSJSONObject | null
}>()
// const layout = useLayout()
// const rawCssVars = (layout as UTSJSONObject)['cssVars'] as Ref<UTSJSONObject> | null
// onResize(() => {
// console.log('layout-------onResize',1112321321321321)
// updateOrientation()
// })
// const styleObj = computed((): UTSJSONObject => {
// const r = rawCssVars
// if (r == null) return {}
// const v = r.value
// return v != null ? v : {}
// })
const styleObj = computed((): UTSJSONObject => { // // useResolutionConfig()
const r = rawCssVars // const LAYOUT_ROOT_POLL_MS = 350
if (r == null) return {} // let layoutRootPollId: number | null = null
const v = r.value // let lastLayoutW = 0
return v != null ? v : {} // let lastLayoutH = 0
})
useResolutionConfig()
console.log('useResolutionConfigAAA', useResolutionConfig())
const LAYOUT_ROOT_POLL_MS = 350
let layoutRootPollId: number | null = null
let lastLayoutW = 0
let lastLayoutH = 0
function syncLayoutRootResolution(): void {
const info = uni.getWindowInfo()
let w = info.windowWidth
let h = info.windowHeight
if (w == 0 && info.screenWidth > 0) {
w = info.screenWidth
if (info.screenHeight > 0) {
h = info.screenHeight
}
}
if (w == 0 || h == 0) {
return
}
if (w == lastLayoutW && h == lastLayoutH) {
return
}
lastLayoutW = w
lastLayoutH = h
layoutService.refreshScreenInfo()
updateResolutionConfig()
}
const adapterClass = computed((): string => { // function syncLayoutRootResolution(): void {
const cls = cssClassRef.value // const info = uni.getWindowInfo()
return cls != null ? (cls as string) : '' // let w = info.windowWidth
// let h = info.windowHeight
// if (w == 0 && info.screenWidth > 0) {
// w = info.screenWidth
// if (info.screenHeight > 0) {
// h = info.screenHeight
// }
// }
// if (w == 0 || h == 0) {
// return
// }
// if (w == lastLayoutW && h == lastLayoutH) {
// return
// }
// lastLayoutW = w
// lastLayoutH = h
// layoutService.refreshScreenInfo()
// updateResolutionConfig()
// }
const screenVarsHook = useScreenVars(props.pageVars ?? null)
const styleObject = computed((): Any => {
const sv = screenVarsHook.screenVars as Ref<UTSJSONObject>
return sv.value as Any
}) })
// const adapterClass = computed((): string => {
// const cls = cssClassRef.value
// return cls != null ? (cls as string) : ''
// })
const modeClass = computed((): string => { // const modeClass = computed((): string => {
const modeRef = layoutService.getCurrentMode() // const modeRef = layoutService.getCurrentMode()
const m = modeRef.value // const m = modeRef.value
return m == 'portrait' ? 'mode-portrait' : 'mode-landscape' // return m == 'portrait' ? 'mode-portrait' : 'mode-landscape'
}) // })
const resolutionClass = computed((): string => { // const resolutionClass = computed((): string => {
const bucket = layoutService.getResolutionBucket() // const bucket = layoutService.getResolutionBucket()
return `res-${bucket}` // return `res-${bucket}`
}) // })
onMounted(() => { onMounted(() => {
syncLayoutRootResolution() // syncLayoutRootResolution()
layoutRootPollId = setInterval(syncLayoutRootResolution, LAYOUT_ROOT_POLL_MS) // layoutRootPollId = setInterval(syncLayoutRootResolution, LAYOUT_ROOT_POLL_MS)
}) })
onUnmounted(() => { onUnmounted(() => {
const tid = layoutRootPollId // const tid = layoutRootPollId
if (tid != null) { // if (tid != null) {
clearInterval(tid) // clearInterval(tid)
layoutRootPollId = null // layoutRootPollId = null
} // }
}) })
</script> </script>
......
<template> <template>
<layout-root> <layout-root :page-vars="pageVars">
<view class="page-container account-page fade-in" >
<view class="page-container account-page fade-in">
<view class="bg"> <view class="bg">
<image class="bg-image" <image class="bg-image"
mode="aspectFill" mode="aspectFill"
...@@ -55,6 +54,10 @@ ...@@ -55,6 +54,10 @@
</uni-icons> </uni-icons>
</view> </view>
</view> </view>
<!-- <view class="test-view">
<text class="adapter">hdadl2a22dj2ajdka2s</text>
</view> -->
<scroll-view class="list" <scroll-view class="list"
direction="vertical" direction="vertical"
:show-scrollbar="false"> :show-scrollbar="false">
...@@ -79,6 +82,9 @@ import { ComponentPublicInstance, nextTick, ref } from "vue"; ...@@ -79,6 +82,9 @@ import { ComponentPublicInstance, nextTick, ref } from "vue";
import AccountList from "@/pages/common/components/AccountList.uvue"; import AccountList from "@/pages/common/components/AccountList.uvue";
import MerchantList from "@/pages/common/components/MerchantList.uvue"; import MerchantList from "@/pages/common/components/MerchantList.uvue";
import Scene from "@/pages/common/components/Scene.uvue"; import Scene from "@/pages/common/components/Scene.uvue";
import { updateOrientation, usePageVars,useScreenVars } from '@/services/adapter/hooks/index.uts'
import { cssClassRef } from "@/services/adapter";
import pageVars from '../styles/index.vars'
// 不显式导入 onLoad,避免与编译器生成的 BasePage 构造函数中的 onLoad 冲突(error18) // 不显式导入 onLoad,避免与编译器生成的 BasePage 构造函数中的 onLoad 冲突(error18)
// import { onLoad } from "@dcloudio/uni-app"; // import { onLoad } from "@dcloudio/uni-app";
...@@ -103,8 +109,8 @@ onLoad((options: null | UTSJSONObject) => { ...@@ -103,8 +109,8 @@ onLoad((options: null | UTSJSONObject) => {
} }
}, 100); }, 100);
} }
// 调试:检查 screenVars
}); });
const search = (): void => { const search = (): void => {
edit.value = false; edit.value = false;
inputFocus.value = false; inputFocus.value = false;
...@@ -157,9 +163,13 @@ const chooseMerchant = (userInfo: any): void => { ...@@ -157,9 +163,13 @@ const chooseMerchant = (userInfo: any): void => {
} }
}); });
}; };
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
@import "../styles/common.scss";
// @import "../styles/landscape.scss";
// @import "../styles/portrait.scss";
.page-container { .page-container {
width: 100%; width: 100%;
height: 100%; height: 100%;
......
.adapter{
color:var(--adapter-color);
font-size: var(--adapter-fontsize);
}
.test-view{
height: var(--test-view-height);
width: var(--test-view-width);
border: var(--test-view-border-width, 1px) var(--test-view-border-style, solid) var(--test-view-border-color, transparent);
background-color: var(--test-view-bg, transparent);
border-radius: var(--test-view-border-radius);
display: flex;
align-items: var(--test-view-align-items);
justify-content: var(--test-view-justify-content);
flex-direction: var(--test-view-flex-direction);
padding: var(--test-view-padding);
margin: 10px;
// background-color: var(--test-view-bg);
// background-color: red;
}
// 约定式命名:必须叫 index.vars.uts
export default {
common: {
'--home-box-bg': '#FF4444',
},
portrait: {
'--adapter-color': 'red',
'--adapter-fontsize': '50px',
'--test-view-height': '360px',
'--test-view-border': '10px solid blue',
'--test-view-width': '100%'
'--test-view-bg': 'black',
'--test-view-border-width': '2px',
'--test-view-border-style': 'dashed',
'--test-view-border-color': 'blue',
'--test-view-border-radius': '10px',
'--test-view-align-items': 'center',
'--test-view-justify-content': 'center',
'--test-view-flex-direction': 'column',
'padding': '10px'
},
landscape: {
'--adapter-color': 'green',
'--adapter-fontsize': '50px',
'--test-view-height': '360px',
'--test-view-border': '10px solid blue',
'--test-view-width': '100%'
'--test-view-bg': 'orange',
'--test-view-border-width': '2px',
'--test-view-border-style': 'dashed',
'--test-view-border-color': 'blue',
'--test-view-border-radius': '10px',
'--test-view-align-items': 'center',
'--test-view-justify-content': 'center',
'--test-view-flex-direction': 'column',
'padding': '10px'
},
resolutions: {
'portrait-393x816': {
'--adapter-color': 'blue',
'--adapter-fontsize': '50px',
'--test-view-height': '360px',
'--test-view-border': '10px solid blue',
'--test-view-width': '100%'
'--test-view-bg': 'red',
'--test-view-border-width': '2px',
'--test-view-border-style': 'dashed',
'--test-view-border-color': 'blue',
'--test-view-border-radius': '10px',
'--test-view-align-items': 'center',
'--test-view-justify-content': 'center',
'--test-view-flex-direction': 'column',
'padding': '10px'
},
'landscape-816x393': {
'--adapter-color': '#FF4444',
'--adapter-fontsize': '20px',
'--test-view-width': '100%',
'--test-view-height': '380px',
'--test-view-border': '11px solid red',
'--test-view-bg': 'yellow',
'--test-view-border-width': '1px',
'--test-view-border-style': 'solid',
'--test-view-border-color': 'red',
'--test-view-border-radius': '50px',
'--test-view-align-items': 'center',
'--test-view-justify-content': 'flex-end',
'--test-view-flex-direction': 'row',
'padding': '10px'
},
},
}
...@@ -84,16 +84,15 @@ function onUpdateOutputTabIndex(index: number): void { ...@@ -84,16 +84,15 @@ function onUpdateOutputTabIndex(index: number): void {
const dynamicModuleBoxStyle = computed((): any => { const dynamicModuleBoxStyle = computed((): any => {
// 使用 cssClassRef.value 确保响应式 // 使用 cssClassRef.value 确保响应式
const adapterCls = cssClassRef.value; const adapterCls = cssClassRef.value;
// TODO: headerTitleGroup 配置尚未实现,暂时返回空对象
// if (adapterCls.indexOf('layout-landscape-1174x768') >= 0) { // if (adapterCls.indexOf('layout-landscape-1174x768') >= 0) {
// const cfg = getLandscapeConfig(adapterCls).headerTitleGroup // const cfg = getLandscapeConfig(adapterCls)?.headerTitleGroup
// // 注意:getLandscapeConfig 返回模块级常量对象(同引用),computed 可能判定“值未变”从而不触发视图更新 // return cfg != null ? ({ ...cfg } as UTSJSONObject) : ({} as UTSJSONObject);
// // 这里返回一个新对象引用,确保 :style 能更新 // }
// if (adapterCls.indexOf('layout-portrait-768x1174') >= 0) {
// const cfg = getPortraitConfig(adapterCls)?.headerTitleGroup
// return cfg != null ? ({ ...cfg } as UTSJSONObject) : ({} as UTSJSONObject); // return cfg != null ? ({ ...cfg } as UTSJSONObject) : ({} as UTSJSONObject);
// } // }
if (adapterCls.indexOf('layout-portrait-768x1174') >= 0) {
const cfg = getPortraitConfig(adapterCls)?.headerTitleGroup
return cfg != null ? ({ ...cfg } as UTSJSONObject) : ({} as UTSJSONObject);
}
return {} as UTSJSONObject; return {} as UTSJSONObject;
}); });
const progressWidth = computed((): string => { const progressWidth = computed((): string => {
......
// 全项目通用,所有页面共享
export const globalScreenVars = {
// 横竖屏通用
common: {
'--color-primary': '#1677FF',
'--radius': '8px',
'--opacity': 1,
},
// 竖屏全局
portrait: {
'--padding': '12px',
'--gap': '8px',
'--font-md': '14px',
},
// 横屏全局
landscape: {
'--padding': '20px',
'--gap': '12px',
'--font-md': '16px',
},
// 精准分辨率
resolutions: {
'portrait-768x1174': {
'--padding': '14px',
},
'landscape-1174x768': {
'--padding': '22px',
},
},
}
export { useOrientation, updateOrientation } from './useOrientation';
export { useScreenVars } from './useScreenVars';
export { usePageVars } from './usePageVars';
\ No newline at end of file \ No newline at end of file
import { ref, computed } from 'vue'
// 全局唯一状态
const isPortrait = ref(true)
const windowWidth = ref(0)
const windowHeight = ref(0)
// 更新方向
export function updateOrientation(): void {
const systemInfo = uni.getSystemInfoSync()
const { screenWidth: w, screenHeight: h } = systemInfo
console.log('[useOrientation] screenWidth:', w, 'screenHeight:', h)
console.log('[useOrientation] windowWidth:', systemInfo.windowWidth, 'windowHeight:', systemInfo.windowHeight)
// 使用屏幕物理尺寸
windowWidth.value = Math.round(w)
windowHeight.value = Math.round(h)
isPortrait.value = systemInfo.windowWidth < systemInfo.windowHeight
console.log('[useOrientation] resolutionKey will be:', `${windowWidth.value}x${windowHeight.value}`)
}
// 提供状态
export function useOrientation() {
return {
isPortrait,
windowWidth,
windowHeight,
// 方向:portrait / landscape
orientationKey: computed(() => isPortrait.value ? 'portrait' : 'landscape'),
// 分辨率 key:宽x高 例如 393x816
resolutionKey: computed(() => {
const key = `${windowWidth.value}x${windowHeight.value}`
console.log('[useOrientation] resolutionKey computed:', key)
return key
}),
}
}
import { useScreenVars } from './useScreenVars'
/**
* 使用页面变量 Hook
* TODO: 此功能尚未完全实现,暂时返回空对象
* UTS 不支持 require() 动态导入,建议使用静态导入
*/
export function usePageVars() {
// TODO: 实现页面变量加载逻辑
// 当前 UTS 不支持 require() 动态导入
// 建议在具体页面中直接导入并使用 useScreenVars
return useScreenVars(null)
}
import { type Ref, watch, ref } from 'vue'
import { useOrientation, updateOrientation } from './useOrientation'
import { globalScreenVars } from '../constants/screen.vars.global'
export function useScreenVars(pageVars: UTSJSONObject | null) {
// 确保方向信息已更新
updateOrientation()
const orientation = useOrientation()
const orientationKey = orientation.orientationKey as Ref<string>
const resolutionKey = orientation.resolutionKey as Ref<string>
// 使用 ref 包装,每次更新时替换整个对象
const screenVarsValue = ref<UTSJSONObject>({})
const updateScreenVars = (): void => {
const orient = orientationKey.value
const resKey = resolutionKey.value
const fullResKey = `${orient}-${resKey}`
console.log('[useScreenVars] orient:', orient)
console.log('[useScreenVars] resKey:', resKey)
console.log('[useScreenVars] fullResKey:', fullResKey)
// 构建新的样式对象
const newValue: UTSJSONObject = {}
// 合并 globalScreenVars.common
if (globalScreenVars.common != null) {
const common = globalScreenVars.common as UTSJSONObject
for (const key in common) {
newValue[key] = common[key]
}
}
// 合并 globalScreenVars[orient] - 使用条件判断
let globalOrient: any | null = null
if (orient == 'portrait') {
globalOrient = globalScreenVars.portrait
} else if (orient == 'landscape') {
globalOrient = globalScreenVars.landscape
}
if (globalOrient != null) {
const orientObj = globalOrient as UTSJSONObject
for (const key in orientObj) {
newValue[key] = orientObj[key]
}
}
// 合并 globalScreenVars.resolutions[fullResKey]
if (globalScreenVars.resolutions != null) {
const resolutions = globalScreenVars.resolutions as UTSJSONObject
const globalRes = resolutions[fullResKey]
if (globalRes != null) {
const globalResObj = globalRes as UTSJSONObject
for (const key in globalResObj) {
newValue[key] = globalResObj[key]
}
}
}
// 如果 pageVars 为 null,直接赋值
if (pageVars == null) {
console.log('[useScreenVars] pageVars is null')
screenVarsValue.value = newValue
return
}
// 将 pageVars 转换为 UTSJSONObject
const pageVarsObj = pageVars as UTSJSONObject
// 合并 pageVars.common
const pageCommon = pageVarsObj['common']
if (pageCommon != null) {
const commonObj = pageCommon as UTSJSONObject
for (const key in commonObj) {
newValue[key] = commonObj[key]
}
}
// 合并 pageVars[orient]
const pageOrient = pageVarsObj[orient]
if (pageOrient != null) {
const orientObj = pageOrient as UTSJSONObject
for (const key in orientObj) {
newValue[key] = orientObj[key]
}
}
// 合并 pageVars.resolutions[fullResKey]
const pageResolutions = pageVarsObj['resolutions']
if (pageResolutions != null) {
const resolutionsObj = pageResolutions as UTSJSONObject
const pageRes = resolutionsObj[fullResKey]
if (pageRes != null) {
const pageResObj = pageRes as UTSJSONObject
for (const key in pageResObj) {
newValue[key] = pageResObj[key]
}
}
}
console.log('[useScreenVars] final newValue --adapter-color:', newValue['--adapter-color'])
// 替换整个对象
screenVarsValue.value = newValue
console.log('[useScreenVars] updated newValue newValue:', newValue)
}
// 初始更新
updateScreenVars()
// 监听方向变化
watch(orientationKey, (): void => {
console.log('[useScreenVars] orientationKey changed')
updateScreenVars()
})
watch(resolutionKey, (): void => {
console.log('[useScreenVars] resolutionKey changed')
updateScreenVars()
})
return {
screenVars: screenVarsValue
}
}
...@@ -20,12 +20,14 @@ const portraitMap = new Map<string, AppResolutionConfig>(); ...@@ -20,12 +20,14 @@ const portraitMap = new Map<string, AppResolutionConfig>();
const landscapeConfigs = { const landscapeConfigs = {
"common": ls_common, "common": ls_common,
"1174x768": ls_1174, "1174x768": ls_1174,
"1920x1080": ls_1920 "1920x1080": ls_1920,
"816x393": ls_common
} as UTSJSONObject; } as UTSJSONObject;
const portraitConfigs = { const portraitConfigs = {
"768x1174": pt_768x1174, "768x1174": pt_768x1174,
"640x979": pt_768x1174, "640x979": pt_common,
"393x816": pt_common,
"common": pt_common "common": pt_common
} as UTSJSONObject; } as UTSJSONObject;
......
...@@ -54,7 +54,8 @@ export function applyScreenOrientationLock(): void { ...@@ -54,7 +54,8 @@ export function applyScreenOrientationLock(): void {
scheduleRefresh(250) scheduleRefresh(250)
scheduleRefresh(750) scheduleRefresh(750)
} else { } else {
lockOrientation('portrait-primary') // lockOrientation('portrait-primary')
unlockOrientation()
scheduleRefresh(250) scheduleRefresh(250)
scheduleRefresh(650) scheduleRefresh(650)
} }
......
import { store } from "@/store/index.uts"; import { store } from "@/store/index.uts";
import { applyScreenOrientationLock } from "@/utils/apply-orientation-lock.uts"; import { applyScreenOrientationLock } from "@/utils/apply-orientation-lock.uts";
import { updateOrientation } from '@/services/adapter/hooks/index.uts'
export function appMixin(app: VueApp) { export function appMixin(app: VueApp) {
// 注入 $store,兼容旧项目 this.$store 用法 // 注入 $store,兼容旧项目 this.$store 用法
app.config.globalProperties.$store = store; app.config.globalProperties.$store = store;
...@@ -13,7 +13,12 @@ export function appMixin(app: VueApp) { ...@@ -13,7 +13,12 @@ export function appMixin(app: VueApp) {
// 每个页面显示时统一按设备锁定方向(pad 横屏、手机竖屏),无需各页面或 LayoutRoot 单独写 // 每个页面显示时统一按设备锁定方向(pad 横屏、手机竖屏),无需各页面或 LayoutRoot 单独写
applyScreenOrientationLock(); applyScreenOrientationLock();
}, },
onLoad() {} onLoad() {},
onResize() {
// 全局监听屏幕旋转,自动更新方向信息
// 所有页面都会自动执行,无需在每个页面重复编写
updateOrientation();
}
}); });
console.log(app); console.log(app);
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!