From b173924f39265893fa436e7c574658d49f39fa8c Mon Sep 17 00:00:00 2001 From: Elemt Date: Tue, 3 Nov 2026 11:56:48 +0800 Subject: [PATCH] =?UTF-8?q?dev:=201=E3=80=81UniMp=E4=B8=8B=E8=BD=BD?= =?UTF-8?q?=E3=80=81=E8=A7=A3=E5=AF=86=E3=80=81=E6=97=A5=E5=BF=97=E4=B8=8A?= =?UTF-8?q?=E6=8A=A5=202=E3=80=81=E9=80=82=E9=85=8D=E4=B8=89=E9=94=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build-profile.json5 | 4 +- common/BuildProfile.ets | 2 +- .../src/main/ets/utils/UniMpHostRuntime.ets | 15 ++ common/src/main/ets/utils/UniMpManager.ets | 3 +- .../src/main/ets/utils/UniMpRuntimeCompat.ets | 7 +- common/src/main/ets/utils/WindowSafeArea.ets | 156 ++++++++++++++++++ .../resources/rawfile/unimp-harmony-compat.js | 85 +++++++--- features/mainLayout/BuildProfile.ets | 2 +- .../oh_modules/@ohos/common/BuildProfile.ets | 2 +- .../src/main/ets/utils/UniMpManager.ets | 3 +- .../src/main/ets/pages/WebLayout.ets | 4 + products/app/build-profile.json5 | 2 +- .../src/main/ets/appability/AppAbility.ets | 34 ++-- products/app/src/main/ets/pages/Index.ets | 8 +- products/app/src/main/ets/pages/LoginPage.ets | 12 ++ .../app/src/main/ets/pages/NavigationPage.ets | 11 +- .../src/main/ets/pages/SplashScreenPage.ets | 17 +- products/app/src/main/ets/view/HomeBanner.ets | 14 +- .../app/src/main/ets/view/SafeAreaPage.ets | 33 ++++ 19 files changed, 350 insertions(+), 64 deletions(-) create mode 100644 common/src/main/ets/utils/UniMpHostRuntime.ets create mode 100644 common/src/main/ets/utils/WindowSafeArea.ets create mode 100644 products/app/src/main/ets/view/SafeAreaPage.ets diff --git a/build-profile.json5 b/build-profile.json5 index 9975f2a..3ac23ba 100644 --- a/build-profile.json5 +++ b/build-profile.json5 @@ -43,12 +43,12 @@ "arkOptions": { "buildProfileFields": { "CHANNEL": "harmony", - "BUILD_TIME": "2611021826" + "BUILD_TIME": "2611031154" } } }, "output": { - "artifactName": "rabbit_harmony_debug_v1.0.1_2611021826" + "artifactName": "rabbit_harmony_debug_v1.0.1_2611031154" } } ], diff --git a/common/BuildProfile.ets b/common/BuildProfile.ets index 2dc1785..bedbdc0 100644 --- a/common/BuildProfile.ets +++ b/common/BuildProfile.ets @@ -6,7 +6,7 @@ export const BUILD_MODE_NAME = 'debug'; export const DEBUG = true; export const TARGET_NAME = 'default'; export const CHANNEL = 'harmony'; -export const BUILD_TIME = '2611021826'; +export const BUILD_TIME = '2611031154'; /** * BuildProfile Class is used only for compatibility purposes. diff --git a/common/src/main/ets/utils/UniMpHostRuntime.ets b/common/src/main/ets/utils/UniMpHostRuntime.ets new file mode 100644 index 0000000..441e297 --- /dev/null +++ b/common/src/main/ets/utils/UniMpHostRuntime.ets @@ -0,0 +1,15 @@ +import { UIAbility } from '@kit.AbilityKit'; +import { window } from '@kit.ArkUI'; +import { hiAppEvent } from '@kit.PerformanceAnalysisKit'; +import { init } from '@dcloudio/uni-app-runtime'; + +export function initUniMpRuntime(ability: UIAbility, stage: window.WindowStage, debug: boolean): void { + try { + init(ability, stage, { debug }); + } finally { + // uni-app-runtime 5.14 在 init 中同步注册此监听器。历史 APP_CRASH 随后异步投递时, + // uni-crash 会在尚无 currentMP 的宿主页面调用 uni.getStorageSync,导致启动循环崩溃。 + // 只关闭这个 SDK 监听器;系统崩溃日志及其他监听器仍保留。SDK 升级后需重新核验。 + hiAppEvent.removeWatcher({ name: 'uniAppCrashWatcher' }); + } +} diff --git a/common/src/main/ets/utils/UniMpManager.ets b/common/src/main/ets/utils/UniMpManager.ets index d900815..700de87 100644 --- a/common/src/main/ets/utils/UniMpManager.ets +++ b/common/src/main/ets/utils/UniMpManager.ets @@ -1,4 +1,5 @@ import { isExistsUniMP, openUniMP, UniMP } from '@dcloudio/uni-app-runtime'; +import { getNavigationInsets } from './WindowSafeArea'; import { AESDecrypt, PLATFORM, RELEASE_BASE_URL, Signature, TOKEN, TOKEN_LOGIN, USER_PROFILE } from '../constants/AppConstants'; import { ToastUtils } from '../dialog/ToastUtils'; import { UniVersionEntity, TradeData, UniIconEntity, UserProfile } from '../viewmodel/DataBean'; @@ -238,7 +239,7 @@ async function uniMpConfig(context: UIContext): Promise> const bundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION); let safeBottom = 0; try { - safeBottom = Math.max(0, Math.round(context.px2vp(AppUtil.getNavigationIndicatorHeight()))); + safeBottom = Math.max(0, Math.ceil(context.px2vp(getNavigationInsets(AppUtil.getMainWindow()).bottom))); } catch (_) { // 无导航指示条或窗口尚未就绪时仍传有效值,避免旧 WGT 在 onLaunch 中读取 undefined。 } diff --git a/common/src/main/ets/utils/UniMpRuntimeCompat.ets b/common/src/main/ets/utils/UniMpRuntimeCompat.ets index 096fbcb..2ffc421 100644 --- a/common/src/main/ets/utils/UniMpRuntimeCompat.ets +++ b/common/src/main/ets/utils/UniMpRuntimeCompat.ets @@ -6,7 +6,7 @@ import { Logger } from './Logger'; /** 修复旧 WGT 在鸿蒙启动时读取 plus.os.name 等缺失元数据导致的白屏。 */ export class UniMpRuntimeCompat { - static readonly MARKER: string = '/* rabbit-unimp-harmony-compat:v3 */'; + static readonly MARKER: string = '/* rabbit-unimp-harmony-compat:v6 */'; static async prepare(context: common.Context, appId: string): Promise { const servicePath = getUniMPRunPath(appId) + '/www/app-service.js'; @@ -15,7 +15,10 @@ export class UniMpRuntimeCompat { return; } if (source.startsWith('/* rabbit-unimp-harmony-compat:v1 */') || - source.startsWith('/* rabbit-unimp-harmony-compat:v2 */')) { + source.startsWith('/* rabbit-unimp-harmony-compat:v2 */') || + source.startsWith('/* rabbit-unimp-harmony-compat:v3 */') || + source.startsWith('/* rabbit-unimp-harmony-compat:v4 */') || + source.startsWith('/* rabbit-unimp-harmony-compat:v5 */')) { const endMarker = '/* end-rabbit-unimp-harmony-compat */'; const end = source.indexOf(endMarker); if (end < 0) { diff --git a/common/src/main/ets/utils/WindowSafeArea.ets b/common/src/main/ets/utils/WindowSafeArea.ets new file mode 100644 index 0000000..9424512 --- /dev/null +++ b/common/src/main/ets/utils/WindowSafeArea.ets @@ -0,0 +1,156 @@ +import { window } from '@kit.ArkUI'; +import { common } from '@kit.AbilityKit'; +import { settings } from '@kit.BasicServicesKit'; +import { Logger } from './Logger'; + +export interface NavigationInsets { + left: number; + right: number; + bottom: number; +} + +// 传统三键导航属于 TYPE_SYSTEM,手势导航属于 TYPE_NAVIGATION_INDICATOR。 +// 两类区域可能重叠,取最大值,不能累加;返回值单位为 px。 +export function getNavigationInsets(mainWindow: window.Window): NavigationInsets { + const systemArea = mainWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM); + const navigationArea = mainWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR); + return { + left: Math.max(0, systemArea.leftRect.width, navigationArea.leftRect.width), + right: Math.max(0, systemArea.rightRect.width, navigationArea.rightRect.width), + bottom: Math.max(0, systemArea.bottomRect.height, navigationArea.bottomRect.height) + }; +} + +const FLOAT_NAVIGATION_KEY: string = 'float_navigation_info'; + +interface FloatingNavigationInfo { + showType: number; + region: number[]; +} + +// 悬浮三键在部分系统版本不计入 TYPE_SYSTEM;region 是屏幕坐标,单位 px。 +export function getFloatingNavigationInsets(value: string, bounds: window.Rect): NavigationInsets { + const result: NavigationInsets = { left: 0, right: 0, bottom: 0 }; + try { + const info = JSON.parse(value) as FloatingNavigationInfo; + if (!info || info.showType !== 0 || !Array.isArray(info.region) || info.region.length !== 4 || + !info.region.every((part: number) => typeof part === 'number' && Number.isFinite(part))) { + return result; + } + const x = info.region[0]; + const y = info.region[1]; + const width = info.region[2]; + const height = info.region[3]; + const right = bounds.left + bounds.width; + const bottom = bounds.top + bounds.height; + if (width <= 0 || height <= 0 || x >= right || x + width <= bounds.left || + y >= bottom || y + height <= bounds.top) { + return result; + } + if (width >= height && y + height >= bottom) { + result.bottom = bottom - Math.max(bounds.top, y); + } else if (width < height && x <= bounds.left) { + result.left = Math.min(right, x + width) - bounds.left; + } else if (width < height && x + width >= right) { + result.right = right - Math.max(bounds.left, x); + } + } catch (_) { + // 平板、旧系统或设置尚未就绪时,继续使用窗口标准避让区域。 + } + return result; +} + +export class WindowSafeArea { + private mainWindow: window.Window | undefined = undefined; + private context: common.UIAbilityContext | undefined = undefined; + private floatingNavigationValue: string = ''; + private navigationRequest: number = 0; + private observingNavigation: boolean = false; + private readonly onFloatingNavigationChange = (): void => { this.refresh(); }; + private readonly onAvoidAreaChange = (options: window.AvoidAreaOptions): void => { + if (options.type === window.AvoidAreaType.TYPE_SYSTEM || + options.type === window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR) { + this.refresh(); + } + }; + private readonly onWindowSizeChange = (): void => { + this.refresh(); + }; + + start(mainWindow: window.Window, context: common.UIAbilityContext): void { + this.stop(); + this.mainWindow = mainWindow; + this.context = context; + mainWindow.on('avoidAreaChange', this.onAvoidAreaChange); + mainWindow.on('windowSizeChange', this.onWindowSizeChange); + try { + this.observingNavigation = settings.registerKeyObserver(context, FLOAT_NAVIGATION_KEY, + settings.domainName.USER_PROPERTY, this.onFloatingNavigationChange); + } catch (_) {} + this.refresh(); + } + + refresh(): void { + this.updateInsets(); + const context = this.context; + if (!context) { return; } + const request = ++this.navigationRequest; + this.updateFloatingNavigation(context, request); + } + + private async updateFloatingNavigation(context: common.UIAbilityContext, request: number): Promise { + try { + const value = await settings.getValue(context, FLOAT_NAVIGATION_KEY, settings.domainName.USER_PROPERTY); + if (request !== this.navigationRequest || context !== this.context) { return; } + this.floatingNavigationValue = value; + this.updateInsets(); + } catch (_) { + if (request !== this.navigationRequest || context !== this.context) { return; } + this.floatingNavigationValue = ''; + this.updateInsets(); + } + } + + private updateInsets(): void { + const mainWindow = this.mainWindow; + if (!mainWindow) { + return; + } + try { + const uiContext = mainWindow.getUIContext(); + const systemArea = mainWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM); + const insets = getNavigationInsets(mainWindow); + const floating = getFloatingNavigationInsets(this.floatingNavigationValue, + mainWindow.getWindowProperties().windowRect); + insets.left = Math.max(insets.left, floating.left); + insets.right = Math.max(insets.right, floating.right); + insets.bottom = Math.max(insets.bottom, floating.bottom); + AppStorage.setOrCreate('statusBarHeight', uiContext.px2vp(systemArea.topRect.height)); + AppStorage.setOrCreate('navigationBarLeft', uiContext.px2vp(insets.left)); + AppStorage.setOrCreate('navigationBarRight', uiContext.px2vp(insets.right)); + AppStorage.setOrCreate('navigationBarBottom', uiContext.px2vp(insets.bottom)); + // 三键导航是不可遮挡的系统区域;首页可单独收紧手势指示条上方的留白。 + AppStorage.setOrCreate('systemNavigationBarBottom', + uiContext.px2vp(Math.max(0, systemArea.bottomRect.height, floating.bottom))); + } catch (error) { + Logger.error('WindowSafeArea', '更新系统栏避让区域失败: ' + JSON.stringify(error)); + } + } + + stop(): void { + this.navigationRequest++; + if (this.context && this.observingNavigation) { + try { + settings.unregisterKeyObserver(this.context, FLOAT_NAVIGATION_KEY, settings.domainName.USER_PROPERTY); + } catch (_) {} + } + this.observingNavigation = false; + this.context = undefined; + this.floatingNavigationValue = ''; + if (this.mainWindow) { + this.mainWindow.off('avoidAreaChange', this.onAvoidAreaChange); + this.mainWindow.off('windowSizeChange', this.onWindowSizeChange); + this.mainWindow = undefined; + } + } +} diff --git a/common/src/main/resources/rawfile/unimp-harmony-compat.js b/common/src/main/resources/rawfile/unimp-harmony-compat.js index 450e4fa..ee4d435 100644 --- a/common/src/main/resources/rawfile/unimp-harmony-compat.js +++ b/common/src/main/resources/rawfile/unimp-harmony-compat.js @@ -1,32 +1,58 @@ -/* rabbit-unimp-harmony-compat:v3 */ +/* rabbit-unimp-harmony-compat:v6 */ // Legacy WGT startup reads these properties before mounting its first page. // Only fill metadata absent from the Harmony SDK; do not emulate native Android APIs. (function () { if (typeof plus !== 'object' || !plus || typeof uni !== 'object' || !uni) return; - // WGT console forwarding stringifies its arguments. Vue component proxies can - // warn while being stringified, recursively re-entering that same logger. - if (typeof console === 'object' && console) { - ['log', 'info', 'warn', 'error', 'debug'].forEach(function (level) { - var descriptor = Object.getOwnPropertyDescriptor(console, level); - if (descriptor && descriptor.configurable === false) return; - function guard(fn) { - if (typeof fn !== 'function') return fn; - var active = false; - return function () { - if (active) return; - active = true; - try { return fn.apply(console, arguments); } finally { active = false; } - }; - } - var current = guard(console[level]); - Object.defineProperty(console, level, { - configurable: true, enumerable: true, - get: function () { return current; }, - set: function (fn) { current = guard(fn); } - }); + // Both console and uni.__log__ are wrapped by the WGT's native log bridge. + // Reentry guards alone still let JSON.stringify walk a whole Vue component tree. + // Never enumerate objects (or invoke their getters/toJSON) at these log boundaries. + var logDepth = 0; + var guarded = new WeakSet(); + function logValue(value) { + if (value === null) return value; + if (typeof value === 'object') { + try { + if (value instanceof Error) return String(value.stack || value.message).slice(0, 2048); + return Array.isArray(value) ? '[Array]' : '[Object]'; + } catch (_) { return '[Object]'; } + } + if (typeof value === 'function') return '[Function]'; + return typeof value === 'string' ? value.slice(0, 2048) : value; + } + function protectLog(target, key) { + var descriptor = Object.getOwnPropertyDescriptor(target, key); + if (descriptor && descriptor.configurable === false) return; + function guard(fn) { + if (typeof fn !== 'function' || guarded.has(fn)) return fn; + var active = false; + var wrapped = function () { + if (active || logDepth >= 8) return; + active = true; + logDepth++; + try { + var args = []; + for (var i = 0; i < arguments.length && i < 16; i++) args.push(logValue(arguments[i])); + return fn.apply(target, args); + } finally { + logDepth--; + active = false; + } + }; + guarded.add(wrapped); + return wrapped; + } + var current = guard(target[key]); + Object.defineProperty(target, key, { + configurable: true, enumerable: true, + get: function () { return current; }, + set: function (fn) { current = guard(fn); } }); } + if (typeof console === 'object' && console) { + ['log', 'info', 'warn', 'error', 'debug'].forEach(function (level) { protectLog(console, level); }); + } + protectLog(uni, '__log__'); function systemInfo() { try { return uni.getSystemInfoSync() || {}; } catch (_) { return {}; } @@ -50,6 +76,21 @@ var device = systemInfo(); plus.device = { vendor: device.brand || '', model: device.model || '' }; } + // Legacy templates read this field on every row but never define it on Harmony. + // Supply it before the first render instead of suppressing Vue's warning handler. + if (typeof Vue === 'object' && Vue) { + ['createApp', 'createSSRApp', 'createVueApp'].forEach(function (key) { + var create = Vue[key]; + var descriptor = Object.getOwnPropertyDescriptor(Vue, key); + if (typeof create !== 'function' || (descriptor && descriptor.writable === false)) return; + Vue[key] = function () { + var app = create.apply(this, arguments); + var properties = app && app.config && app.config.globalProperties; + if (properties && !('$system' in properties)) properties.$system = plus.os.name; + return app; + }; + }); + } if (plus.runtime && !('version' in plus.runtime)) { Object.defineProperty(plus.runtime, 'version', { configurable: true, enumerable: true, get: hostVersion }); } diff --git a/features/mainLayout/BuildProfile.ets b/features/mainLayout/BuildProfile.ets index c386046..b558378 100644 --- a/features/mainLayout/BuildProfile.ets +++ b/features/mainLayout/BuildProfile.ets @@ -6,7 +6,7 @@ export const BUILD_MODE_NAME = 'debug'; export const DEBUG = true; export const TARGET_NAME = 'default'; export const CHANNEL = 'harmony'; -export const BUILD_TIME = '2611021826'; +export const BUILD_TIME = '2611031154'; /** * BuildProfile Class is used only for compatibility purposes. diff --git a/features/mainLayout/oh_modules/@ohos/common/BuildProfile.ets b/features/mainLayout/oh_modules/@ohos/common/BuildProfile.ets index 2dc1785..bedbdc0 100644 --- a/features/mainLayout/oh_modules/@ohos/common/BuildProfile.ets +++ b/features/mainLayout/oh_modules/@ohos/common/BuildProfile.ets @@ -6,7 +6,7 @@ export const BUILD_MODE_NAME = 'debug'; export const DEBUG = true; export const TARGET_NAME = 'default'; export const CHANNEL = 'harmony'; -export const BUILD_TIME = '2611021826'; +export const BUILD_TIME = '2611031154'; /** * BuildProfile Class is used only for compatibility purposes. diff --git a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpManager.ets b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpManager.ets index d900815..700de87 100644 --- a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpManager.ets +++ b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpManager.ets @@ -1,4 +1,5 @@ import { isExistsUniMP, openUniMP, UniMP } from '@dcloudio/uni-app-runtime'; +import { getNavigationInsets } from './WindowSafeArea'; import { AESDecrypt, PLATFORM, RELEASE_BASE_URL, Signature, TOKEN, TOKEN_LOGIN, USER_PROFILE } from '../constants/AppConstants'; import { ToastUtils } from '../dialog/ToastUtils'; import { UniVersionEntity, TradeData, UniIconEntity, UserProfile } from '../viewmodel/DataBean'; @@ -238,7 +239,7 @@ async function uniMpConfig(context: UIContext): Promise> const bundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION); let safeBottom = 0; try { - safeBottom = Math.max(0, Math.round(context.px2vp(AppUtil.getNavigationIndicatorHeight()))); + safeBottom = Math.max(0, Math.ceil(context.px2vp(getNavigationInsets(AppUtil.getMainWindow()).bottom))); } catch (_) { // 无导航指示条或窗口尚未就绪时仍传有效值,避免旧 WGT 在 onLaunch 中读取 undefined。 } diff --git a/features/mainLayout/src/main/ets/pages/WebLayout.ets b/features/mainLayout/src/main/ets/pages/WebLayout.ets index 1b99faf..af81037 100644 --- a/features/mainLayout/src/main/ets/pages/WebLayout.ets +++ b/features/mainLayout/src/main/ets/pages/WebLayout.ets @@ -34,7 +34,11 @@ export struct WebLayout { // 页面加载完成后执行 JS this.controller.runJavaScript('document.title = "HarmonyOS"'); }) + .width('100%') + .height('100%') } + .width('100%') + .layoutWeight(1) } .width('100%') .height('100%') diff --git a/products/app/build-profile.json5 b/products/app/build-profile.json5 index 495dd5e..6221bf7 100644 --- a/products/app/build-profile.json5 +++ b/products/app/build-profile.json5 @@ -26,7 +26,7 @@ { "name": "default", "output": { - "artifactName": "rabbit_harmony_v1.0.1_261121826" + "artifactName": "rabbit_harmony_v1.0.1_261131154" } }, { diff --git a/products/app/src/main/ets/appability/AppAbility.ets b/products/app/src/main/ets/appability/AppAbility.ets index 12e4463..a45fa0f 100644 --- a/products/app/src/main/ets/appability/AppAbility.ets +++ b/products/app/src/main/ets/appability/AppAbility.ets @@ -3,7 +3,7 @@ import { KVStore } from '@ohos/common/src/main/ets/utils/KVStore'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { window } from '@kit.ArkUI'; import { AppUtil } from '@pura/harmony-utils'; -import { init } from '@dcloudio/uni-app-runtime'; +import { initUniMpRuntime } from '@ohos/common/src/main/ets/utils/UniMpHostRuntime'; import { closeUniMpApps } from '@ohos/common/src/main/ets/utils/UniMpManager'; import * as wxopensdk from '@tencent/wechat_open_sdk'; import { emitter } from '@kit.BasicServicesKit'; @@ -15,11 +15,13 @@ import { WXApi } from '@ohos/common/src/main/ets/viewmodel/CommonService'; import { setWechatAuthCode } from '@ohos/common/src/main/ets/utils/KVManager'; import { Logger } from '@ohos/common'; import { WX_BIND_AUTHOR } from '@ohos/common/src/main/ets/constants/AppConstants'; +import { WindowSafeArea } from '@ohos/common/src/main/ets/utils/WindowSafeArea'; const DOMAIN = 0x0000; export default class AppAbility extends UIAbility { + private readonly windowSafeArea: WindowSafeArea = new WindowSafeArea(); onCreate(want: Want, _launchParam: AbilityConstant.LaunchParam): void { try { @@ -81,6 +83,7 @@ export default class AppAbility extends UIAbility { onDestroy(): void { + this.windowSafeArea.stop(); closeUniMpApps(); // 生命周期管理:销毁 hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy'); @@ -90,34 +93,30 @@ export default class AppAbility extends UIAbility { // 生命周期管理:主窗口已创建,为此功能设置主页 //获取主窗口,设置沉浸式 windowStage.getMainWindow((err, data) => { + if (err.code || !data) { + hilog.error(DOMAIN, 'AppAbility', 'Failed to get main window: %{public}s', JSON.stringify(err)); + return; + } let windowClass: window.Window = data; + this.windowSafeArea.start(windowClass, this.context); // 1. 设置窗口为全屏模式(沉浸式) - windowClass.setWindowLayoutFullScreen(true); + windowClass.setWindowLayoutFullScreen(true).then(() => { + this.windowSafeArea.refresh(); + }).catch((error: Error) => { + hilog.error(DOMAIN, 'AppAbility', 'Failed to set full screen layout: %{public}s', JSON.stringify(error)); + }); // 2. 设置状态栏文字颜色(白色/黑色) let sysBarProps: window.SystemBarProperties = { statusBarContentColor: '#000000' // 黑色文字 }; windowClass.setSystemBarProperties(sysBarProps); - - // 3. 获取避让区域(状态栏等) - // 注意:使用 window.AvoidAreaType.TYPE_SYSTEM 明确类型 - let type: window.AvoidAreaType = window.AvoidAreaType.TYPE_SYSTEM; - let avoidArea: window.AvoidArea = windowClass.getWindowAvoidArea(type); - - // 4. 计算高度并存储 (px2vp 是内置函数,直接使用) - let statusBarHeight: number = px2vp(avoidArea.topRect.height); - - // 5. 存入全局存储,Key 名为 'statusBarHeight' - AppStorage.setOrCreate('statusBarHeight', statusBarHeight); }); hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); //初始化UniMp - init(this, windowStage, { - debug: AppUtil.debug() - }) + initUniMpRuntime(this, windowStage, AppUtil.debug()); // 加载页面(启动页) windowStage.loadContent('pages/SplashScreenPage', (err) => { @@ -126,15 +125,18 @@ export default class AppAbility extends UIAbility { return; } hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.'); + this.windowSafeArea.refresh(); }); } onWindowStageDestroy(): void { + this.windowSafeArea.stop(); // 生命周期管理:主窗口已销毁,释放与UI相关的资源 hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy'); } onForeground(): void { + this.windowSafeArea.refresh(); // 生命周期管理:已处于前台页面 hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground'); } diff --git a/products/app/src/main/ets/pages/Index.ets b/products/app/src/main/ets/pages/Index.ets index 25df715..9785aba 100644 --- a/products/app/src/main/ets/pages/Index.ets +++ b/products/app/src/main/ets/pages/Index.ets @@ -1,4 +1,5 @@ import { NavigationPage } from './NavigationPage'; +import { SafeAreaPage } from '../view/SafeAreaPage'; import { ToastUtils } from '@ohos/common/src/main/ets/dialog/ToastUtils'; @Builder @@ -18,6 +19,7 @@ struct Index { //private context = this.getUIContext()?.getHostContext() as common.UIAbilityContext | undefined; // private windowClass: window.Window | undefined = undefined; private lastExitTime: number = 0; + @State private tabBarVisible: boolean = true; /* aboutToAppear() { @@ -55,9 +57,11 @@ struct Index { build() { Stack() { - NavigationPage(); + SafeAreaPage({ compactGestureBottom: this.tabBarVisible }) { + NavigationPage((visible: boolean) => { this.tabBarVisible = visible; }); + } } .width('100%') .height('100%') } -} \ No newline at end of file +} diff --git a/products/app/src/main/ets/pages/LoginPage.ets b/products/app/src/main/ets/pages/LoginPage.ets index 8a870e5..a35f57c 100644 --- a/products/app/src/main/ets/pages/LoginPage.ets +++ b/products/app/src/main/ets/pages/LoginPage.ets @@ -12,6 +12,7 @@ import { emitter } from '@kit.BasicServicesKit'; import { EVT_LOGIN_WX_AUTHOR_SUCCESS } from '@ohos/common/src/main/ets/constants/EventConstants'; import { Logger } from '@ohos/common'; import { LoginForHuawei } from '../view/LoginForHuawei'; +import { SafeAreaPage } from '../view/SafeAreaPage'; /** * 登录页面 @@ -113,6 +114,17 @@ struct LoginPage { } build() { + Stack() { + SafeAreaPage() { + this.pageContent() + } + } + .width('100%') + .height('100%') + } + + @Builder + pageContent() { Navigation(this.pageStack) { Stack() { // 1. 背景层 diff --git a/products/app/src/main/ets/pages/NavigationPage.ets b/products/app/src/main/ets/pages/NavigationPage.ets index 536ba79..675e09c 100644 --- a/products/app/src/main/ets/pages/NavigationPage.ets +++ b/products/app/src/main/ets/pages/NavigationPage.ets @@ -9,9 +9,9 @@ import { TabBarItem } from '../viewmodel/LocalBean'; * 入口布局 */ @Builder -export function NavigationPage() { +export function NavigationPage(onTabBarVisibilityChange: (visible: boolean) => void) { Column() { - TabIndex() + TabIndex({ onTabBarVisibilityChange: onTabBarVisibilityChange }) } } @@ -19,6 +19,7 @@ export function NavigationPage() { export struct TabIndex { @State currentIndex: number = 0; @State private navBarVisible: boolean = true; + onTabBarVisibilityChange: (visible: boolean) => void = () => {}; private tabController: TabsController = new TabsController(); @State tabs: TabBarItem[] = TabsViewModel.getTabData(); @StorageLink('mainBreakpoint') currentBreakpoint: string = commonConstants.breakpointsInitializeName; @@ -130,7 +131,9 @@ export struct TabIndex { } .hideTitleBar(true) .mode(NavigationMode.Stack) - .onNavBarStateChange((visible: boolean) => { this.navBarVisible = visible; }) - .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM]) + .onNavBarStateChange((visible: boolean) => { + this.navBarVisible = visible; + this.onTabBarVisibilityChange(visible); + }) } } diff --git a/products/app/src/main/ets/pages/SplashScreenPage.ets b/products/app/src/main/ets/pages/SplashScreenPage.ets index 62bd4ab..b221409 100644 --- a/products/app/src/main/ets/pages/SplashScreenPage.ets +++ b/products/app/src/main/ets/pages/SplashScreenPage.ets @@ -17,6 +17,7 @@ import { CommonService } from '@ohos/common/src/main/ets/viewmodel/CommonService import { UserProfile } from '@ohos/common/src/main/ets/viewmodel/DataBean'; import { registerUniProvider } from '@dcloudio/uni-app-runtime'; import { UniPaymentAlipayProviderImpl } from '@uni_modules/uni-payment-alipay'; +import { SafeAreaPage } from '../view/SafeAreaPage'; /** * 启动页 - Splash Screen @@ -31,6 +32,7 @@ struct SplashScreenPage { @State canSkip: boolean = false; @State hasAgreed?: boolean = undefined; @State isShowCountDown: boolean = false; + @StorageProp('statusBarHeight') statusBarHeight: number = 0; // 用于存储请求到的配置或错误状态 private isNavigated: boolean = false; @@ -178,6 +180,17 @@ struct SplashScreenPage { } build() { + Stack() { + SafeAreaPage() { + this.pageContent() + } + } + .width('100%') + .height('100%') + } + + @Builder + pageContent() { Stack() { // 1. 背景图 Image($r('app.media.ic_splash_mask')) @@ -205,7 +218,7 @@ struct SplashScreenPage { } .position({ x: '100%', y: 0 }) // 定位到右上角 .markAnchor({ x: '100%', y: 0 }) // 锚点修正 - .margin({ top: px2vp(AppStorage.get('statusBarHeight') ?? 0) + 20, right: 20 }) // 避让状态栏 + .margin({ top: this.statusBarHeight + 20, right: 20 }) // 已按窗口密度转换为 vp .padding({ left: 12, right: 12, top: 6, bottom: 6 }) .backgroundColor('#40000000') // 40% 不透明度的黑色背景 .borderRadius(15) // 圆角胶囊形状 @@ -220,4 +233,4 @@ struct SplashScreenPage { .backgroundColor('#FFFFFF') } -} \ No newline at end of file +} diff --git a/products/app/src/main/ets/view/HomeBanner.ets b/products/app/src/main/ets/view/HomeBanner.ets index ca33209..00715c9 100644 --- a/products/app/src/main/ets/view/HomeBanner.ets +++ b/products/app/src/main/ets/view/HomeBanner.ets @@ -52,7 +52,7 @@ export struct HomeBanner { Stack({ alignContent: Alignment.Bottom }) { if (this.banners.length === 0) { Image($r('app.media.ic_home_top_image')).width('100%').height('100%') - .objectFit(ImageFit.Fill) + .objectFit(ImageFit.Cover) } else { Swiper() { ForEach(this.banners, (banner: HomeBannerEntity, index: number) => { @@ -100,29 +100,27 @@ export struct HomeBanner { @Component struct HomeBannerImage { @Prop @Watch('resetImage') banner: HomeBannerEntity; - @State private imageRatio: number = BANNER_RATIO; @State private imageLoaded: boolean = false; private resetImage(): void { - this.imageRatio = BANNER_RATIO; this.imageLoaded = false; } build() { Stack({ alignContent: Alignment.Center }) { - Image($r('app.media.ic_home_top_image')).width('100%').height('100%').objectFit(ImageFit.Fill) + Image($r('app.media.ic_home_top_image')).width('100%').height('100%').objectFit(ImageFit.Cover) .opacity(this.imageLoaded ? 0 : 1) Image(this.banner.img ?? '') .alt($r('app.media.ic_home_top_image')) - .width('100%').height((BANNER_RATIO / this.imageRatio * 100) + '%') - .objectFit(ImageFit.Fill) + // 等比铺满固定容器,超出部分居中裁剪,宽图也不会在上下露出背景。 + .width('100%').height('100%') + .objectFit(ImageFit.Cover) .onComplete((event) => { if (event && event.width > 0 && event.height > 0) { - this.imageRatio = event.width / event.height; this.imageLoaded = event.loadingStatus === 1; } }) - .onError(() => { this.imageRatio = BANNER_RATIO; }) + .onError(() => { this.imageLoaded = false; }) }.width('100%').height('100%').clip(true) } } diff --git a/products/app/src/main/ets/view/SafeAreaPage.ets b/products/app/src/main/ets/view/SafeAreaPage.ets new file mode 100644 index 0000000..06e5160 --- /dev/null +++ b/products/app/src/main/ets/view/SafeAreaPage.ets @@ -0,0 +1,33 @@ +/** + * 所有路由入口共用的导航栏避让容器。 + * Navigation 和它的 NavDestination 一起缩进,子页面无需重复添加底部间距。 + * 顶部仍由页面自己的标题栏处理,保留首页背景的沉浸式效果。 + */ +@Component +export struct SafeAreaPage { + @StorageProp('navigationBarLeft') private navigationBarLeft: number = 0; + @StorageProp('navigationBarRight') private navigationBarRight: number = 0; + @StorageProp('navigationBarBottom') private navigationBarBottom: number = 0; + @StorageProp('systemNavigationBarBottom') private systemNavigationBarBottom: number = 0; + // TabBar:手势区最多 12vp,三键导航完整避让后再留 8vp;详情页使用完整安全区。 + @Prop compactGestureBottom: boolean = false; + @BuilderParam content: () => void; + + build() { + Stack() { + this.content() + } + .width('100%') + .height('100%') + .backgroundColor(Color.White) + .padding({ + left: this.navigationBarLeft, + right: this.navigationBarRight, + bottom: this.compactGestureBottom + ? (this.systemNavigationBarBottom > 0 + ? Math.max(this.systemNavigationBarBottom, this.navigationBarBottom) + : Math.min(this.navigationBarBottom, 12)) + : this.navigationBarBottom + }) + } +}