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

feat: support generating tags directly from metaInfo object

This commit is contained in:
pimlie
2019-07-28 16:13:58 +02:00
committed by Pim
parent 931c0c4e88
commit cb2758eb0f
17 changed files with 128 additions and 70 deletions
+2
View File
@@ -21,6 +21,8 @@ const banner = `/**
const babelConfig = () => ({ const babelConfig = () => ({
presets: [ presets: [
['@babel/preset-env', { ['@babel/preset-env', {
/*useBuiltIns: 'usage',
corejs: 2,*/
targets: { targets: {
node: 8, node: 8,
ie: 9, ie: 9,
+7 -2
View File
@@ -1,6 +1,7 @@
import { clientSequences } from '../shared/escaping'
import { getComponentMetaInfo } from '../shared/getComponentOption'
import getMetaInfo from '../shared/getMetaInfo' import getMetaInfo from '../shared/getMetaInfo'
import { isFunction } from '../utils/is-type' import { isFunction } from '../utils/is-type'
import { clientSequences } from '../shared/escaping'
import updateClientMetaInfo from './updateClientMetaInfo' import updateClientMetaInfo from './updateClientMetaInfo'
export default function _refresh (options = {}) { export default function _refresh (options = {}) {
@@ -15,10 +16,14 @@ export default function _refresh (options = {}) {
* @return {Object} - new meta info * @return {Object} - new meta info
*/ */
return function refresh () { return function refresh () {
const metaInfo = getMetaInfo(options, this.$root, clientSequences) // collect & aggregate all metaInfo $options
const rawInfo = getComponentMetaInfo(options, this.$root)
const metaInfo = getMetaInfo(options, rawInfo, clientSequences, this.$root)
const appId = this.$root._vueMeta.appId const appId = this.$root._vueMeta.appId
const tags = updateClientMetaInfo(appId, options, metaInfo) const tags = updateClientMetaInfo(appId, options, metaInfo)
// emit "event" with new info // emit "event" with new info
if (tags && isFunction(metaInfo.changed)) { if (tags && isFunction(metaInfo.changed)) {
metaInfo.changed(metaInfo, tags.addedTags, tags.removedTags) metaInfo.changed(metaInfo, tags.addedTags, tags.removedTags)
+3 -1
View File
@@ -2,6 +2,7 @@ import { version } from '../package.json'
import createMixin from './shared/mixin' import createMixin from './shared/mixin'
import { setOptions } from './shared/options' import { setOptions } from './shared/options'
import $meta from './server/$meta' import $meta from './server/$meta'
import generate from './server/generate'
import { hasMetaInfo } from './shared/meta-helpers' import { hasMetaInfo } from './shared/meta-helpers'
/** /**
@@ -24,5 +25,6 @@ function install (Vue, options = {}) {
export default { export default {
version, version,
install, install,
hasMetaInfo hasMetaInfo,
generate
} }
+15
View File
@@ -0,0 +1,15 @@
import getMetaInfo from '../shared/getMetaInfo'
import { defaultOptions } from '../shared/constants'
import { serverSequences } from '../shared/escaping'
import { setOptions } from '../shared/options'
import generateServerInjector from './generateServerInjector'
export default function generate (options, rawInfo) {
if (arguments.length === 1) {
rawInfo = options
options = defaultOptions
}
const metaInfo = getMetaInfo(setOptions(options), rawInfo, serverSequences)
return generateServerInjector(options, metaInfo)
}
+19 -9
View File
@@ -1,4 +1,4 @@
import { metaInfoAttributeKeys } from '../shared/constants' import { metaInfoOptionKeys, metaInfoAttributeKeys, defaultInfo } from '../shared/constants'
import { titleGenerator, attributeGenerator, tagGenerator } from './generators' import { titleGenerator, attributeGenerator, tagGenerator } from './generators'
/** /**
@@ -9,14 +9,24 @@ import { titleGenerator, attributeGenerator, tagGenerator } from './generators'
* @return {Object} - the new injector * @return {Object} - the new injector
*/ */
export default function generateServerInjector (options, type, data) { export default function generateServerInjector (options, newInfo) {
if (type === 'title') { for (const type in defaultInfo) {
return titleGenerator(options, type, data) if (metaInfoOptionKeys.includes(type)) {
continue
}
if (type === 'title') {
newInfo[type] = titleGenerator(options, type, newInfo[type])
continue
}
if (metaInfoAttributeKeys.includes(type)) {
newInfo[type] = attributeGenerator(options, type, newInfo[type])
continue
}
newInfo[type] = tagGenerator(options, type, newInfo[type])
} }
if (metaInfoAttributeKeys.includes(type)) { return newInfo
return attributeGenerator(options, type, data)
}
return tagGenerator(options, type, data)
} }
+4
View File
@@ -18,6 +18,10 @@ export default function tagGenerator ({ ssrAppId, attribute, tagIDKeyName } = {}
return { return {
text ({ body = false, pbody = false } = {}) { text ({ body = false, pbody = false } = {}) {
if (!tags || !tags.length) {
return ''
}
// build a string containing all tags of this type // build a string containing all tags of this type
return tags.reduce((tagsStr, tag) => { return tags.reduce((tagsStr, tag) => {
if (tag.skip) { if (tag.skip) {
+7 -9
View File
@@ -1,6 +1,6 @@
import getMetaInfo from '../shared/getMetaInfo'
import { metaInfoOptionKeys } from '../shared/constants'
import { serverSequences } from '../shared/escaping' import { serverSequences } from '../shared/escaping'
import { getComponentMetaInfo } from '../shared/getComponentOption'
import getMetaInfo from '../shared/getMetaInfo'
import generateServerInjector from './generateServerInjector' import generateServerInjector from './generateServerInjector'
export default function _inject (options = {}) { export default function _inject (options = {}) {
@@ -12,15 +12,13 @@ export default function _inject (options = {}) {
* @return {Object} - server meta info with `toString` methods * @return {Object} - server meta info with `toString` methods
*/ */
return function inject () { return function inject () {
// get meta info with sensible defaults // collect & aggregate all metaInfo $options
const metaInfo = getMetaInfo(options, this.$root, serverSequences) const rawInfo = getComponentMetaInfo(options, this.$root)
const metaInfo = getMetaInfo(options, rawInfo, serverSequences, this.$root)
// generate server injectors // generate server injectors
for (const key in metaInfo) { generateServerInjector(options, metaInfo)
if (!metaInfoOptionKeys.includes(key) && metaInfo.hasOwnProperty(key)) {
metaInfo[key] = generateServerInjector(options, key, metaInfo[key])
}
}
return metaInfo return metaInfo
} }
+22
View File
@@ -1,5 +1,6 @@
import { isString, isArray, isPureObject } from '../utils/is-type' import { isString, isArray, isPureObject } from '../utils/is-type'
import { includes } from '../utils/array' import { includes } from '../utils/array'
import { ensureIsArray } from '../utils/ensure'
import { metaInfoOptionKeys, disableOptionKeys } from './constants' import { metaInfoOptionKeys, disableOptionKeys } from './constants'
export const serverSequences = [ export const serverSequences = [
@@ -78,3 +79,24 @@ export function escape (info, options, escapeOptions, escapeKeys) {
return escaped return escaped
} }
export function escapeMetaInfo (options, info, escapeSequences = []) {
const escapeOptions = {
doEscape: value => escapeSequences.reduce((val, [v, r]) => val.replace(v, r), value)
}
disableOptionKeys.forEach((disableKey, index) => {
if (index === 0) {
ensureIsArray(info, disableKey)
} else if (index === 1) {
for (const key in info[disableKey]) {
ensureIsArray(info[disableKey], key)
}
}
escapeOptions[disableKey] = info[disableKey]
})
// begin sanitization
return escape(info, options, escapeOptions)
}
+6 -1
View File
@@ -1,9 +1,14 @@
import { isFunction, isObject } from '../utils/is-type' import { isFunction, isObject } from '../utils/is-type'
import { findIndex } from '../utils/array' import { findIndex } from '../utils/array'
import { defaultInfo } from './constants'
import { merge } from './merge' import { merge } from './merge'
import { applyTemplate } from './template' import { applyTemplate } from './template'
import { inMetaInfoBranch } from './meta-helpers' import { inMetaInfoBranch } from './meta-helpers'
export function getComponentMetaInfo (options = {}, component) {
return getComponentOption(options, component, defaultInfo)
}
/** /**
* Returns the `opts.option` $option value of the given `opts.component`. * Returns the `opts.option` $option value of the given `opts.component`.
* If methods are encountered, they will be bound to the component context. * If methods are encountered, they will be bound to the component context.
@@ -18,7 +23,7 @@ import { inMetaInfoBranch } from './meta-helpers'
* @param {Object} [result={}] - result so far * @param {Object} [result={}] - result so far
* @return {Object} result - final aggregated result * @return {Object} result - final aggregated result
*/ */
export default function getComponentOption (options = {}, component, result = {}) { export function getComponentOption (options = {}, component, result = {}) {
const { keyName, metaTemplateKeyName, tagIDKeyName } = options const { keyName, metaTemplateKeyName, tagIDKeyName } = options
const { $options, $children } = component const { $options, $children } = component
+3 -28
View File
@@ -1,8 +1,5 @@
import { ensureIsArray } from '../utils/ensure' import { escapeMetaInfo } from '../shared/escaping'
import { applyTemplate } from './template' import { applyTemplate } from './template'
import { defaultInfo, disableOptionKeys } from './constants'
import { escape } from './escaping'
import getComponentOption from './getComponentOption'
/** /**
* Returns the correct meta info for the given component * Returns the correct meta info for the given component
@@ -11,10 +8,7 @@ import getComponentOption from './getComponentOption'
* @param {Object} component - the Vue instance to get meta info from * @param {Object} component - the Vue instance to get meta info from
* @return {Object} - returned meta info * @return {Object} - returned meta info
*/ */
export default function getMetaInfo (options = {}, component, escapeSequences = []) { export default function getMetaInfo (options = {}, info, escapeSequences = [], component) {
// collect & aggregate all metaInfo $options
let info = getComponentOption(options, component, defaultInfo)
// Remove all "template" tags from meta // Remove all "template" tags from meta
// backup the title chunk in case user wants access to it // backup the title chunk in case user wants access to it
@@ -33,24 +27,5 @@ export default function getMetaInfo (options = {}, component, escapeSequences =
info.base = Object.keys(info.base).length ? [info.base] : [] info.base = Object.keys(info.base).length ? [info.base] : []
} }
const escapeOptions = { return escapeMetaInfo(options, info, escapeSequences)
doEscape: value => escapeSequences.reduce((val, [v, r]) => val.replace(v, r), value)
}
disableOptionKeys.forEach((disableKey, index) => {
if (index === 0) {
ensureIsArray(info, disableKey)
} else if (index === 1) {
for (const key in info[disableKey]) {
ensureIsArray(info[disableKey], key)
}
}
escapeOptions[disableKey] = info[disableKey]
})
// begin sanitization
info = escape(info, options, escapeOptions)
return info
} }
+2 -1
View File
@@ -1,3 +1,4 @@
import { getComponentMetaInfo } from '../../src/shared/getComponentOption'
import _getMetaInfo from '../../src/shared/getMetaInfo' import _getMetaInfo from '../../src/shared/getMetaInfo'
import { mount, createWrapper, loadVueMetaPlugin, vmTick } from '../utils' import { mount, createWrapper, loadVueMetaPlugin, vmTick } from '../utils'
import { defaultOptions } from '../../src/shared/constants' import { defaultOptions } from '../../src/shared/constants'
@@ -7,7 +8,7 @@ import HelloWorld from '../components/hello-world.vue'
import KeepAlive from '../components/keep-alive.vue' import KeepAlive from '../components/keep-alive.vue'
import Changed from '../components/changed.vue' import Changed from '../components/changed.vue'
const getMetaInfo = component => _getMetaInfo(defaultOptions, component) const getMetaInfo = component => _getMetaInfo(defaultOptions, getComponentMetaInfo(defaultOptions, component))
jest.mock('../../src/utils/window', () => ({ jest.mock('../../src/utils/window', () => ({
hasGlobalWindow: false hasGlobalWindow: false
+2 -1
View File
@@ -1,9 +1,10 @@
import { getComponentMetaInfo } from '../../src/shared/getComponentOption'
import _getMetaInfo from '../../src/shared/getMetaInfo' import _getMetaInfo from '../../src/shared/getMetaInfo'
import { loadVueMetaPlugin } from '../utils' import { loadVueMetaPlugin } from '../utils'
import { defaultOptions } from '../../src/shared/constants' import { defaultOptions } from '../../src/shared/constants'
import { serverSequences } from '../../src/shared/escaping' import { serverSequences } from '../../src/shared/escaping'
const getMetaInfo = (component, escapeSequences) => _getMetaInfo(defaultOptions, component, escapeSequences) const getMetaInfo = (component, escapeSequences) => _getMetaInfo(defaultOptions, getComponentMetaInfo(defaultOptions, component), escapeSequences)
describe('escaping', () => { describe('escaping', () => {
let Vue let Vue
+21 -9
View File
@@ -3,7 +3,7 @@ import { defaultOptions } from '../../src/shared/constants'
import metaInfoData from '../utils/meta-info-data' import metaInfoData from '../utils/meta-info-data'
import { titleGenerator } from '../../src/server/generators' import { titleGenerator } from '../../src/server/generators'
const generateServerInjector = (type, data) => _generateServerInjector(defaultOptions, type, data) const generateServerInjector = metaInfo => _generateServerInjector(defaultOptions, metaInfo)
describe('generators', () => { describe('generators', () => {
for (const type in metaInfoData) { for (const type in metaInfoData) {
@@ -34,9 +34,9 @@ describe('generators', () => {
} }
const defaultTestFn = () => { const defaultTestFn = () => {
const tags = generateServerInjector(type, testInfo.data) const newInfo = generateServerInjector({ [type]: testInfo.data })
testCases[action](tags) testCases[action](newInfo[type])
return tags return newInfo[type]
} }
let testFn let testFn
@@ -62,6 +62,18 @@ describe('generators', () => {
}) })
describe('extra tests', () => { describe('extra tests', () => {
test('empty config doesnt generate a tag', () => {
const { meta } = generateServerInjector({ meta: [] })
expect(meta.text()).toEqual('')
})
test('config with empty object doesnt generate a tag', () => {
const { meta } = generateServerInjector({ meta: [{}] })
expect(meta.text()).toEqual('')
})
test('title generator should return an empty string when title is null', () => { test('title generator should return an empty string when title is null', () => {
const title = null const title = null
const generatedTitle = titleGenerator({}, 'title', title) const generatedTitle = titleGenerator({}, 'title', title)
@@ -70,19 +82,19 @@ describe('extra tests', () => {
}) })
test('auto add ssrAttribute', () => { test('auto add ssrAttribute', () => {
const htmlAttrs = generateServerInjector('htmlAttrs', {}) const { htmlAttrs } = generateServerInjector({ htmlAttrs: {} })
expect(htmlAttrs.text(true)).toBe('data-vue-meta-server-rendered') expect(htmlAttrs.text(true)).toBe('data-vue-meta-server-rendered')
const headAttrs = generateServerInjector('headAttrs', {}) const { headAttrs } = generateServerInjector({ headAttrs: {} })
expect(headAttrs.text(true)).toBe('') expect(headAttrs.text(true)).toBe('')
const bodyAttrs = generateServerInjector('bodyAttrs', {}) const { bodyAttrs } = generateServerInjector({ bodyAttrs: {} })
expect(bodyAttrs.text(true)).toBe('') expect(bodyAttrs.text(true)).toBe('')
}) })
test('script prepend body', () => { test('script prepend body', () => {
const tags = [{ src: '/script.js', pbody: true }] const tags = [{ src: '/script.js', pbody: true }]
const scriptTags = generateServerInjector('script', tags) const { script: scriptTags } = generateServerInjector({ script: tags })
expect(scriptTags.text()).toBe('') expect(scriptTags.text()).toBe('')
expect(scriptTags.text({ body: true })).toBe('') expect(scriptTags.text({ body: true })).toBe('')
@@ -91,7 +103,7 @@ describe('extra tests', () => {
test('script append body', () => { test('script append body', () => {
const tags = [{ src: '/script.js', body: true }] const tags = [{ src: '/script.js', body: true }]
const scriptTags = generateServerInjector('script', tags) const { script: scriptTags } = generateServerInjector({ script: tags })
expect(scriptTags.text()).toBe('') expect(scriptTags.text()).toBe('')
expect(scriptTags.text({ body: true })).toBe('<script data-vue-meta="ssr" src="/script.js" data-body="true"></script>') expect(scriptTags.text({ body: true })).toBe('<script data-vue-meta="ssr" src="/script.js" data-body="true"></script>')
+1 -1
View File
@@ -1,4 +1,4 @@
import getComponentOption from '../../src/shared/getComponentOption' import { getComponentOption } from '../../src/shared/getComponentOption'
import { inMetaInfoBranch } from '../../src/shared/meta-helpers' import { inMetaInfoBranch } from '../../src/shared/meta-helpers'
import { mount, getVue, loadVueMetaPlugin } from '../utils' import { mount, getVue, loadVueMetaPlugin } from '../utils'
+2 -1
View File
@@ -1,8 +1,9 @@
import { getComponentMetaInfo } from '../../src/shared/getComponentOption'
import _getMetaInfo from '../../src/shared/getMetaInfo' import _getMetaInfo from '../../src/shared/getMetaInfo'
import { loadVueMetaPlugin } from '../utils' import { loadVueMetaPlugin } from '../utils'
import { defaultOptions } from '../../src/shared/constants' import { defaultOptions } from '../../src/shared/constants'
const getMetaInfo = component => _getMetaInfo(defaultOptions, component) const getMetaInfo = component => _getMetaInfo(defaultOptions, getComponentMetaInfo(defaultOptions, component), [], component)
describe('getMetaInfo', () => { describe('getMetaInfo', () => {
let Vue let Vue
+12
View File
@@ -93,4 +93,16 @@ describe('plugin', () => {
warn.mockRestore() warn.mockRestore()
}) })
test('can use generate export', () => {
const rawInfo = {
meta: [{ charset: 'utf-8' }]
}
const metaInfo = VueMetaServerPlugin.generate(rawInfo)
expect(metaInfo.meta.text()).toBe('<meta data-vue-meta="ssr" charset="utf-8">')
// no error on not provided metaInfo types
expect(metaInfo.script.text()).toBe('')
})
}) })
-7
View File
@@ -225,13 +225,6 @@ const metaInfoData = {
data: {}, data: {},
expect: ['<body>'] expect: ['<body>']
} }
},
empty: {
add: {
data: [{}],
expect: [''],
test: side => side === 'server'
}
} }
} }