All files / mp patchMiniProgram.ts

0% Statements 0/117
0% Branches 0/27
0% Functions 0/26
0% Lines 0/117

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 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 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 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 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
import { AnyObject } from '../types'
import { currentPageListeners, miniProgramBus } from './miniProgramBus'
import { ensureInMiniProgram } from './ensureInMiniProgram'
import { getCurrentPagePath } from './getCurrentPagePath'
import { getCurrentPageQuery } from './getCurrentPageQuery'
import { getCurrentPageUrl } from './getCurrentPageUrl'
import { last, MiniProgramApi } from '../utils'
 
let prevPagesInfo:
  | {
      count: number
      lastPageUrl: string
      lastPagePath: string
      lastPageQuery: AnyObject
    }
  | undefined
 
function patchAppOptions(
  mp: MiniProgramApi,
  appOptions: WechatMiniprogram.App.Options<{}>,
) {
  const onLaunch = appOptions.onLaunch
  appOptions.onLaunch = function (launchOptions) {
    miniProgramBus.emit({ name: 'appLaunch', context: this }, launchOptions)
    return onLaunch?.call(this, launchOptions)
  }
 
  const onShow = appOptions.onShow
  appOptions.onShow = function (showOptions) {
    miniProgramBus.emit({ name: 'appShow', context: this }, showOptions)
    return onShow?.call(this, showOptions)
  }
 
  const onHide = appOptions.onHide
  appOptions.onHide = function () {
    miniProgramBus.emit({ name: 'appHide', context: this })
    return onHide?.call(this)
  }
 
  const onError = appOptions.onError
  appOptions.onError = function (error) {
    miniProgramBus.emit({ name: 'appError', context: this }, error)
    return onError?.call(this, error)
  }
 
  const onPageNotFound = appOptions.onPageNotFound
  appOptions.onPageNotFound = function (payload) {
    miniProgramBus.emit({ name: 'pageNotFound', context: this }, payload)
    return onPageNotFound?.call(this, payload)
  }
 
  const onUnhandledRejection = appOptions.onUnhandledRejection
  appOptions.onUnhandledRejection = function (payload) {
    miniProgramBus.emit(
      { name: 'appUnhandledRejectionThrow', context: this },
      payload,
    )
    return onUnhandledRejection?.call(this, payload)
  }
 
  const onThemeChange = appOptions.onThemeChange
  appOptions.onThemeChange = function (payload) {
    miniProgramBus.emit({ name: 'appThemeChange', context: this }, payload)
    return onThemeChange?.call(this, payload)
  }
}
 
function patchPageOptions(
  mp: MiniProgramApi,
  pageOptions: WechatMiniprogram.Page.Options<{}, {}>,
) {
  const onLoad = pageOptions.onLoad
  pageOptions.onLoad = function (pageQuery) {
    if (mp.$brand === '支付宝') {
      // 支持通过 options 获取页面参数
      ;(this as any).options = pageQuery
    }
    ;(this as any).__PAGE_ID__ = ++patchMiniProgram.__CURRENT_PAGE_ID__
    miniProgramBus.emit({ name: 'pageLoad', context: this }, pageQuery)
    return onLoad?.call(this, pageQuery)
  }
 
  const onShow = pageOptions.onShow
  pageOptions.onShow = function () {
    const currentPagesInfo = {
      count: getCurrentPages().length,
      lastPageUrl: getCurrentPageUrl(),
      lastPagePath: getCurrentPagePath(),
      lastPageQuery: getCurrentPageQuery(),
    }
    if (
      !(
        prevPagesInfo &&
        currentPagesInfo.count === prevPagesInfo.count &&
        currentPagesInfo.lastPageUrl === prevPagesInfo.lastPageUrl
      )
    ) {
      miniProgramBus.emit('routeChange', {
        from: prevPagesInfo && {
          url: prevPagesInfo.lastPageUrl,
          path: prevPagesInfo.lastPagePath,
          query: prevPagesInfo.lastPageQuery,
        },
        to: {
          url: currentPagesInfo.lastPageUrl,
          path: currentPagesInfo.lastPagePath,
          query: currentPagesInfo.lastPageQuery,
        },
        action:
          !prevPagesInfo || currentPagesInfo.count > prevPagesInfo.count
            ? 'push'
            : currentPagesInfo.count < prevPagesInfo.count
            ? 'pop'
            : 'replace',
      })
    }
 
    patchMiniProgram.__CURRENT_PAGE_ID__ = (this as any).__PAGE_ID__
    miniProgramBus.emit({
      name: 'currentPageShow',
      context: this,
      tag: (this as any).__PAGE_ID__,
    })
    miniProgramBus.emit({ name: 'pageShow', context: this })
    return onShow?.call(this)
  }
 
  const onReady = pageOptions.onReady
  pageOptions.onReady = function () {
    miniProgramBus.emit({
      name: 'currentPageReady',
      context: this,
      tag: (this as any).__PAGE_ID__,
    })
    miniProgramBus.emit({ name: 'pageReady', context: this })
    return onReady?.call(this)
  }
 
  const onHide = pageOptions.onHide
  pageOptions.onHide = function () {
    prevPagesInfo = {
      count: getCurrentPages().length,
      lastPageUrl: getCurrentPageUrl(),
      lastPagePath: getCurrentPagePath(),
      lastPageQuery: getCurrentPageQuery(),
    }
 
    miniProgramBus.emit({
      name: 'currentPageHide',
      context: this,
      tag: (this as any).__PAGE_ID__,
    })
    miniProgramBus.emit({ name: 'pageHide', context: this })
    return onHide?.call(this)
  }
 
  const onUnload = pageOptions.onUnload
  pageOptions.onUnload = function () {
    prevPagesInfo = {
      count: getCurrentPages().length,
      lastPageUrl: getCurrentPageUrl(),
      lastPagePath: getCurrentPagePath(),
      lastPageQuery: getCurrentPageQuery(),
    }
 
    miniProgramBus.emit({
      name: 'currentPageUnload',
      context: this,
      tag: (this as any).__PAGE_ID__,
    })
    miniProgramBus.emit({ name: 'pageUnload', context: this })
    const res = onUnload?.call(this)
    for (const currentPageListenerName of currentPageListeners) {
      miniProgramBus.off(currentPageListenerName, (this as any).__PAGE_ID__)
    }
    return res
  }
 
  const onPullDownRefresh = pageOptions.onPullDownRefresh
  pageOptions.onPullDownRefresh = function () {
    miniProgramBus.emit({
      name: 'currentPagePullDownRefresh',
      context: this,
      tag: (this as any).__PAGE_ID__,
    })
    miniProgramBus.emit({ name: 'pagePullDownRefresh', context: this })
    return onPullDownRefresh?.call(this)
  }
 
  const onReachBottom = pageOptions.onReachBottom
  pageOptions.onReachBottom = function () {
    miniProgramBus.emit({
      name: 'currentPageReachBottom',
      context: this,
      tag: (this as any).__PAGE_ID__,
    })
    miniProgramBus.emit({ name: 'pageReachBottom', context: this })
    return onReachBottom?.call(this)
  }
 
  const onShareAppMessage = pageOptions.onShareAppMessage
  pageOptions.onShareAppMessage = function (payload) {
    const pageListenerData = miniProgramBus.emit(
      {
        name: 'currentPageShareAppMessage',
        context: this,
        tag: (this as any).__PAGE_ID__,
      },
      payload,
    )
    const globalListenerData = miniProgramBus.emit(
      { name: 'pageShareAppMessage', context: this },
      payload,
    )
    const originalListenerData = onShareAppMessage?.call(this, payload)
    return (
      originalListenerData || last(pageListenerData) || last(globalListenerData)
    )
  }
 
  // @ts-ignore
  const onShareTimeline = pageOptions.onShareTimeline
  // @ts-ignore
  pageOptions.onShareTimeline = function (payload) {
    const pageListenerData = miniProgramBus.emit(
      {
        name: 'currentPageShareTimeline',
        context: this,
        tag: (this as any).__PAGE_ID__,
      },
      // @ts-ignore
      payload,
    )
    const globalListenerData = miniProgramBus.emit(
      { name: 'pageShareTimeline', context: this },
      // @ts-ignore
      payload,
    )
    const originalListenerData = onShareTimeline?.call(
      this,
      // @ts-ignore
      payload,
    )
    return (
      originalListenerData || last(pageListenerData) || last(globalListenerData)
    )
  }
 
  const onAddToFavorites = pageOptions.onAddToFavorites
  pageOptions.onAddToFavorites = function (payload) {
    const pageListenerData = miniProgramBus.emit(
      {
        name: 'currentPageAddToFavorites',
        context: this,
        tag: (this as any).__PAGE_ID__,
      },
      payload,
    )
    const globalListenerData = miniProgramBus.emit(
      { name: 'pageAddToFavorites', context: this },
      payload,
    )
    const originalListenerData = onAddToFavorites?.call(this, payload)
    return (
      originalListenerData ||
      last(pageListenerData) ||
      last(globalListenerData) ||
      {}
    )
  }
 
  const onResize = pageOptions.onResize
  pageOptions.onResize = function (payload) {
    miniProgramBus.emit(
      {
        name: 'currentPageResize',
        context: this,
        tag: (this as any).__PAGE_ID__,
      },
      payload,
    )
    miniProgramBus.emit({ name: 'pageResize', context: this }, payload)
    return onResize?.call(this, payload)
  }
 
  const onTabItemTap = pageOptions.onTabItemTap
  pageOptions.onTabItemTap = function (payload) {
    miniProgramBus.emit(
      {
        name: 'currentPageTabItemTap',
        context: this,
        tag: (this as any).__PAGE_ID__,
      },
      payload,
    )
    miniProgramBus.emit({ name: 'pageTabItemTap', context: this }, payload)
    return onTabItemTap?.call(this, payload)
  }
}
 
/**
 * 打补丁。
 */
export function patchMiniProgram() {
  ensureInMiniProgram(mp => {
    // 重写 App
    const originalApp = App
    App = function (appOptions) {
      patchAppOptions(mp, appOptions)
      return originalApp(appOptions)
    }
 
    // 重写 Page
    const originalPage = Page
    Page = function (pageOptions) {
      patchPageOptions(mp, pageOptions)
      return originalPage(pageOptions)
    }
 
    // 重写 Component
    const originalComponent = Component
    Component = function (componentOptions) {
      componentOptions.methods = componentOptions.methods || ({} as any)
      patchPageOptions(mp, componentOptions.methods as any)
      return originalComponent(componentOptions)
    }
  })
}
 
patchMiniProgram.__CURRENT_PAGE_ID__ = 0