redirectTo.ts 2.1 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7 8 9 10 11
import {
  API_REDIRECT_TO,
  API_TYPE_REDIRECT_TO,
  defineAsyncApi,
  RedirectToOptions,
  RedirectToProtocol,
} from '@dcloudio/uni-api'
import { parseUrl } from '@dcloudio/uni-shared'
import { getCurrentPage } from '@dcloudio/uni-core'
import { removePage } from '../../framework/page/getCurrentPages'
import { registerPage } from '../../framework/page'
fxy060608's avatar
fxy060608 已提交
12
import { navigate, RouteOptions } from './utils'
fxy060608's avatar
fxy060608 已提交
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
import { showWebview } from './webview'
import { setStatusBarStyle } from '../../statusBar'
import { ComponentPublicInstance } from 'vue'

export const redirectTo = defineAsyncApi<API_TYPE_REDIRECT_TO>(
  API_REDIRECT_TO,
  ({ url }, { resolve, reject }) => {
    const { path, query } = parseUrl(url)
    navigate(path, () => {
      _redirectTo({
        url,
        path,
        query,
      })
        .then(resolve)
        .catch(reject)
    })
  },
  RedirectToProtocol,
  RedirectToOptions
)

fxy060608's avatar
fxy060608 已提交
35
interface RedirectToOptions extends RouteOptions {}
fxy060608's avatar
fxy060608 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87

function _redirectTo({
  url,
  path,
  query,
}: RedirectToOptions): Promise<undefined> {
  // TODO exists
  //   if (exists === 'back') {
  //     const existsPageIndex = findExistsPageIndex(url)
  //     if (existsPageIndex !== -1) {
  //       const delta = len - existsPageIndex
  //       if (delta > 0) {
  //         navigateBack({
  //           delta,
  //         })
  //         invoke(callbackId, {
  //           errMsg: 'redirectTo:ok',
  //         })
  //         return
  //       }
  //     }
  //   }

  const lastPage = getCurrentPage()
  lastPage && removePage(lastPage)

  return new Promise((resolve) => {
    showWebview(
      registerPage({
        url,
        path,
        query,
        openType: 'redirectTo',
      }),
      'none',
      0,
      () => {
        if (lastPage) {
          const webview = (lastPage as ComponentPublicInstance)
            .$getAppWebview!()
          // TODO preload
          //   if (webview.__preload__) {
          //     removePreloadWebview(webview)
          //   }
          webview.close('none')
        }
        resolve(undefined)
      }
    )
    setStatusBarStyle()
  })
}