Skip to content

Commit

Permalink
feat(client): add support for clientData
Browse files Browse the repository at this point in the history
  • Loading branch information
Mister-Hope committed Apr 21, 2023
1 parent 1fe9635 commit 958d970
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 0 deletions.
6 changes: 6 additions & 0 deletions packages/client/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { clientConfigs } from '@internal/clientConfigs'
import { createApp, createSSRApp, h } from 'vue'
import { RouterView } from 'vue-router'
import { siteData } from './composables/index.js'
import { clientDataMap } from './helpers/index.js'
import { createVueRouter } from './router.js'
import { setupGlobalComponents } from './setupGlobalComponents.js'
import { setupGlobalComputed } from './setupGlobalComputed.js'
Expand Down Expand Up @@ -50,6 +51,11 @@ export const createVueApp: CreateVueAppFunction = async () => {
setupDevtools(app, globalComputed)
}

// provide client data
for (const [key, value] of clientDataMap) {
app.provide(key, value)
}

// invoke all client enhance
for (const clientConfig of clientConfigs) {
await clientConfig.enhance?.({ app, router, siteData })
Expand Down
15 changes: 15 additions & 0 deletions packages/client/src/composables/clientData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { inject } from 'vue'
import type { InjectionKey } from 'vue'

export const useClientData = <T = unknown, U extends boolean = false>(
key: InjectionKey<T>,
required?: U
): U extends true ? T : T | undefined => {
const result = inject(key)

if (required && !result) {
throw new Error(`Can not found ${key} in clientData()`)
}

return <U extends true ? T : T | undefined>result
}
1 change: 1 addition & 0 deletions packages/client/src/composables/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './clientData.js'
export * from './layouts.js'
export * from './pageData.js'
export * from './pageFrontmatter.js'
Expand Down
13 changes: 13 additions & 0 deletions packages/client/src/helpers/defineClientData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import type { InjectionKey } from 'vue'

export const clientDataMap = new Map<InjectionKey<unknown>, unknown>()

/**
* A helper function to help you define vuepress client data
*/
export const defineClientData = <T = unknown>(
key: InjectionKey<T>,
data: T
): void => {
clientDataMap.set(key, data)
}
1 change: 1 addition & 0 deletions packages/client/src/helpers/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './defineClientConfig.js'
export * from './defineClientData.js'
export * from './withBase.js'

0 comments on commit 958d970

Please sign in to comment.