Skip to content

Commit

Permalink
refactor: handle page data hmr in the same file (#779)
Browse files Browse the repository at this point in the history
  • Loading branch information
meteorlxy authored Jun 14, 2022
1 parent c5c3c64 commit 6174362
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 23 deletions.
22 changes: 0 additions & 22 deletions src/client/app/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import { usePrefetch } from './composables/preFetch'
import { dataSymbol, initData } from './data'
import { Content } from './components/Content'
import { ClientOnly } from './components/ClientOnly'
import { PageDataPayload } from '../shared'

const NotFound = Theme.NotFound || (() => '404 Not Found')

Expand Down Expand Up @@ -46,8 +45,6 @@ const VitePressApp = {
export function createApp() {
const router = newRouter()

handleHMR(router)

const app = newApp()

app.provide(RouterSymbol, router)
Expand Down Expand Up @@ -116,25 +113,6 @@ function newRouter(): Router {
}, NotFound)
}

function handleHMR(router: Router): void {
// update route.data on HMR updates of active page
if (import.meta.hot) {
// hot reload pageData
import.meta.hot!.on('vitepress:pageData', (payload: PageDataPayload) => {
if (shouldHotReload(payload)) {
router.route.data = payload.pageData
}
})
}
}

function shouldHotReload(payload: PageDataPayload): boolean {
const payloadPath = payload.path.replace(/(\bindex)?\.md$/, '')
const locationPath = location.pathname.replace(/(\bindex)?\.html$/, '')

return payloadPath === locationPath
}

if (inBrowser) {
const { app, router, data } = createApp()

Expand Down
23 changes: 22 additions & 1 deletion src/client/app/router.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { reactive, inject, markRaw, nextTick, readonly } from 'vue'
import type { Component, InjectionKey } from 'vue'
import { PageData, notFoundPageData } from '../shared'
import { notFoundPageData } from '../shared'
import type { PageData, PageDataPayload } from '../shared'
import { inBrowser, withBase } from './utils'
import { siteDataRef } from './data'

Expand Down Expand Up @@ -173,6 +174,8 @@ export function createRouter(
})
}

handleHMR(route)

return {
route,
go
Expand Down Expand Up @@ -230,3 +233,21 @@ function scrollTo(el: HTMLElement, hash: string, smooth = false) {
}
}
}

function handleHMR(route: Route): void {
// update route.data on HMR updates of active page
if (import.meta.hot) {
// hot reload pageData
import.meta.hot!.on('vitepress:pageData', (payload: PageDataPayload) => {
if (shouldHotReload(payload)) {
route.data = payload.pageData
}
})
}
}

function shouldHotReload(payload: PageDataPayload): boolean {
const payloadPath = payload.path.replace(/(\bindex)?\.md$/, '')
const locationPath = location.pathname.replace(/(\bindex)?\.html$/, '')
return payloadPath === locationPath
}

0 comments on commit 6174362

Please sign in to comment.