Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed elements like keyboardToolbar need set position with visualViewport for PWA in iOS #13743

Open
Wetoria opened this issue Jan 7, 2025 · 0 comments

Comments

@Wetoria
Copy link

Wetoria commented Jan 7, 2025

In what scenarios do you need this feature?

pwa 模式下,使用 fixed 进行定位的元素,由于 viewport 的变化,会出现超出视窗导致看不见的情况。需要根据 visualViewport 调整定位。

比如下图是思源目前的情况,点击块进行编辑,会看不到工具栏。工具栏大概是在红框所在的位置。

image

我在插件中按照 viewport 重新定位以后,能让工具栏正常显示在键盘上方。
image

Describe the optimal solution

以下是监听和调整工具栏定位的代码。

监听 viewport 变化,记录 viewport 数据:

const viewportRef = ref<{
  [key in viewportKeys]: any;
}>({} as any)
export function useViewport() {
  let pendingUpdate = false
  function viewportHandler() {
    if (pendingUpdate) return
    pendingUpdate = true

    requestAnimationFrame(() => {
      pendingUpdate = false

      Object.values(viewportKeys).forEach((key) => {
        viewportRef.value[key] = window.visualViewport[key]
      })
    })
  }
  onMounted(() => {
    if (!listened) {
      window.visualViewport.addEventListener('scroll', viewportHandler)
      window.visualViewport.addEventListener('resize', viewportHandler)
      listened = true
    }
  })
  onBeforeUnmount(() => {
    if (listened) {
      window.visualViewport.removeEventListener('scroll', viewportHandler)
      window.visualViewport.removeEventListener('resize', viewportHandler)
    }
  })
  viewportHandler()
  return viewportRef
}

监听 viewport 数据的变化,调整工具栏的位置:

onViewportChange((newViewport) => {
  if (newViewport.height != window.innerHeight) {
    // @ts-expect-error keyboardToolbar
    window.keyboardToolbar.style.top = `${newViewport.offsetTop + newViewport.height - 42}px`
  } else {
    // @ts-expect-error keyboardToolbar
    window.keyboardToolbar.style.top = 'unset'
  }
})

Describe the candidate solution

No response

Other information

该 issue 主要为后续移动端优化时提供参考,关联 #10022

安卓不常用,所以这个问题没在安卓上进行测试。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant