diff --git a/packages/taro-h5/__tests__/ui/navigation.test.ts b/packages/taro-h5/__tests__/ui/navigation.test.ts index cac40c9ba0dc..9b9a0cef3c05 100644 --- a/packages/taro-h5/__tests__/ui/navigation.test.ts +++ b/packages/taro-h5/__tests__/ui/navigation.test.ts @@ -1,3 +1,4 @@ +import { eventCenter } from '@tarojs/runtime' import * as Taro from '@tarojs/taro-h5' import { buildApp } from '../utils' @@ -96,4 +97,26 @@ describe('navigation', () => { }) }) }) + describe('hideHomeButton', () => { + test('should ask the navigation bar to hide the home button', async () => { + const listener = jest.fn() + const success = jest.fn() + const fail = jest.fn() + const complete = jest.fn() + const expectRes = { errMsg: 'hideHomeButton:ok' } + eventCenter.on('__taroH5HideHomeButton', listener) + + try { + await expect(Taro.hideHomeButton({ success, fail, complete })).resolves.toEqual(expectRes) + await expect(Taro.hideHomeButton()).resolves.toEqual(expectRes) + } finally { + eventCenter.off('__taroH5HideHomeButton', listener) + } + + expect(listener).toHaveBeenCalledTimes(2) + expect(success.mock.calls).toEqual([[expectRes]]) + expect(complete.mock.calls).toEqual([[expectRes]]) + expect(fail).not.toHaveBeenCalled() + }) + }) }) diff --git a/packages/taro-h5/src/api/ui/navigation-bar/index.ts b/packages/taro-h5/src/api/ui/navigation-bar/index.ts index 51a28d0923a5..59eac8d8f63c 100644 --- a/packages/taro-h5/src/api/ui/navigation-bar/index.ts +++ b/packages/taro-h5/src/api/ui/navigation-bar/index.ts @@ -1,7 +1,7 @@ import Taro from '@tarojs/api' -import { setNavigationBarLoading, setNavigationBarStyle, setTitle } from '@tarojs/router' +import { hideNavigationBarHomeButton, setNavigationBarLoading, setNavigationBarStyle, setTitle } from '@tarojs/router' -import { getParameterError, shouldBeObject, temporarilyNotSupport } from '../../../utils' +import { getParameterError, shouldBeObject } from '../../../utils' import { MethodHandler } from '../../../utils/handler' // 导航栏 @@ -66,4 +66,12 @@ export function hideNavigationBarLoading (options: Taro.hideNavigationBarLoading return handle.success() } -export const hideHomeButton = /* @__PURE__ */ temporarilyNotSupport('hideHomeButton') +/** + * 隐藏当前页面导航栏中的返回首页按钮 + */ +export const hideHomeButton: typeof Taro.hideHomeButton = (options = {}) => { + const { success, fail, complete } = options + const handle = new MethodHandler({ name: 'hideHomeButton', success, fail, complete }) + hideNavigationBarHomeButton() + return handle.success() +} diff --git a/packages/taro-router/__tests__/navigation-bar-test.ts b/packages/taro-router/__tests__/navigation-bar-test.ts index 40d1589ff767..0862c9174406 100644 --- a/packages/taro-router/__tests__/navigation-bar-test.ts +++ b/packages/taro-router/__tests__/navigation-bar-test.ts @@ -1,8 +1,13 @@ +import { Current, createPageConfig, document as taroDocument, injectPageInstance } from '@tarojs/runtime' +import { createBrowserHistory } from 'history' + import NavigationBarHandler from '../src/router/navigation-bar' +import PageHandler from '../src/router/page' import stacks from '../src/router/stack' +import { hideNavigationBarHomeButton } from '../src/utils/navigate' import type { PageInstance } from '@tarojs/runtime' -import type PageHandler from '../src/router/page' +import type { SpaRouterConfig } from '../types/router' const HOME_PAGE = '/pages/index/index' const OTHER_PAGE = '/pages/detail/index' @@ -23,6 +28,12 @@ function createHandler (currentPage: string, options: { } as unknown as PageHandler) } +// 页面的生命周期执行时,Current.page 指向该页面 +function hideAsCurrentPage () { + Current.page = stacks.last as any + hideNavigationBarHomeButton() +} + function setStackSize (size: number) { while (stacks.length > 0) stacks.pop() for (let i = 0; i < size; i++) stacks.push({} as PageInstance) @@ -42,13 +53,13 @@ describe('NavigationBarHandler', () => { setStackSize(0) }) - describe('setFnBtnState', () => { - const getFnBtn = () => { - if (navigationBar.classList.contains('taro-navigation-bar-back-icon')) return 'back' - if (navigationBar.classList.contains('taro-navigation-bar-home-icon')) return 'home' - return 'none' - } + const getFnBtn = () => { + if (navigationBar.classList.contains('taro-navigation-bar-back-icon')) return 'back' + if (navigationBar.classList.contains('taro-navigation-bar-home-icon')) return 'home' + return 'none' + } + describe('setFnBtnState', () => { it.each([ ['the home page opened as the only page', HOME_PAGE, 1, 'none'], ['the home page navigated to from another page', HOME_PAGE, 2, 'back'], @@ -77,6 +88,272 @@ describe('NavigationBarHandler', () => { }) }) + describe('hideHomeButton', () => { + it('hides the home button of the current page', () => { + setStackSize(1) + const handler = createHandler(OTHER_PAGE) + handler.load() + expect(getFnBtn()).toBe('home') + + hideAsCurrentPage() + + expect(getFnBtn()).toBe('none') + }) + + it('keeps the home button hidden when called before the page is loaded', () => { + setStackSize(1) + const handler = createHandler(OTHER_PAGE) + + // 页面在 onShow 中调用时,导航栏还未根据当前页面刷新 + hideAsCurrentPage() + handler.load() + + expect(getFnBtn()).toBe('none') + }) + + it('does not hide the back button', () => { + setStackSize(2) + const handler = createHandler(OTHER_PAGE) + handler.load() + + hideAsCurrentPage() + + expect(getFnBtn()).toBe('back') + }) + + it('only applies to the page instance that hid it', () => { + setStackSize(1) + const handler = createHandler(OTHER_PAGE) + handler.load() + hideAsCurrentPage() + expect(getFnBtn()).toBe('none') + + const anotherPage = '/pages/another/index' + setStackSize(1) + Object.assign(handler.pageContext, { currentPage: anotherPage, originPathname: anotherPage }) + handler.load() + expect(getFnBtn()).toBe('home') + }) + + it('stays hidden after navigating to another page and back', () => { + setStackSize(1) + const handler = createHandler(OTHER_PAGE) + handler.load() + hideAsCurrentPage() + + const anotherPage = '/pages/another/index' + const original = stacks.last + stacks.push({} as PageInstance) + Object.assign(handler.pageContext, { currentPage: anotherPage, originPathname: anotherPage }) + handler.load() + expect(getFnBtn()).toBe('back') + + stacks.pop() + expect(stacks.last).toBe(original) + Object.assign(handler.pageContext, { currentPage: OTHER_PAGE, originPathname: OTHER_PAGE }) + handler.load() + expect(getFnBtn()).toBe('none') + }) + + it('does not carry over to a new instance of the same route', () => { + setStackSize(1) + const handler = createHandler(OTHER_PAGE) + handler.load() + hideAsCurrentPage() + expect(getFnBtn()).toBe('none') + + // 例如 reLaunch 到同一路由:旧实例出栈,新实例入栈且没有调用该接口 + setStackSize(1) + handler.load() + + expect(getFnBtn()).toBe('home') + }) + }) + + describe('hideHomeButton with the real page config', () => { + const ANOTHER_PAGE = '/pages/another/index' + const STAMP = 'navigation-bar-test' + + type Lifecycles = Partial void>> + + let route = OTHER_PAGE + let handler: PageHandler + + // 与 connect 一致:挂载页面时创建页面容器并注册页面实例,用户生命周期通过 safeExecute 在 hasLoaded 之后执行 + function createPage (path: string, lifecycles: Lifecycles = {}) { + const component = { onShow: jest.fn(lifecycles.onShow), onUnload: jest.fn(lifecycles.onUnload) } + Current.app = { + mount: (_component, $taroPath, cb) => { + const el = document.createElement('div') + el.id = $taroPath + el.className = 'taro_page' + document.body.appendChild(el) + const root = taroDocument.createElement('root') + root.id = $taroPath + taroDocument.body.appendChild(root) + injectPageInstance(component as any, $taroPath) + cb() + }, + unmount: (_$taroPath, cb) => cb() + } as any + const page = createPageConfig(component, path, {}, {}) as unknown as PageInstance + page.options = { stamp: STAMP } + return { page, component } + } + + function load (page: PageInstance, path: string) { + route = path + handler.load(page, {}, STAMP) + } + + function back (from: PageInstance, to: PageInstance, path: string) { + handler.unload(from, 1) + route = path + handler.show(to) + } + + // 用户的 onShow 在 Promise 回调中执行,需要等待微任务 + const flush = async () => { + for (let i = 0; i < 5; i++) await Promise.resolve() + } + + // H5 端页面路径会写入页面配置,同时页面挂载后同步执行回调 + const platform = process.env.TARO_PLATFORM + beforeAll(() => { + process.env.TARO_PLATFORM = 'web' + }) + + afterAll(() => { + process.env.TARO_PLATFORM = platform + }) + + beforeEach(() => { + route = OTHER_PAGE + const config: SpaRouterConfig = { + pages: ['pages/index/index', 'pages/detail/index', 'pages/another/index'], + routes: [{ path: HOME_PAGE }, { path: OTHER_PAGE }, { path: ANOTHER_PAGE }], + router: { mode: 'browser', basename: '', pathname: OTHER_PAGE }, + window: { navigationStyle: 'default' } + } + handler = new PageHandler(config, createBrowserHistory()) + jest.spyOn(handler, 'currentPage', 'get').mockImplementation(() => route) + }) + + afterEach(() => { + jest.useRealTimers() + Current.page = null + document.body.innerHTML = '' + }) + + it('stays hidden after navigateTo and navigateBack, and resets on a relaunched instance', async () => { + const { page: pageA, component: a } = createPage(OTHER_PAGE) + // 只在第一次 onShow 中调用 + a.onShow.mockImplementationOnce(() => hideNavigationBarHomeButton()) + load(pageA, OTHER_PAGE) + await flush() + expect(getFnBtn()).toBe('none') + + const { page: pageB } = createPage(ANOTHER_PAGE) + handler.hide(pageA) + load(pageB, ANOTHER_PAGE) + await flush() + expect(getFnBtn()).toBe('back') + + back(pageB, pageA, OTHER_PAGE) + await flush() + expect(a.onShow).toHaveBeenCalledTimes(2) + expect(getFnBtn()).toBe('none') + + // reLaunch 到同一路由的新实例,且没有调用该接口 + handler.unload(pageA) + const { page: relaunched } = createPage(OTHER_PAGE) + load(relaunched, OTHER_PAGE) + await flush() + expect(getFnBtn()).toBe('home') + }) + + describe.each([ + ['without animation', false], + ['with animation', true] + ])('on the page navigated back to %s', (_name, animated) => { + async function openAThenB (lifecyclesB: Lifecycles = {}, lifecyclesA: Lifecycles = {}) { + const a = createPage(OTHER_PAGE, lifecyclesA) + load(a.page, OTHER_PAGE) + await flush() + expect(getFnBtn()).toBe('home') + + const b = createPage(ANOTHER_PAGE, lifecyclesB) + handler.hide(a.page) + load(b.page, ANOTHER_PAGE) + await flush() + return { a, b } + } + + // 带动画时页面在动画结束后才卸载,之后再展示目标页面 + async function goBack (from: PageInstance, to: PageInstance) { + if (animated) { + jest.useFakeTimers() + handler.unload(from, 1, true) + await jest.advanceTimersByTimeAsync(handler.animationDuration) + route = OTHER_PAGE + handler.show(to) + } else { + back(from, to, OTHER_PAGE) + } + await flush() + } + + it('does not hide the home button when the popped page calls it synchronously in onUnload', async () => { + const { a, b } = await openAThenB({ onUnload: () => hideNavigationBarHomeButton() }) + + await goBack(b.page, a.page) + + expect(b.component.onUnload).toHaveBeenCalledTimes(1) + expect(getFnBtn()).toBe('home') + }) + + it('does not hide the home button when the popped page calls it from a microtask in onUnload', async () => { + let deferred: Promise = Promise.resolve() + const { a, b } = await openAThenB({ + onUnload: () => { + deferred = Promise.resolve().then(() => hideNavigationBarHomeButton()) + } + }) + + await goBack(b.page, a.page) + await deferred + + expect(b.component.onUnload).toHaveBeenCalledTimes(1) + expect(getFnBtn()).toBe('home') + }) + + it('applies a call made in onShow when the page is shown again', async () => { + const { a, b } = await openAThenB() + // 只在返回后的第二次 onShow 中调用 + a.component.onShow.mockImplementationOnce(() => hideNavigationBarHomeButton()) + + await goBack(b.page, a.page) + + expect(a.component.onShow).toHaveBeenCalledTimes(2) + expect(getFnBtn()).toBe('none') + }) + }) + + it('applies a call made in onShow of a page opened by reLaunch', async () => { + const { page: pageA } = createPage(OTHER_PAGE) + load(pageA, OTHER_PAGE) + await flush() + expect(getFnBtn()).toBe('home') + + handler.unload(pageA) + const { page: relaunched } = createPage(ANOTHER_PAGE, { onShow: () => hideNavigationBarHomeButton() }) + load(relaunched, ANOTHER_PAGE) + await flush() + + expect(getFnBtn()).toBe('none') + }) + }) + describe('setNavigationBarVisible', () => { const isVisible = () => { const show = navigationBar.classList.contains('taro-navigation-bar-show') diff --git a/packages/taro-router/src/router/navigation-bar.ts b/packages/taro-router/src/router/navigation-bar.ts index 21fcb4ae6825..cdf9cde46de4 100644 --- a/packages/taro-router/src/router/navigation-bar.ts +++ b/packages/taro-router/src/router/navigation-bar.ts @@ -1,9 +1,10 @@ -import { eventCenter } from '@tarojs/runtime' +import { Current, eventCenter } from '@tarojs/runtime' import { navigateBack, reLaunch } from '../api' import { isDingTalk } from '../utils' import stacks from './stack' +import type { PageInstance } from '@tarojs/runtime' import type PageHandler from './page' interface NavigationBarCache { @@ -19,6 +20,10 @@ export default class NavigationBarHandler { navigationBarElement: HTMLElement cache: Record isLoadDdEntry = false + // 页面在 onUnload 中(已出栈)时,忽略对栈顶页面的首页按钮设置 + isPageUnloading = false + // 按页面实例记录已隐藏首页按钮的页面,页面实例销毁后状态随之失效 + homeButtonHiddenPages = new WeakSet() constructor (pageContext: PageHandler) { this.cache = {} @@ -38,6 +43,10 @@ export default class NavigationBarHandler { if (typeof frontColor === 'string') this.setNavigationBarTextStyle(frontColor) }) + + eventCenter.on('__taroH5HideHomeButton', () => { + this.hideHomeButton() + }) } private toHomeFn () { @@ -102,13 +111,28 @@ export default class NavigationBarHandler { this.fnBtnToggleToNone() } else if (stacks.length > 1) { this.fnBtnToggleToBack() - } else if (this.pageContext.homePage === currentRouter) { + } else if (this.pageContext.homePage === currentRouter || this.isHomeButtonHidden()) { this.fnBtnToggleToNone() } else { this.fnBtnToggleToHome() } } + private isHomeButtonHidden () { + const page = stacks.last + return !!page && this.homeButtonHiddenPages.has(page) + } + + hideHomeButton () { + // Note: 页面通常在 onShow 中调用,此时 load 尚未执行,但页面已入栈,直接记录在页面实例上,确保 load 时不会重新展示首页按钮 + if (this.isPageUnloading) return + const page = stacks.last + // Note: Current.page 是最近一次执行生命周期的页面。已出栈页面在 onUnload 中通过微任务延后的调用,会早于目标页面的 onShow,此时它不是栈顶页面 + if (!page || Current.page !== page) return + this.homeButtonHiddenPages.add(page) + this.setFnBtnState() + } + shiftLoadingState (show: boolean) { if (!this.loadingElement) return if (show) { diff --git a/packages/taro-router/src/router/page.ts b/packages/taro-router/src/router/page.ts index b8c326a46720..e6ce3eadd89c 100644 --- a/packages/taro-router/src/router/page.ts +++ b/packages/taro-router/src/router/page.ts @@ -202,6 +202,17 @@ export default class PageHandler { } } + // Note: 页面出栈后才会执行 onUnload,此时栈顶已是目标页面,需要避免已出栈页面在 onUnload 中同步调用的导航栏方法作用到目标页面 + protected triggerUnload (page?: PageInstance | null) { + const handler = this.navigationBarHandler + handler.isPageUnloading = true + try { + page?.onUnload?.() + } finally { + handler.isPageUnloading = false + } + } + unload (page?: PageInstance | null, delta = 1, top = false) { if (!page) return @@ -210,7 +221,7 @@ export default class PageHandler { if (this.animation && top) { if (this.unloadTimer) { clearTimeout(this.unloadTimer) - this.lastUnloadPage?.onUnload?.() + this.triggerUnload(this.lastUnloadPage) this.unloadTimer = null } this.lastUnloadPage = page @@ -223,14 +234,14 @@ export default class PageHandler { this.unloadTimer = setTimeout(() => { this.unloadTimer = null - this.lastUnloadPage?.onUnload?.() + this.triggerUnload(this.lastUnloadPage) eventCenter.trigger('__taroPageOnShowAfterDestroyed') }, this.animationDuration) } else { const pageEl = this.getPageContainer(page) pageEl?.classList.remove('taro_page_stationed') pageEl?.classList.remove('taro_page_show') - page?.onUnload?.() + this.triggerUnload(page) setTimeout(() => { eventCenter.trigger('__taroPageOnShowAfterDestroyed') }, 0) diff --git a/packages/taro-router/src/utils/navigate.ts b/packages/taro-router/src/utils/navigate.ts index 851c75f83f31..7f365ad5ad6d 100644 --- a/packages/taro-router/src/utils/navigate.ts +++ b/packages/taro-router/src/utils/navigate.ts @@ -30,3 +30,7 @@ export function setNavigationBarStyle (option: { backgroundColor: string, frontC export function setNavigationBarLoading (loading: boolean): void { eventCenter.trigger('__taroH5setNavigationBarLoading', loading) } + +export function hideNavigationBarHomeButton (): void { + eventCenter.trigger('__taroH5HideHomeButton') +} diff --git a/packages/taro/types/api/ui/navigation-bar.d.ts b/packages/taro/types/api/ui/navigation-bar.d.ts index d978a3fe2642..2e887684926d 100644 --- a/packages/taro/types/api/ui/navigation-bar.d.ts +++ b/packages/taro/types/api/ui/navigation-bar.d.ts @@ -122,7 +122,8 @@ declare module '../../index' { hideNavigationBarLoading(option?: hideNavigationBarLoading.Option): void /** 隐藏返回首页按钮。微信7.0.7版本起,当用户打开的小程序最底层页面是非首页时,默认展示“返回首页”按钮,开发者可在页面 onShow 中调用 hideHomeButton 进行隐藏。 - * @supported weapp, tt, harmony + * @supported weapp, tt, h5, harmony + * @h5 隐藏当前页面实例 H5 导航栏中的返回首页按钮,不影响返回按钮;通过 reLaunch 等方式重新打开的页面不受影响。建议在需要隐藏按钮的页面的 onShow 中调用;延迟执行的调用(例如在 onUnload 中设置的定时器)会作用于执行时的当前页面,可能会隐藏用户返回后所在页面的按钮 * @see https://developers.weixin.qq.com/miniprogram/dev/api/ui/navigation-bar/wx.hideHomeButton.html */ hideHomeButton(option?: hideHomeButton.Option): Promise