Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow automatic injection of head() into components #43

Merged
merged 13 commits into from
May 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions defu.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
declare module 'defu'
Copy link
Member Author

@danielroe danielroe May 8, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will need to go. defu has types but for some reason rollup wasn't recognising them until I edited its package.json.

unjs/defu#15

2 changes: 1 addition & 1 deletion docs/.vuepress/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ module.exports = {
'/helpers/useAsync',
'/helpers/useContext',
'/helpers/useFetch',
'/helpers/useHead',
'/helpers/useMeta',
],
},
{
Expand Down
23 changes: 0 additions & 23 deletions docs/helpers/useHead.md

This file was deleted.

26 changes: 26 additions & 0 deletions docs/helpers/useMeta.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
---

# useMeta

You can interact directly with [`head()` properties](https://nuxtjs.org/api/pages-head/) in `setup` by means of the `useMeta()` helper.

```ts
import { defineComponent, useMeta, computed } from 'nuxt-composition-api'

export default defineComponent({
// You need to define an empty head to activate this functionality
head: {},
setup() {
// This will allow you to set the title in head - but won't allow you to read its state outside of this component.
const { title } = useMeta()
title.value = 'My page'

// You could also provide an initial value.
const { title } = useMeta({ title: 'My page' })

// ... or simply set some meta tags
useMeta({ title: 'My page', ... })
},
})
```
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@
"pre-commit": "lint-staged"
},
"dependencies": {
"@vue/composition-api": "^0.5.0"
"@vue/composition-api": "^0.5.0",
"defu": "^2.0.2"
},
"devDependencies": {
"@babel/plugin-transform-runtime": "^7.9.6",
Expand Down
53 changes: 53 additions & 0 deletions src/component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import {
defineComponent as define,
reactive,
toRefs,
getCurrentInstance,
} from '@vue/composition-api'
import defu from 'defu'
import { MetaInfo } from 'vue-meta'

import { createEmptyMeta } from './meta'

import { UnwrapRef, Ref } from '@vue/composition-api/dist/reactivity'

type ReactiveHead<T = {}> = UnwrapRef<Ref<MetaInfo & T>>

export const defineComponent: typeof define = (options: any) => {
if (!('head' in options)) return options

const _head: ReactiveHead = reactive<MetaInfo>({})
if (!(options.head instanceof Function)) {
Object.assign(_head, options.head)
}
const head =
options.head instanceof Function
? () => defu(_head, options.head())
: () => _head

return {
...options,
_head,
head,
}
}

export const useMeta = <T extends MetaInfo>(init?: T) => {
const vm = getCurrentInstance()
if (!vm) throw new Error('useMeta must be called within a component.')

if (!('_head' in vm.$options))
throw new Error(
'In order to enable `useMeta`, please make sure you include `head: {}` within your component definition, and you are using the `defineComponent` exported from nuxt-composition-api.'
)

const { _head } = vm.$options as { _head: ReactiveHead }

Object.assign(_head, createEmptyMeta())
Object.assign(_head, init || {})
return toRefs(
_head as UnwrapRef<
Ref<Exclude<ReturnType<typeof createEmptyMeta>, keyof T> & T>
>
)
}
3 changes: 1 addition & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ export default compositionApiModule
export const meta = require('../package.json')

export { useAsync } from './async'
export { defineComponent, useMeta } from './component'
export { useContext, withContext } from './context'
export { useFetch } from './fetch'
export { useHead } from './meta'
export { onServerPrefetch } from './server-prefetch'
export { ssrRef, setSSRContext } from './ssr-ref'

Expand All @@ -43,7 +43,6 @@ export {
computed,
createComponent,
createElement,
defineComponent,
getCurrentInstance,
inject,
isRef,
Expand Down
22 changes: 8 additions & 14 deletions src/meta.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import { reactive, toRefs } from '@vue/composition-api'
import { MetaInfo } from 'vue-meta'

function createEmptyMeta(): MetaInfo {
type MetaInfoMapper<T> = {
[P in keyof T]: T[P] extends Array<any> ? T[P] : T[P] | undefined
}

export function createEmptyMeta(): MetaInfoMapper<Required<MetaInfo>> {
return {
__dangerouslyDisableSanitizers: [],
danielroe marked this conversation as resolved.
Show resolved Hide resolved
__dangerouslyDisableSanitizersByTagID: undefined,

title: undefined,
titleTemplate: undefined,
htmlAttrs: undefined,
Expand All @@ -21,15 +27,3 @@ function createEmptyMeta(): MetaInfo {
afterNavigation: undefined,
}
}

export function useHead(init: MetaInfo = {}) {
const meta = reactive<MetaInfo>({
...createEmptyMeta(),
...init,
})

return {
head: () => meta,
useMeta: () => toRefs(meta),
}
}
6 changes: 2 additions & 4 deletions test/fixture/pages/meta.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,10 @@
</template>

<script>
import { defineComponent, useHead, computed } from 'nuxt-composition-api'

const { head, useMeta } = useHead()
import { defineComponent, useMeta, computed } from 'nuxt-composition-api'

export default defineComponent({
head,
head: {},
setup() {
const { title } = useMeta()

Expand Down
6 changes: 6 additions & 0 deletions test/tsd/component.test-d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { expectType } from 'tsd'
import { defineComponent } from '@vue/composition-api'

import { defineComponent as modifiedDefineComponent } from '../..'

expectType<typeof defineComponent>(modifiedDefineComponent)
6 changes: 6 additions & 0 deletions test/tsd/meta.test-d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { expectType } from 'tsd'

import { useMeta, Ref } from '../..'

expectType<Ref<string>>(useMeta({ title: 'provided' }).title)
expectType<Ref<string | undefined>>(useMeta().title)
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -5627,6 +5627,11 @@ defu@^1.0.0:
resolved "https://registry.yarnpkg.com/defu/-/defu-1.0.0.tgz#43acb09dfcf81866fa3b0fc047ece18e5c30df71"
integrity sha512-1Y1KRFxiiq+LYsZ3iP7xYSR8bHfmHFOUpDunZCN1ld1fGfDJWJIvkUBtjl3apnBwPuJtL/H7cwwlLYX8xPkraQ==

defu@^2.0.2:
version "2.0.2"
resolved "https://registry.yarnpkg.com/defu/-/defu-2.0.2.tgz#9a3d4c1330d60c0ed4812e51864b948c51f7ad45"
integrity sha512-E5dO3ji0TmVcZaB/2G6Ovu5zNHbWkgCU7v+EoE/Jj1Lbwv1BB6hNNKLkio2ZLI3/e3avlO634QUhQl4iCpm3Bg==

del@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/del/-/del-3.0.0.tgz#53ecf699ffcbcb39637691ab13baf160819766e5"
Expand Down