page.ts 7.4 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6
import {
  VNode,
  nextTick,
  computed,
  ConcreteComponent,
  ComponentPublicInstance,
fxy060608's avatar
fxy060608 已提交
7
  ComponentInternalInstance,
fxy060608's avatar
fxy060608 已提交
8
} from 'vue'
fxy060608's avatar
fxy060608 已提交
9
import { useRoute, RouteLocationNormalizedLoaded } from 'vue-router'
fxy060608's avatar
fxy060608 已提交
10 11 12 13 14
import {
  invokeHook,
  disableScrollListener,
  createScrollListener,
  CreateScrollListenerOptions,
fxy060608's avatar
fxy060608 已提交
15
  initPageInternalInstance,
fxy060608's avatar
fxy060608 已提交
16
  initPageVm,
fxy060608's avatar
fxy060608 已提交
17
} from '@dcloudio/uni-core'
fxy060608's avatar
fxy060608 已提交
18 19 20 21 22 23
import {
  ON_PAGE_SCROLL,
  ON_REACH_BOTTOM,
  ON_REACH_BOTTOM_DISTANCE,
  ON_UNLOAD,
} from '@dcloudio/uni-shared'
fxy060608's avatar
fxy060608 已提交
24
import { usePageMeta } from './provide'
fxy060608's avatar
fxy060608 已提交
25
import { NavigateType } from '../../service/api/route/utils'
fxy060608's avatar
fxy060608 已提交
26
import { updateCurPageCssVar } from '../../helpers/cssVar'
fxy060608's avatar
fxy060608 已提交
27
import { getStateId } from '../../helpers/dom'
fxy060608's avatar
fxy060608 已提交
28 29 30

const SEP = '$$'

fxy060608's avatar
fxy060608 已提交
31
const currentPagesMap = new Map<string, ComponentPublicInstance>()
fxy060608's avatar
fxy060608 已提交
32

fxy060608's avatar
fxy060608 已提交
33 34
function pruneCurrentPages() {
  currentPagesMap.forEach((page, id) => {
35
    if ((page as unknown as ComponentPublicInstance).$.isUnmounted) {
fxy060608's avatar
fxy060608 已提交
36 37 38 39 40
      currentPagesMap.delete(id)
    }
  })
}

fxy060608's avatar
fxy060608 已提交
41 42
export function getCurrentPagesMap() {
  return currentPagesMap
fxy060608's avatar
fxy060608 已提交
43 44
}

fxy060608's avatar
fxy060608 已提交
45
export function getCurrentPages() {
fxy060608's avatar
fxy060608 已提交
46
  const curPages: ComponentPublicInstance[] = []
fxy060608's avatar
fxy060608 已提交
47 48
  const pages = currentPagesMap.values()
  for (const page of pages) {
fxy060608's avatar
fxy060608 已提交
49
    if (page.$.__isTabBar) {
fxy060608's avatar
fxy060608 已提交
50
      if (page.$.__isActive) {
fxy060608's avatar
fxy060608 已提交
51
        curPages.push(page)
fxy060608's avatar
fxy060608 已提交
52
      }
fxy060608's avatar
fxy060608 已提交
53 54
    } else {
      curPages.push(page)
fxy060608's avatar
fxy060608 已提交
55
    }
fxy060608's avatar
fxy060608 已提交
56
  }
fxy060608's avatar
fxy060608 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70
  return curPages
}

function removeRouteCache(routeKey: string) {
  const vnode = pageCacheMap.get(routeKey)
  if (vnode) {
    pageCacheMap.delete(routeKey)
    routeCache.pruneCacheEntry!(vnode)
  }
}

export function removePage(routeKey: string, removeRouteCaches = true) {
  const pageVm = currentPagesMap.get(routeKey) as ComponentPublicInstance
  pageVm.$.__isUnload = true
fxy060608's avatar
fxy060608 已提交
71
  invokeHook(pageVm, ON_UNLOAD)
fxy060608's avatar
fxy060608 已提交
72 73
  currentPagesMap.delete(routeKey)
  removeRouteCaches && removeRouteCache(routeKey)
fxy060608's avatar
fxy060608 已提交
74 75
}

fxy060608's avatar
fxy060608 已提交
76
let id = /*#__PURE__*/ getStateId()
fxy060608's avatar
fxy060608 已提交
77

fxy060608's avatar
fxy060608 已提交
78
export function createPageState(type: NavigateType, __id__?: number) {
fxy060608's avatar
fxy060608 已提交
79
  return {
fxy060608's avatar
fxy060608 已提交
80
    __id__: __id__ || ++id,
fxy060608's avatar
fxy060608 已提交
81 82 83 84 85
    __type__: type,
  }
}

function initPublicPage(route: RouteLocationNormalizedLoaded) {
86
  const meta = usePageMeta()
fxy060608's avatar
fxy060608 已提交
87

fxy060608's avatar
fxy060608 已提交
88
  if (!__UNI_FEATURE_PAGES__) {
fxy060608's avatar
fxy060608 已提交
89
    return initPageInternalInstance('navigateTo', __uniRoutes[0].path, {}, meta)
fxy060608's avatar
fxy060608 已提交
90
  }
fxy060608's avatar
fxy060608 已提交
91
  let fullPath = route.fullPath
fxy060608's avatar
fxy060608 已提交
92
  if (route.meta.isEntry && fullPath.indexOf(route.meta.route) === -1) {
fxy060608's avatar
fxy060608 已提交
93 94 95
    fullPath = '/' + route.meta.route + fullPath.replace('/', '')
  }
  return initPageInternalInstance('navigateTo', fullPath, {}, meta)
fxy060608's avatar
fxy060608 已提交
96 97 98 99
}

export function initPage(vm: ComponentPublicInstance) {
  const route = vm.$route
fxy060608's avatar
fxy060608 已提交
100
  const page = initPublicPage(route)
fxy060608's avatar
fxy060608 已提交
101
  initPageVm(vm, page)
fxy060608's avatar
fxy060608 已提交
102
  currentPagesMap.set(normalizeRouteKey(page.path, page.id), vm)
fxy060608's avatar
fxy060608 已提交
103 104
}

fxy060608's avatar
fxy060608 已提交
105
export function normalizeRouteKey(path: string, id: number) {
fxy060608's avatar
fxy060608 已提交
106
  return path + SEP + id
fxy060608's avatar
fxy060608 已提交
107 108 109 110
}

export function useKeepAliveRoute() {
  const route = useRoute()
fxy060608's avatar
fxy060608 已提交
111 112 113
  const routeKey = computed(() =>
    normalizeRouteKey('/' + route.meta.route, getStateId())
  )
fxy060608's avatar
fxy060608 已提交
114
  const isTabBar = computed(() => route.meta.isTabBar)
fxy060608's avatar
fxy060608 已提交
115 116
  return {
    routeKey,
fxy060608's avatar
fxy060608 已提交
117
    isTabBar,
fxy060608's avatar
fxy060608 已提交
118 119 120
    routeCache,
  }
}
fxy060608's avatar
fxy060608 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145

// https://github.com/vuejs/rfcs/pull/284
// https://github.com/vuejs/vue-next/pull/3414

type CacheKey = string | number | ConcreteComponent
interface KeepAliveCache {
  get(key: CacheKey): VNode | void
  set(key: CacheKey, value: VNode): void
  delete(key: CacheKey): void
  forEach(
    fn: (value: VNode, key: CacheKey, map: Map<CacheKey, VNode>) => void,
    thisArg?: any
  ): void
  pruneCacheEntry?: (cached: VNode) => void
}
const pageCacheMap = new Map<CacheKey, VNode>()
const routeCache: KeepAliveCache = {
  get(key) {
    return pageCacheMap.get(key)
  },
  set(key, value) {
    pruneRouteCache(key as string)
    pageCacheMap.set(key, value)
  },
  delete(key) {
fxy060608's avatar
fxy060608 已提交
146 147 148 149
    const vnode = pageCacheMap.get(key)
    if (!vnode) {
      return
    }
fxy060608's avatar
fxy060608 已提交
150 151 152 153 154 155 156
    pageCacheMap.delete(key)
  },
  forEach(fn) {
    pageCacheMap.forEach(fn)
  },
}

fxy060608's avatar
fxy060608 已提交
157
function isTabBarVNode(vnode: VNode): boolean {
fxy060608's avatar
fxy060608 已提交
158
  return vnode.props!.type === 'tabBar'
fxy060608's avatar
fxy060608 已提交
159 160
}

fxy060608's avatar
fxy060608 已提交
161 162 163 164 165 166 167 168
function pruneRouteCache(key: string) {
  const pageId = parseInt(key.split(SEP)[1])
  if (!pageId) {
    return
  }
  routeCache.forEach((vnode, key) => {
    const cPageId = parseInt((key as string).split(SEP)[1])
    if (cPageId && cPageId > pageId) {
fxy060608's avatar
fxy060608 已提交
169
      if (__UNI_FEATURE_TABBAR__ && isTabBarVNode(vnode)) {
fxy060608's avatar
fxy060608 已提交
170
        // tabBar keep alive
fxy060608's avatar
fxy060608 已提交
171
        return
fxy060608's avatar
fxy060608 已提交
172
      }
fxy060608's avatar
fxy060608 已提交
173 174 175 176 177 178
      routeCache.delete(key)
      routeCache.pruneCacheEntry!(vnode)
      nextTick(() => pruneCurrentPages())
    }
  })
}
fxy060608's avatar
fxy060608 已提交
179

fxy060608's avatar
fxy060608 已提交
180
function updateCurPageAttrs(pageMeta: UniApp.PageRouteMeta) {
fxy060608's avatar
fxy060608 已提交
181
  const nvueDirKey = 'nvue-dir-' + __uniConfig.nvue!['flex-direction']
fxy060608's avatar
fxy060608 已提交
182 183 184 185 186 187 188 189 190
  if (pageMeta.isNVue) {
    document.body.setAttribute('nvue', '')
    document.body.setAttribute(nvueDirKey, '')
  } else {
    document.body.removeAttribute('nvue')
    document.body.removeAttribute(nvueDirKey)
  }
}

fxy060608's avatar
fxy060608 已提交
191 192 193 194
export function onPageShow(
  instance: ComponentInternalInstance,
  pageMeta: UniApp.PageRouteMeta
) {
fxy060608's avatar
fxy060608 已提交
195
  updateBodyScopeId(instance)
fxy060608's avatar
fxy060608 已提交
196
  updateCurPageCssVar(pageMeta)
fxy060608's avatar
fxy060608 已提交
197
  updateCurPageAttrs(pageMeta)
fxy060608's avatar
fxy060608 已提交
198 199 200
  initPageScrollListener(instance, pageMeta)
}

fxy060608's avatar
fxy060608 已提交
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
export function onPageReady(instance: ComponentInternalInstance) {
  const scopeId = getScopeId(instance)
  scopeId && updateCurPageBodyScopeId(scopeId)
}

function updateCurPageBodyScopeId(scopeId: string) {
  const pageBodyEl = document.querySelector('uni-page-body')
  if (pageBodyEl) {
    pageBodyEl.setAttribute(scopeId, '')
  } else if (__DEV__) {
    console.warn('uni-page-body not found')
  }
}

function getScopeId(instance: ComponentInternalInstance) {
  return (instance.type as any).__scopeId
}

let curScopeId: string
function updateBodyScopeId(instance: ComponentInternalInstance) {
  const scopeId = getScopeId(instance)
  const { body } = document
  curScopeId && body.removeAttribute(curScopeId!)
  scopeId && body.setAttribute(scopeId, '')
  curScopeId = scopeId!
}

fxy060608's avatar
fxy060608 已提交
228
let curScrollListener: (evt: Event) => any
fxy060608's avatar
fxy060608 已提交
229
// TODO 当动态渲染的组件内监听onPageScroll时
fxy060608's avatar
fxy060608 已提交
230 231 232 233 234 235 236 237 238 239 240
function initPageScrollListener(
  instance: ComponentInternalInstance,
  pageMeta: UniApp.PageRouteMeta
) {
  document.removeEventListener('touchmove', disableScrollListener)
  if (curScrollListener) {
    document.removeEventListener('scroll', curScrollListener)
  }
  if (pageMeta.disableScroll) {
    return document.addEventListener('touchmove', disableScrollListener)
  }
fxy060608's avatar
fxy060608 已提交
241

fxy060608's avatar
fxy060608 已提交
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
  const { onPageScroll, onReachBottom } = instance
  const navigationBarTransparent = pageMeta.navigationBar.type === 'transparent'
  if (!onPageScroll && !onReachBottom && !navigationBarTransparent) {
    return
  }
  const opts: CreateScrollListenerOptions = {}
  const pageId = instance.proxy!.$page.id
  if (onPageScroll || navigationBarTransparent) {
    opts.onPageScroll = createOnPageScroll(
      pageId,
      onPageScroll,
      navigationBarTransparent
    )
  }
  if (onReachBottom) {
    opts.onReachBottomDistance =
      pageMeta.onReachBottomDistance || ON_REACH_BOTTOM_DISTANCE
    opts.onReachBottom = () =>
fxy060608's avatar
fxy060608 已提交
260
      UniViewJSBridge.publishHandler(ON_REACH_BOTTOM, {}, pageId)
fxy060608's avatar
fxy060608 已提交
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
  }
  curScrollListener = createScrollListener(opts)
  // 避免监听太早,直接触发了 scroll
  requestAnimationFrame(() =>
    document.addEventListener('scroll', curScrollListener)
  )
}

function createOnPageScroll(
  pageId: number,
  onPageScroll: unknown,
  navigationBarTransparent: boolean
) {
  return (scrollTop: number) => {
    if (onPageScroll) {
fxy060608's avatar
fxy060608 已提交
276
      UniViewJSBridge.publishHandler(ON_PAGE_SCROLL, { scrollTop }, pageId)
fxy060608's avatar
fxy060608 已提交
277 278
    }
    if (navigationBarTransparent) {
fxy060608's avatar
fxy060608 已提交
279
      UniViewJSBridge.emit(pageId + '.' + ON_PAGE_SCROLL, {
fxy060608's avatar
fxy060608 已提交
280 281 282 283 284
        scrollTop,
      })
    }
  }
}