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

feat: add possibility to add additional meta info

refactor: server injectors

feat: add head, bodyPrepend, bodyAppend injectors

refactor: create browserbuild through rollup replace (not separate entry)
This commit is contained in:
pimlie
2019-09-13 00:08:21 +02:00
committed by Pim
parent 0e49a9c43e
commit 0ab76ee16b
27 changed files with 389 additions and 387 deletions
-37
View File
@@ -1,37 +0,0 @@
import { version } from '../package.json'
import createMixin from './shared/mixin'
import { setOptions } from './shared/options'
import { isUndefined } from './utils/is-type'
import $meta from './client/$meta'
import { hasMetaInfo } from './shared/meta-helpers'
/**
* Plugin install function.
* @param {Function} Vue - the Vue constructor.
*/
function install (Vue, options = {}) {
if (Vue.__vuemeta_installed) {
return
}
Vue.__vuemeta_installed = true
options = setOptions(options)
Vue.prototype.$meta = function () {
return $meta.call(this, options)
}
Vue.mixin(createMixin(Vue, options))
}
// automatic install
if (!isUndefined(window) && !isUndefined(window.Vue)) {
/* istanbul ignore next */
install(window.Vue)
}
export default {
version,
install,
hasMetaInfo
}
-29
View File
@@ -1,29 +0,0 @@
import { showWarningNotSupported } from '../shared/log'
import { getOptions } from '../shared/options'
import { pause, resume } from '../shared/pausing'
import refresh from './refresh'
export default function $meta (options = {}) {
/**
* Returns an injector for server-side rendering.
* @this {Object} - the Vue instance (a root component)
* @return {Object} - injector
*/
if (!this.$root._vueMeta) {
return {
getOptions: showWarningNotSupported,
refresh: showWarningNotSupported,
inject: showWarningNotSupported,
pause: showWarningNotSupported,
resume: showWarningNotSupported
}
}
return {
getOptions: () => getOptions(options),
refresh: () => refresh.call(this, options),
inject: () => {},
pause: () => pause.call(this),
resume: () => resume.call(this)
}
}
+32 -15
View File
@@ -1,26 +1,34 @@
import { clientSequences } from '../shared/escaping'
import { showWarningNotSupported } from '../shared/log'
import { getComponentMetaInfo } from '../shared/getComponentOption'
import { getAppsMetaInfo, clearAppsMetaInfo } from '../shared/additional-app'
import getMetaInfo from '../shared/getMetaInfo'
import { isFunction } from '../utils/is-type'
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.
*
* Credit to [Sébastien Chopin](https://github.com/Atinux) for the suggestion
* to implement this method.
*
* @return {Object} - new meta info
*/
/**
* 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.
*
* Credit to [Sébastien Chopin](https://github.com/Atinux) for the suggestion
* to implement this method.
*
* @return {Object} - new meta info
*/
export default function refresh (vm, options = {}) {
// make sure vue-meta was initiated
if (!vm.$root._vueMeta) {
showWarningNotSupported()
return {}
}
// collect & aggregate all metaInfo $options
const rawInfo = getComponentMetaInfo(options, this.$root)
const rawInfo = getComponentMetaInfo(options, vm.$root)
const metaInfo = getMetaInfo(options, rawInfo, clientSequences, this.$root)
const metaInfo = getMetaInfo(options, rawInfo, clientSequences, vm.$root)
const appId = this.$root._vueMeta.appId
const { appId } = vm.$root._vueMeta
const tags = updateClientMetaInfo(appId, options, metaInfo)
// emit "event" with new info
@@ -28,5 +36,14 @@ export default function refresh (options = {}) {
metaInfo.changed(metaInfo, tags.addedTags, tags.removedTags)
}
return { vm: this, metaInfo, tags }
const appsMetaInfo = getAppsMetaInfo()
if (appsMetaInfo) {
for (const additionalAppId in appsMetaInfo) {
updateClientMetaInfo(additionalAppId, options, appsMetaInfo[additionalAppId])
delete appsMetaInfo[additionalAppId]
}
clearAppsMetaInfo(true)
}
return { vm, metaInfo, tags }
}
+3 -3
View File
@@ -1,7 +1,7 @@
import { version } from '../package.json'
import createMixin from './shared/mixin'
import { setOptions } from './shared/options'
import $meta from './server/$meta'
import $meta from './shared/$meta'
import generate from './server/generate'
import { hasMetaInfo } from './shared/meta-helpers'
@@ -27,6 +27,6 @@ function install (Vue, options = {}) {
export default {
version,
install,
hasMetaInfo,
generate
generate: process.server ? generate : () => {},
hasMetaInfo
}
-19
View File
@@ -1,19 +0,0 @@
import { getOptions } from '../shared/options'
import { pause, resume } from '../shared/pausing'
import refresh from '../client/refresh'
import inject from './inject'
export default function $meta (options = {}) {
/**
* Returns an injector for server-side rendering.
* @this {Object} - the Vue instance (a root component)
* @return {Object} - injector
*/
return {
getOptions: () => getOptions(options),
refresh: () => refresh.call(this, options),
inject: () => inject.call(this, options),
pause: () => pause.call(this),
resume: () => resume.call(this)
}
}
+3 -1
View File
@@ -5,5 +5,7 @@ import generateServerInjector from './generateServerInjector'
export default function generate (rawInfo, options = {}) {
const metaInfo = getMetaInfo(setOptions(options), rawInfo, serverSequences)
return generateServerInjector(options, metaInfo)
const serverInjector = generateServerInjector(options, metaInfo)
return serverInjector.injectors
}
+58 -11
View File
@@ -9,24 +9,71 @@ import { titleGenerator, attributeGenerator, tagGenerator } from './generators'
* @return {Object} - the new injector
*/
export default function generateServerInjector (options, newInfo) {
export default function generateServerInjector (options, metaInfo) {
const serverInjector = {
data: metaInfo,
extraData: undefined,
addInfo (appId, metaInfo) {
this.extraData = this.extraData || {}
this.extraData[appId] = metaInfo
},
callInjectors (opts) {
const m = this.injectors
// only call title for the head
return (opts.body || opts.pbody ? '' : m.title.text(opts)) +
m.meta.text(opts) +
m.link.text(opts) +
m.style.text(opts) +
m.script.text(opts) +
m.noscript.text(opts)
},
injectors: {
head: ln => serverInjector.callInjectors({ ln }),
bodyPrepend: ln => serverInjector.callInjectors({ ln, pbody: true }),
bodyAppend: ln => serverInjector.callInjectors({ ln, body: true })
}
}
for (const type in defaultInfo) {
if (metaInfoOptionKeys.includes(type)) {
continue
}
if (type === 'title') {
newInfo[type] = titleGenerator(options, type, newInfo[type])
continue
}
serverInjector.injectors[type] = {
text (arg) {
if (type === 'title') {
return titleGenerator(options, type, serverInjector.data[type], arg)
}
if (metaInfoAttributeKeys.includes(type)) {
newInfo[type] = attributeGenerator(options, type, newInfo[type])
continue
}
if (metaInfoAttributeKeys.includes(type)) {
let str = attributeGenerator(options, type, serverInjector.data[type], arg)
newInfo[type] = tagGenerator(options, type, newInfo[type])
if (serverInjector.extraData) {
for (const appId in serverInjector.extraData) {
const data = serverInjector.extraData[appId][type]
const extraStr = attributeGenerator(options, type, data, arg)
str = `${str}${extraStr}`
}
}
return str
}
let str = tagGenerator(options, type, serverInjector.data[type], arg)
if (serverInjector.extraData) {
for (const appId in serverInjector.extraData) {
const data = serverInjector.extraData[appId][type]
const extraStr = tagGenerator(options, type, data, { appId, ...arg })
str = `${str}${extraStr}`
}
}
return str
}
}
}
return newInfo
return serverInjector
}
+20 -24
View File
@@ -8,33 +8,29 @@ import { isUndefined, isArray } from '../../utils/is-type'
* @param {Object} data - the attributes to generate
* @return {Object} - the attribute generator
*/
export default function attributeGenerator ({ attribute, ssrAttribute } = {}, type, data) {
return {
text (addSrrAttribute) {
let attributeStr = ''
const watchedAttrs = []
export default function attributeGenerator ({ attribute, ssrAttribute } = {}, type, data, addSrrAttribute) {
let attributeStr = ''
const watchedAttrs = []
for (const attr in data) {
if (data.hasOwnProperty(attr)) {
watchedAttrs.push(attr)
for (const attr in data) {
if (data.hasOwnProperty(attr)) {
watchedAttrs.push(attr)
attributeStr += isUndefined(data[attr]) || booleanHtmlAttributes.includes(attr)
? attr
: `${attr}="${isArray(data[attr]) ? data[attr].join(' ') : data[attr]}"`
attributeStr += isUndefined(data[attr]) || booleanHtmlAttributes.includes(attr)
? attr
: `${attr}="${isArray(data[attr]) ? data[attr].join(' ') : data[attr]}"`
attributeStr += ' '
}
}
if (attributeStr) {
attributeStr += `${attribute}="${(watchedAttrs.sort()).join(',')}"`
}
if (type === 'htmlAttrs' && addSrrAttribute) {
return `${ssrAttribute}${attributeStr ? ' ' : ''}${attributeStr}`
}
return attributeStr
attributeStr += ' '
}
}
if (attributeStr) {
attributeStr += `${attribute}="${(watchedAttrs.sort()).join(',')}"`
}
if (type === 'htmlAttrs' && addSrrAttribute) {
return `${ssrAttribute}${attributeStr ? ' ' : ''}${attributeStr}`
}
return attributeStr
}
+64 -67
View File
@@ -14,79 +14,76 @@ import {
* @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 ({ ssrAppId, attribute, tagIDKeyName } = {}, type, tags) {
export default function tagGenerator ({ ssrAppId, attribute, tagIDKeyName } = {}, type, tags, { appId, body = false, pbody = false, ln = false } = {}) {
const dataAttributes = [tagIDKeyName, ...commonDataAttributes]
return {
text ({ body = false, pbody = false } = {}) {
if (!tags || !tags.length) {
return ''
if (!tags || !tags.length) {
return ''
}
// build a string containing all tags of this type
return tags.reduce((tagsStr, tag) => {
if (tag.skip) {
return tagsStr
}
const tagKeys = Object.keys(tag)
if (tagKeys.length === 0) {
return tagsStr // Bail on empty tag object
}
if (Boolean(tag.body) !== body || Boolean(tag.pbody) !== pbody) {
return tagsStr
}
let attrs = tag.once ? '' : ` ${attribute}="${appId || ssrAppId}"`
// build a string containing all attributes of this tag
for (const attr in tag) {
// these attributes are treated as children on the tag
if (tagAttributeAsInnerContent.includes(attr) || tagProperties.includes(attr)) {
continue
}
// build a string containing all tags of this type
return tags.reduce((tagsStr, tag) => {
if (tag.skip) {
return tagsStr
}
if (attr === 'callback') {
attrs += ` onload="this.__vm_l=1"`
continue
}
const tagKeys = Object.keys(tag)
// these form the attribute list for this tag
let prefix = ''
if (dataAttributes.includes(attr)) {
prefix = 'data-'
}
if (tagKeys.length === 0) {
return tagsStr // Bail on empty tag object
}
const isBooleanAttr = !prefix && booleanHtmlAttributes.includes(attr)
if (isBooleanAttr && !tag[attr]) {
continue
}
if (Boolean(tag.body) !== body || Boolean(tag.pbody) !== pbody) {
return tagsStr
}
let attrs = tag.once ? '' : ` ${attribute}="${ssrAppId}"`
// build a string containing all attributes of this tag
for (const attr in tag) {
// these attributes are treated as children on the tag
if (tagAttributeAsInnerContent.includes(attr) || tagProperties.includes(attr)) {
continue
}
if (attr === 'callback') {
attrs += ` onload="this.__vm_l=1"`
continue
}
// these form the attribute list for this tag
let prefix = ''
if (dataAttributes.includes(attr)) {
prefix = 'data-'
}
const isBooleanAttr = !prefix && booleanHtmlAttributes.includes(attr)
if (isBooleanAttr && !tag[attr]) {
continue
}
attrs += ` ${prefix}${attr}` + (isBooleanAttr ? '' : `="${tag[attr]}"`)
}
let json = ''
if (tag.json) {
json = JSON.stringify(tag.json)
}
// grab child content from one of these attributes, if possible
const content = tag.innerHTML || tag.cssText || json
// generate tag exactly without any other redundant attribute
// these tags have no end tag
const hasEndTag = !tagsWithoutEndTag.includes(type)
// these tag types will have content inserted
const hasContent = hasEndTag && tagsWithInnerContent.includes(type)
// the final string for this specific tag
return `${tagsStr}<${type}${attrs}${!hasContent && hasEndTag ? '/' : ''}>` +
(hasContent ? `${content}</${type}>` : '')
}, '')
attrs += ` ${prefix}${attr}` + (isBooleanAttr ? '' : `="${tag[attr]}"`)
}
}
let json = ''
if (tag.json) {
json = JSON.stringify(tag.json)
}
// grab child content from one of these attributes, if possible
const content = tag.innerHTML || tag.cssText || json
// generate tag exactly without any other redundant attribute
// these tags have no end tag
const hasEndTag = !tagsWithoutEndTag.includes(type)
// these tag types will have content inserted
const hasContent = hasEndTag && tagsWithInnerContent.includes(type)
// the final string for this specific tag
return `${tagsStr}<${type}${attrs}${!hasContent && hasEndTag ? '/' : ''}>` +
(hasContent ? `${content}</${type}>` : '') +
(ln ? '\n' : '')
}, '')
}
+5 -8
View File
@@ -5,13 +5,10 @@
* @param {String} data - the title text
* @return {Object} - the title generator
*/
export default function titleGenerator ({ attribute } = {}, type, data) {
return {
text () {
if (!data) {
return ''
}
return `<${type}>${data}</${type}>`
}
export default function titleGenerator ({ attribute } = {}, type, data, { ln } = {}) {
if (!data) {
return ''
}
return `<${type}>${data}</${type}>${ln ? '\n' : ''}`
}
+30 -13
View File
@@ -1,24 +1,41 @@
import { serverSequences } from '../shared/escaping'
import { showWarningNotSupported } from '../shared/log'
import { getComponentMetaInfo } from '../shared/getComponentOption'
import { getAppsMetaInfo, clearAppsMetaInfo } from '../shared/additional-app'
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
*/
/**
* Converts the state of the meta info object such that each item
* can be compiled to a tag string on the server
*
* @vm {Object} - Vue instance - ideally the root component
* @return {Object} - server meta info with `toString` methods
*/
export default function inject (vm, options = {}) {
// make sure vue-meta was initiated
if (!vm.$root._vueMeta) {
showWarningNotSupported()
return {}
}
// collect & aggregate all metaInfo $options
const rawInfo = getComponentMetaInfo(options, this.$root)
const rawInfo = getComponentMetaInfo(options, vm.$root)
const metaInfo = getMetaInfo(options, rawInfo, serverSequences, this.$root)
const metaInfo = getMetaInfo(options, rawInfo, serverSequences, vm.$root)
// generate server injectors
generateServerInjector(options, metaInfo)
// generate server injector
const serverInjector = generateServerInjector(options, metaInfo)
return metaInfo
// add meta info from additional apps
const appsMetaInfo = getAppsMetaInfo()
if (appsMetaInfo) {
for (const additionalAppId in appsMetaInfo) {
serverInjector.addInfo(additionalAppId, appsMetaInfo[additionalAppId])
delete appsMetaInfo[additionalAppId]
}
clearAppsMetaInfo(true)
}
return serverInjector.injectors
}
+22
View File
@@ -0,0 +1,22 @@
import refresh from '../client/refresh'
import inject from '../server/inject'
import { showWarningNotSupported } from '../shared/log'
import { addApp } from './additional-app'
import { pause, resume } from './pausing'
import { getOptions } from './options'
export default function $meta (options = {}) {
/**
* Returns an injector for server-side rendering.
* @this {Object} - the Vue instance (a root component)
* @return {Object} - injector
*/
return {
getOptions: () => getOptions(options),
refresh: () => refresh(this, options),
inject: () => process.server ? inject(this, options) : showWarningNotSupported(),
pause: () => pause(this),
resume: () => resume(this),
addApp: appId => addApp(this, appId, options)
}
}
+44
View File
@@ -0,0 +1,44 @@
import updateClientMetaInfo from '../client/updateClientMetaInfo'
import { removeElementsByAppId } from '../utils/elements'
let appsMetaInfo
export function addApp (vm, appId, options) {
return {
set: metaInfo => setMetaInfo(vm.$root, appId, options, metaInfo),
remove: () => removeMetaInfo(vm.$root, appId, options)
}
}
export function setMetaInfo (vm, appId, options, metaInfo) {
// if a vm exists _and_ its mounted then immediately update
if (vm && vm.$el) {
return updateClientMetaInfo(appId, options, metaInfo)
}
// store for later, the info
// will be set on the first refresh
appsMetaInfo = appsMetaInfo || {}
appsMetaInfo[appId] = metaInfo
}
export function removeMetaInfo (vm, appId, options) {
if (vm && vm.$el) {
return removeElementsByAppId(options, appId)
}
if (appsMetaInfo[appId]) {
delete appsMetaInfo[appId]
clearAppsMetaInfo()
}
}
export function getAppsMetaInfo () {
return appsMetaInfo
}
export function clearAppsMetaInfo (force) {
if (force || !Object.keys(appsMetaInfo).length) {
appsMetaInfo = undefined
}
}
+5 -5
View File
@@ -1,13 +1,13 @@
export function pause (refresh = true) {
this.$root._vueMeta.paused = true
export function pause (vm, refresh = true) {
vm.$root._vueMeta.paused = true
return () => resume(refresh)
}
export function resume (refresh = true) {
this.$root._vueMeta.paused = false
export function resume (vm, refresh = true) {
vm.$root._vueMeta.paused = false
if (refresh) {
return this.$root.$meta().refresh()
return vm.$root.$meta().refresh()
}
}
+4
View File
@@ -29,3 +29,7 @@ export function queryElements (parentNode, { appId, attribute, type, tagIDKeyNam
return toArray(parentNode.querySelectorAll(queries.join(', ')))
}
export function removeElementsByAppId ({ attribute }, appId) {
toArray(document.querySelectorAll(`[${attribute}="${appId}"]`)).map(el => el.remove())
}