2
0
mirror of https://github.com/tenrok/vue-meta.git synced 2026-06-25 14:50:34 +03:00

Merge pull request #16 from declandewet/options

support custom options
This commit is contained in:
Declan de Wet
2016-11-10 20:24:54 +02:00
committed by GitHub
16 changed files with 400 additions and 321 deletions
+14
View File
@@ -52,6 +52,7 @@
- [CDN](#cdn)
- [Usage](#usage)
- [Step 1: Preparing the plugin](#step-1-preparing-the-plugin)
- [Options](#options)
- [Step 2: Server Rendering (Optional)](#step-2-server-rendering-optional)
- [Step 2.1: Exposing `$meta` to `bundleRenderer`](#step-21-exposing-meta-to-bundlerenderer)
- [Step 2.2: Populating the document meta info with `inject()`](#step-22-populating-the-document-meta-info-with-inject)
@@ -140,6 +141,19 @@ export default new Router({
})
```
#### Options
`vue-meta` allows a few custom options:
```js
Vue.use(Meta, {
keyName: 'metaInfo', // the component option name that vue-meta looks for meta info on.
attribute: 'data-vue-meta', // the attribute name vue-meta adds to the tags it observes
ssrAttribute: 'data-vue-meta-server-rendered', // the attribute name that lets vue-meta know that meta info has already been server-rendered
tagIDKeyName: 'vmid' // the property name that vue-meta uses to determine whether to overwrite or append a tag
})
```
If you don't care about server-side rendering, you can skip straight to [step 3](#step-3-start-defining-metainfo). Otherwise, continue. :smile:
## Step 2: Server Rendering (Optional)
+6 -4
View File
@@ -1,7 +1,8 @@
import getMetaInfo from '../shared/getMetaInfo'
import updateClientMetaInfo from './updateClientMetaInfo'
/**
export default function _refresh (options = {}) {
/**
* When called, will update the current meta info with new meta info.
* Useful when updating meta info as the result of an asynchronous
* action that resolves after the initial render takes place.
@@ -11,8 +12,9 @@ import updateClientMetaInfo from './updateClientMetaInfo'
*
* @return {Object} - new meta info
*/
export default function refresh () {
const info = getMetaInfo(this.$root)
updateClientMetaInfo(info)
return function refresh () {
const info = getMetaInfo(options)(this.$root)
updateClientMetaInfo(options)(info)
return info
}
}
+11 -8
View File
@@ -1,17 +1,19 @@
import updateTitle from './updaters/updateTitle'
import updateTagAttributes from './updaters/updateTagAttributes'
import updateTags from './updaters/updateTags'
import { SERVER_RENDERED_ATTRIBUTE } from '../shared/constants'
/**
export default function _updateClientMetaInfo (options = {}) {
const { ssrAttribute } = options
/**
* Performs client-side updates when new meta info is received
*
* @param {Object} newInfo - the meta info to update to
*/
export default function updateClientMetaInfo (newInfo) {
return function updateClientMetaInfo (newInfo) {
const htmlTag = document.getElementsByTagName('html')[0]
// if this is not a server render, then update
if (htmlTag.getAttribute(SERVER_RENDERED_ATTRIBUTE) === null) {
if (htmlTag.getAttribute(ssrAttribute) === null) {
// initialize tracked changes
const addedTags = {}
const removedTags = {}
@@ -20,12 +22,12 @@ export default function updateClientMetaInfo (newInfo) {
switch (key) {
// update the title
case 'title':
updateTitle(newInfo.title)
updateTitle(options)(newInfo.title)
break
// update attributes
case 'htmlAttrs':
case 'bodyAttrs':
updateTagAttributes(newInfo[key], key === 'htmlAttrs' ? htmlTag : document.getElementsByTagName('body')[0])
updateTagAttributes(options)(newInfo[key], key === 'htmlAttrs' ? htmlTag : document.getElementsByTagName('body')[0])
break
// ignore these
case 'titleChunk':
@@ -34,7 +36,7 @@ export default function updateClientMetaInfo (newInfo) {
break
// catch-all update tags
default:
const { oldTags, newTags } = updateTags(key, newInfo[key], document.getElementsByTagName('head')[0])
const { oldTags, newTags } = updateTags(options)(key, newInfo[key], document.getElementsByTagName('head')[0])
if (newTags.length) {
addedTags[key] = newTags
removedTags[key] = oldTags
@@ -48,6 +50,7 @@ export default function updateClientMetaInfo (newInfo) {
}
} else {
// remove the server render attribute so we can update on changes
htmlTag.removeAttribute(SERVER_RENDERED_ATTRIBUTE)
htmlTag.removeAttribute(ssrAttribute)
}
}
}
+8 -6
View File
@@ -1,13 +1,14 @@
import { VUE_META_ATTRIBUTE } from '../../shared/constants'
export default function _updateTagAttributes (options = {}) {
const { attribute } = options
/**
/**
* updates the document's html tag attributes
*
* @param {Object} attrs - the new document html attributes
* @param {HTMLElement} tag - the HTMLElment tag to update with new attrs
*/
export default function updateTagAttributes (attrs, tag) {
const vueMetaAttrString = tag.getAttribute(VUE_META_ATTRIBUTE)
return function updateTagAttributes (attrs, tag) {
const vueMetaAttrString = tag.getAttribute(attribute)
const vueMetaAttrs = vueMetaAttrString ? vueMetaAttrString.split(',') : []
const toRemove = [].concat(vueMetaAttrs)
for (let attr in attrs) {
@@ -28,8 +29,9 @@ export default function updateTagAttributes (attrs, tag) {
tag.removeAttribute(toRemove[i])
}
if (vueMetaAttrs.length === toRemove.length) {
tag.removeAttribute(VUE_META_ATTRIBUTE)
tag.removeAttribute(attribute)
} else {
tag.setAttribute(VUE_META_ATTRIBUTE, vueMetaAttrs.join(','))
tag.setAttribute(attribute, vueMetaAttrs.join(','))
}
}
}
+12 -10
View File
@@ -1,9 +1,10 @@
import { VUE_META_ATTRIBUTE } from '../../shared/constants'
// borrow the slice method
const toArray = Function.prototype.call.bind(Array.prototype.slice)
/**
export default function _updateTags (options = {}) {
const { attribute } = options
/**
* Updates meta tags inside <head> on the client. Borrowed from `react-helmet`:
* https://github.com/nfl/react-helmet/blob/004d448f8de5f823d10f838b02317521180f34da/src/Helmet.js#L195-L245
*
@@ -11,8 +12,8 @@ const toArray = Function.prototype.call.bind(Array.prototype.slice)
* @param {(Array<Object>|Object)} tags - an array of tag objects or a single object in case of base
* @return {Object} - a representation of what tags changed
*/
export default function updateTags (type, tags, headTag) {
const nodes = headTag.querySelectorAll(`${type}[${VUE_META_ATTRIBUTE}]`)
return function updateTags (type, tags, headTag) {
const nodes = headTag.querySelectorAll(`${type}[${attribute}]`)
const oldTags = toArray(nodes)
const newTags = []
let indexToDelete
@@ -21,8 +22,8 @@ export default function updateTags (type, tags, headTag) {
tags.forEach((tag) => {
const newElement = document.createElement(type)
for (const attribute in tag) {
if (tag.hasOwnProperty(attribute)) {
for (const attr in tag) {
if (tag.hasOwnProperty(attr)) {
if (attribute === 'innerHTML') {
newElement.innerHTML = tag.innerHTML
} else if (attribute === 'cssText') {
@@ -32,13 +33,13 @@ export default function updateTags (type, tags, headTag) {
newElement.appendChild(document.createTextNode(tag.cssText))
}
} else {
const value = (typeof tag[attribute] === 'undefined') ? '' : tag[attribute]
newElement.setAttribute(attribute, value)
const value = (typeof tag[attr] === 'undefined') ? '' : tag[attr]
newElement.setAttribute(attr, value)
}
}
}
newElement.setAttribute(VUE_META_ATTRIBUTE, 'true')
newElement.setAttribute(attribute, 'true')
// Remove a duplicate tag from domTagstoRemove, so it isn't cleared.
if (oldTags.some((existingTag, index) => {
@@ -56,4 +57,5 @@ export default function updateTags (type, tags, headTag) {
newTags.forEach((tag) => headTag.appendChild(tag))
return { oldTags, newTags }
}
}
+4 -2
View File
@@ -1,8 +1,10 @@
/**
export default function _updateTitle () {
/**
* updates the document title
*
* @param {String} title - the new title of the document
*/
export default function updateTitle (title = document.title) {
return function updateTitle (title = document.title) {
document.title = title
}
}
+7 -5
View File
@@ -2,21 +2,23 @@ import titleGenerator from './generators/titleGenerator'
import attrsGenerator from './generators/attrsGenerator'
import tagGenerator from './generators/tagGenerator'
/**
export default function _generateServerInjector (options = {}) {
/**
* Converts a meta info property to one that can be stringified on the server
*
* @param {String} type - the type of data to convert
* @param {(String|Object|Array<Object>)} data - the data value
* @return {Object} - the new injector
*/
export default function generateServerInjector (type, data) {
return function generateServerInjector (type, data) {
switch (type) {
case 'title':
return titleGenerator(type, data)
return titleGenerator(options)(type, data)
case 'htmlAttrs':
case 'bodyAttrs':
return attrsGenerator(type, data)
return attrsGenerator(options)(type, data)
default:
return tagGenerator(type, data)
return tagGenerator(options)(type, data)
}
}
}
+6 -4
View File
@@ -1,13 +1,14 @@
import { VUE_META_ATTRIBUTE } from '../../shared/constants'
export default function _attrsGenerator (options = {}) {
const { attribute } = options
/**
/**
* Generates tag attributes for use on the server.
*
* @param {('bodyAttrs'|'htmlAttrs')} type - the type of attributes to generate
* @param {Object} data - the attributes to generate
* @return {Object} - the attribute generator
*/
export default function attrsGenerator (type, data) {
return function attrsGenerator (type, data) {
return {
text () {
let attributeStr = ''
@@ -22,8 +23,9 @@ export default function attrsGenerator (type, data) {
} `
}
}
attributeStr += `${VUE_META_ATTRIBUTE}="${watchedAttrs.join(',')}"`
attributeStr += `${attribute}="${watchedAttrs.join(',')}"`
return attributeStr.trim()
}
}
}
}
+7 -5
View File
@@ -1,13 +1,14 @@
import { VUE_META_ATTRIBUTE } from '../../shared/constants'
export default function _tagGenerator (options = {}) {
const { attribute } = options
/**
/**
* Generates meta, base, link, style, script, noscript tags for use on the server
*
* @param {('meta'|'base'|'link'|'style'|'script'|'noscript')} the name of the tag
* @param {(Array<Object>|Object)} tags - an array of tag objects or a single object in case of base
* @return {Object} - the tag generator
*/
export default function tagGenerator (type, tags) {
return function tagGenerator (type, tags) {
return {
text () {
// build a string containing all tags of this type
@@ -36,9 +37,10 @@ export default function tagGenerator (type, tags) {
// the final string for this specific tag
return closed
? `${tagsStr}<${type} ${VUE_META_ATTRIBUTE}="true" ${attrs}/>`
: `${tagsStr}<${type} ${VUE_META_ATTRIBUTE}="true" ${attrs}>${content}</${type}>`
? `${tagsStr}<${type} ${attribute}="true" ${attrs}/>`
: `${tagsStr}<${type} ${attribute}="true" ${attrs}>${content}</${type}>`
}, '')
}
}
}
}
+6 -4
View File
@@ -1,16 +1,18 @@
import { VUE_META_ATTRIBUTE } from '../../shared/constants'
export default function _titleGenerator (options = {}) {
const { attribute } = options
/**
/**
* Generates title output for the server
*
* @param {'title'} type - the string "title"
* @param {String} data - the title text
* @return {Object} - the title generator
*/
export default function titleGenerator (type, data) {
return function titleGenerator (type, data) {
return {
text () {
return `<${type} ${VUE_META_ATTRIBUTE}="true">${data}</${type}>`
return `<${type} ${attribute}="true">${data}</${type}>`
}
}
}
}
+6 -4
View File
@@ -1,23 +1,25 @@
import getMetaInfo from '../shared/getMetaInfo'
import generateServerInjector from './generateServerInjector'
/**
export default function _inject (options = {}) {
/**
* Converts the state of the meta info object such that each item
* can be compiled to a tag string on the server
*
* @this {Object} - Vue instance - ideally the root component
* @return {Object} - server meta info with `toString` methods
*/
export default function inject () {
return function inject () {
// get meta info with sensible defaults
const info = getMetaInfo(this.$root)
const info = getMetaInfo(options)(this.$root)
// generate server injectors
for (let key in info) {
if (info.hasOwnProperty(key) && key !== 'titleTemplate') {
info[key] = generateServerInjector(key, info[key])
info[key] = generateServerInjector(options)(key, info[key])
}
}
return info
}
}
+6 -5
View File
@@ -1,15 +1,16 @@
import inject from '../server/inject'
import refresh from '../client/refresh'
/**
export default function _$meta (options = {}) {
/**
* Returns an injector for server-side rendering.
* @this {Object} - the Vue instance (a root component)
* @return {Object} - injector
*/
export default function $meta () {
// bind inject method to this component
return function $meta () {
return {
inject: inject.bind(this),
refresh: refresh.bind(this)
inject: inject(options).bind(this),
refresh: refresh(options).bind(this)
}
}
}
+20 -1
View File
@@ -1,2 +1,21 @@
/**
* These are constant variables used throughout the application.
*/
// This is the name of the component option that contains all the information that
// gets converted to the various meta tags & attributes for the page.
export const VUE_META_KEY_NAME = 'metaInfo'
// This is the attribute vue-meta augments on elements to know which it should
// manage and which it should ignore.
export const VUE_META_ATTRIBUTE = 'data-vue-meta'
export const SERVER_RENDERED_ATTRIBUTE = 'data-vue-meta-server-rendered'
// This is the attribute that goes on the `html` tag to inform `vue-meta`
// that the server has already generated the meta tags for the initial render.
export const VUE_META_SERVER_RENDERED_ATTRIBUTE = 'data-vue-meta-server-rendered'
// This is the property that tells vue-meta to overwrite (instead of append)
// an item in a tag list. For example, if you have two `meta` tag list items
// that both have `vmid` of "description", then vue-meta will overwrite the
// shallowest one with the deepest one.
export const VUE_META_TAG_LIST_ID_KEY_NAME = 'vmid'
+7 -4
View File
@@ -1,14 +1,16 @@
import deepmerge from 'deepmerge'
import getComponentOption from './getComponentOption'
/**
export default function _getMetaInfo (options = {}) {
const { keyName, tagIDKeyName } = options
/**
* Returns the correct meta info for the given component
* (child components will overwrite parent meta info)
*
* @param {Object} component - the Vue instance to get meta info from
* @return {Object} - returned meta info
*/
export default function getMetaInfo (component) {
return function getMetaInfo (component) {
// set some sane defaults
const defaultInfo = {
title: '',
@@ -27,7 +29,7 @@ export default function getMetaInfo (component) {
// collect & aggregate all metaInfo $options
const info = getComponentOption({
component,
option: 'metaInfo',
option: keyName,
deep: true,
arrayMerge (target, source) {
// we concat the arrays without merging objects contained therein,
@@ -41,7 +43,7 @@ export default function getMetaInfo (component) {
let shared = false
for (let sourceIndex in source) {
const sourceItem = source[sourceIndex]
if (targetItem.vmid === sourceItem.vmid) {
if (targetItem[tagIDKeyName] === sourceItem[tagIDKeyName]) {
shared = true
break
}
@@ -72,4 +74,5 @@ export default function getMetaInfo (component) {
}
return deepmerge(defaultInfo, info)
}
}
+21 -2
View File
@@ -1,17 +1,36 @@
import assign from 'object-assign'
import $meta from './$meta'
import {
VUE_META_KEY_NAME,
VUE_META_ATTRIBUTE,
VUE_META_SERVER_RENDERED_ATTRIBUTE,
VUE_META_TAG_LIST_ID_KEY_NAME
} from './constants'
// automatic install
if (typeof Vue !== 'undefined') {
Vue.use(VueMeta)
}
// set some default options
const defaultOptions = {
keyName: VUE_META_KEY_NAME,
attribute: VUE_META_ATTRIBUTE,
ssrAttribute: VUE_META_SERVER_RENDERED_ATTRIBUTE,
tagIDKeyName: VUE_META_TAG_LIST_ID_KEY_NAME
}
/**
* Plugin install function.
* @param {Function} Vue - the Vue constructor.
*/
export default function VueMeta (Vue) {
export default function VueMeta (Vue, options = {}) {
// combine options
options = assign(defaultOptions, options)
// bind the $meta method to this component instance
Vue.prototype.$meta = $meta
Vue.prototype.$meta = $meta(options)
// store an id to keep track of DOM updates
let requestId = null
+3 -1
View File
@@ -1,5 +1,7 @@
import Vue from 'vue'
import getMetaInfo from '../src/shared/getMetaInfo'
import _getMetaInfo from '../src/shared/getMetaInfo'
const getMetaInfo = _getMetaInfo()
describe('getMetaInfo', () => {
// const container = document.createElement('div')