Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions packages/taro-h5/__tests__/ui/navigation.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { eventCenter } from '@tarojs/runtime'
import * as Taro from '@tarojs/taro-h5'

import { buildApp } from '../utils'
Expand Down Expand Up @@ -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()
})
})
})
14 changes: 11 additions & 3 deletions packages/taro-h5/src/api/ui/navigation-bar/index.ts
Original file line number Diff line number Diff line change
@@ -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'

// 导航栏
Expand Down Expand Up @@ -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()
}
176 changes: 169 additions & 7 deletions packages/taro-router/__tests__/navigation-bar-test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
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'
Expand Down Expand Up @@ -42,13 +46,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'],
Expand Down Expand Up @@ -77,6 +81,164 @@ 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')

hideNavigationBarHomeButton()

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 中调用时,导航栏还未根据当前页面刷新
hideNavigationBarHomeButton()
handler.load()

expect(getFnBtn()).toBe('none')
})

it('does not hide the back button', () => {
setStackSize(2)
const handler = createHandler(OTHER_PAGE)
handler.load()

hideNavigationBarHomeButton()

expect(getFnBtn()).toBe('back')
})

it('only applies to the page instance that hid it', () => {
setStackSize(1)
const handler = createHandler(OTHER_PAGE)
handler.load()
hideNavigationBarHomeButton()
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()
hideNavigationBarHomeButton()

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')
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

现有用例都是在栈深为 1 的情况下切换页面,没覆盖最常见的 navigateTo 再 navigateBack 回来的流程。补一个用例确认中间出现返回按钮后,回到该页面时首页按钮仍保持隐藏,这个行为不管缓存最终按路由还是按页面实例都应该成立。

Suggested change
})
})
it('stays hidden after navigating to another page and back', () => {
setStackSize(1)
const handler = createHandler(OTHER_PAGE)
handler.load()
hideNavigationBarHomeButton()
const anotherPage = '/pages/another/index'
setStackSize(2)
Object.assign(handler.pageContext, { currentPage: anotherPage, originPathname: anotherPage })
handler.load()
expect(getFnBtn()).toBe('back')
setStackSize(1)
Object.assign(handler.pageContext, { currentPage: OTHER_PAGE, originPathname: OTHER_PAGE })
handler.load()
expect(getFnBtn()).toBe('none')
})

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added the navigate-away-and-back case in 213c091. It checks the back button shows on the intermediate page and the home button is still hidden after returning.


it('does not carry over to a new instance of the same route', () => {
setStackSize(1)
const handler = createHandler(OTHER_PAGE)
handler.load()
hideNavigationBarHomeButton()
expect(getFnBtn()).toBe('none')

// 例如 reLaunch 到同一路由:旧实例出栈,新实例入栈且没有调用该接口
setStackSize(1)
handler.load()

expect(getFnBtn()).toBe('home')
})
})

describe('hideHomeButton with the page handler', () => {
function createPage (path: string) {
return {
path,
options: {},
$taroParams: { stamp: 'navigation-bar-test' },
onShow: jest.fn(),
onHide: jest.fn(),
onUnload: jest.fn()
} as unknown as PageInstance
}

function createContainer (page: PageInstance) {
const el = document.createElement('div')
el.id = page.path!
el.className = 'taro_page'
document.body.appendChild(el)
return el
}

function createPageHandler (pathname: string) {
const config: SpaRouterConfig = {
pages: ['pages/index/index', 'pages/detail/index', 'pages/another/index'],
routes: [{ path: '/pages/index/index' }, { path: OTHER_PAGE }, { path: '/pages/another/index' }],
router: { mode: 'browser', basename: '', pathname },
window: { navigationStyle: 'default' }
}
return new PageHandler(config, createBrowserHistory())
}

// PageHandler 通过运行时的 location 获取当前路由,这里直接模拟路由切换
let route = OTHER_PAGE
const setRoute = (pathname: string) => {
route = pathname
}

afterEach(() => {
route = OTHER_PAGE
document.body.innerHTML = ''
})

it('stays hidden after navigateTo and navigateBack, and resets on a relaunched instance', () => {
const handler = createPageHandler(OTHER_PAGE)
jest.spyOn(handler, 'currentPage', 'get').mockImplementation(() => route)
const page = createPage(OTHER_PAGE)
createContainer(page)
// 页面在 onShow 中调用,此时路由还未刷新导航栏
;(page.onShow as jest.Mock).mockImplementation(() => hideNavigationBarHomeButton())

handler.load(page, {}, 'navigation-bar-test')
expect(getFnBtn()).toBe('none')

// navigateTo 另一个页面
const nextPage = createPage('/pages/another/index')
createContainer(nextPage)
handler.hide(page)
setRoute('/pages/another/index')
handler.load(nextPage, {}, 'navigation-bar-test')
expect(getFnBtn()).toBe('back')

// navigateBack 回到原页面
handler.unload(nextPage)
setRoute(OTHER_PAGE)
handler.show(page)
expect(getFnBtn()).toBe('none')

// reLaunch 到同一路由的新实例,且没有调用该接口
handler.unload(page)
setRoute(OTHER_PAGE)
const relaunched = createPage(OTHER_PAGE)
createContainer(relaunched)
handler.load(relaunched, {}, 'navigation-bar-test')
expect(getFnBtn()).toBe('home')
})
})

describe('setNavigationBarVisible', () => {
const isVisible = () => {
const show = navigationBar.classList.contains('taro-navigation-bar-show')
Expand Down
22 changes: 21 additions & 1 deletion packages/taro-router/src/router/navigation-bar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ 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 {
Expand All @@ -19,6 +20,8 @@ export default class NavigationBarHandler {
navigationBarElement: HTMLElement
cache: Record<string, NavigationBarCache>
isLoadDdEntry = false
// 按页面实例记录已隐藏首页按钮的页面,页面实例销毁后状态随之失效
homeButtonHiddenPages = new WeakSet<PageInstance>()

constructor (pageContext: PageHandler) {
this.cache = {}
Expand All @@ -38,6 +41,10 @@ export default class NavigationBarHandler {

if (typeof frontColor === 'string') this.setNavigationBarTextStyle(frontColor)
})

eventCenter.on('__taroH5HideHomeButton', () => {
this.hideHomeButton()
})
}

private toHomeFn () {
Expand Down Expand Up @@ -102,13 +109,26 @@ 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 时不会重新展示首页按钮
const page = stacks.last

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reran the unload case with the API call deferred by one microtask and could still reproduce the cross-page update.

  1. Open a non-home, non-tabBar H5 page A directly and confirm it shows the Return to Home button.
  2. Use navigateTo to open B. In B’s onUnload, schedule Promise.resolve().then(() => Taro.hideHomeButton()).
  3. Call navigateBack and check the button on A after it is shown again.

On base 99683d13, A keeps its button. On e835be4, A loses it with or without the return animation. By the time the microtask runs, triggerUnload has cleared isPageUnloading and stacks.last points to A, so the call records A as hidden.

The existing test calls the API synchronously inside onUnload. Could you add a case that waits for both the deferred call and A’s return, then asserts that A still shows its Return to Home button?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9832376. The unload guard now stays active until the macrotask after onUnload, so a call deferred by a microtask no longer reaches A, and onShow of the page shown right after the unload is exempt. Added a test that waits for the deferred call and A's return, then checks A still shows its Return to Home button.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for fixing the microtask case. I verified that B's deferred onUnload call now leaves A's home button alone.

There are two cases that still need coverage:

  • Open a non-home page A, navigate to B, then go back with animation enabled. If A calls Taro.hideHomeButton() in its second onShow, the Promise resolves with hideHomeButton:ok but the button stays visible. A fresh page calling it from onShow after reLaunch has the same problem. The runtime runs the user's onShow in a Promise callback, after triggerShow restores the unload guard.
  • If B schedules setTimeout(() => Taro.hideHomeButton(), 30) in onUnload, it still hides A's button after the guard clears.

Could you add regression tests using the real createPageConfig and SPA router, and assert the button state? The synchronous onShow mock misses the first case.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed the onShow case in 27bb7ca. The router no longer uses a timed unload window and instead ignores a call unless Current.page is the stack top, so A's own onShow call applies after back or reLaunch and B's microtask call from onUnload is still ignored. Added tests with the real createPageConfig, with and without animation. The setTimeout(30) one I left alone: by then Current.page is A, so a call from B can't be told apart from one A makes itself.

if (!page) return
this.homeButtonHiddenPages.add(page)
this.setFnBtnState()
}

shiftLoadingState (show: boolean) {
if (!this.loadingElement) return
if (show) {
Expand Down
4 changes: 4 additions & 0 deletions packages/taro-router/src/utils/navigate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
}
3 changes: 2 additions & 1 deletion packages/taro/types/api/ui/navigation-bar.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 等方式重新打开的页面不受影响

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we recommend calling hideHomeButton() in the onShow of the page whose button you want to hide? It would also help to mention that a delayed call can affect whichever page is current when it runs. For example, a timer scheduled in onUnload can fire after navigation and hide the button on the page the user just returned to.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated the @h5 note in 11b4d97: recommends calling it in the page's onShow and mentions that a delayed call applies to whichever page is current when it runs.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* @h5 隐藏当前页面实例 H5 导航栏中的返回首页按钮,不影响返回按钮;通过 reLaunch 等方式重新打开的页面不受影响
* @h5 隐藏当前页面实例 H5 导航栏中的返回首页按钮,不影响返回按钮;通过 reLaunch 等方式重新打开的页面不受影响。建议在需要隐藏按钮的页面的 onShow 中调用;延迟执行的调用(例如在 onUnload 中设置的定时器)会作用于执行时的当前页面,可能会隐藏用户返回后所在页面的按钮

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated the @h5 note in 11b4d97: recommends calling it in the page's onShow and mentions that a delayed call applies to whichever page is current when it runs.

* @see https://developers.weixin.qq.com/miniprogram/dev/api/ui/navigation-bar/wx.hideHomeButton.html
*/
hideHomeButton(option?: hideHomeButton.Option): Promise<TaroGeneral.CallbackResult>
Expand Down
Loading