Skip to content

Commit

Permalink
feat(runtime-web): 修复转 Web 页面相对路径跳转支持 (#20)
Browse files Browse the repository at this point in the history
  • Loading branch information
shujian-cao committed Apr 18, 2023
1 parent f72c155 commit c82b30d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
5 changes: 3 additions & 2 deletions packages/runtime-web/src/router/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { history } from './history'
import { getCurrentPages } from './pageStack'
import { batchUnloadPage } from './router'
import { IPage, IRouterApiParams } from './types'
import { getCustomUrl } from './url'
import { getAbsolutePath, getCustomUrl } from './url'

interface INavigateTask {
eventName: string
Expand All @@ -14,7 +14,8 @@ const IDLE_TIME = 20
const NAVIGATE_TASKS: INavigateTask[] = []

function getTo(url: string) {
const urlArr = getCustomUrl(url).split('?')
const absolutePath = getAbsolutePath(url)
const urlArr = getCustomUrl(absolutePath).split('?')
return {
pathname: urlArr[0],
search: urlArr[1] ? `?${urlArr[1]}` : ''
Expand Down
31 changes: 31 additions & 0 deletions packages/runtime-web/src/router/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,3 +169,34 @@ export const getRelaunchOptions = () => {
referrerInfo
}
}

/**
* 根据页面相对路径,计算出绝对路径 '../swiper/index' => 'pages/swiper/index'
* @param {String} relativePath 相对路径
* @returns 绝对路径
*/
export const getAbsolutePath = (relativePath: string) => {
const rootPath = getCurrentPages().pop()?.route

if (rootPath && relativePath[0] === '.') {
const rootParts = rootPath.split('/')
const relativeParts = relativePath.split('/')
const absoluteParts = [...relativeParts]

relativeParts.forEach((part, index) => {
if (part === '.') {
rootParts.pop()
absoluteParts.shift()
}

if (part === '..') {
index === 0 ? rootParts.splice(-2, 2) : rootParts.pop()
absoluteParts.shift()
}
})

return rootParts.concat(absoluteParts).join('/')
}

return relativePath
}

0 comments on commit c82b30d

Please sign in to comment.