refactor: update code style

This commit is contained in:
ULIVZ
2019-02-04 02:02:44 +08:00
parent 8f5b0cd18e
commit 8f43be567f
29 changed files with 118 additions and 117 deletions
+2 -1
View File
@@ -6,6 +6,7 @@ module.exports = {
],
rules: {
indent: ['error', 2, { MemberExpression: 'off' }],
"no-undef": ["error"]
"no-undef": ["error"],
'operator-linebreak': ["error", "before"]
}
}
+2 -2
View File
@@ -21,8 +21,8 @@ if (module.hot) {
module.hot.accept(VUEPRESS_TEMP_PATH + '/internal/siteData.js', () => {
if (siteData.base !== prevBase) {
window.alert(
`[vuepress] Site base has changed. ` +
`Please restart dev server to ensure correct asset paths.`
`[vuepress] Site base has changed. `
+ `Please restart dev server to ensure correct asset paths.`
)
}
})
+2 -2
View File
@@ -101,8 +101,8 @@ async function prepareServer (sourceDir, cliOptions = {}, context) {
const { host, displayHost } = await resolveHost(cliOptions.host || ctx.siteConfig.host)
// debug in a running dev process.
process.stdin &&
process.stdin.on('data', chunk => {
process.stdin
&& process.stdin.on('data', chunk => {
const parsed = chunk.toString('utf-8').trim()
if (parsed === '*') {
console.log(Object.keys(ctx))
@@ -12,11 +12,11 @@ module.exports = function (source, map) {
const cached = cache.get(file)
const parsed = parseStrippedFrontmatter(source)
if (cached &&
cached.data &&
parsed &&
parsed.data &&
JSON.stringify(cached.data) !== JSON.stringify(parsed.data)
if (cached
&& cached.data
&& parsed
&& parsed.data
&& JSON.stringify(cached.data) !== JSON.stringify(parsed.data)
) {
frontmatterEmitter.emit('update')
}
@@ -169,8 +169,8 @@ module.exports = class PluginAPI {
this.options[option.name].add(pluginName, value)
} else if (value !== undefined) {
logger.warn(
`${chalk.gray(pluginName)} ` +
`Invalid value for "option" ${chalk.cyan(option.name)}: ${warnMsg}`
`${chalk.gray(pluginName)} `
+ `Invalid value for "option" ${chalk.cyan(option.name)}: ${warnMsg}`
)
}
return this
@@ -67,8 +67,8 @@ module.exports = class EnhanceAppFilesOption extends AsyncOption {
}
} else {
logger.developer(
chalk.gray(`[${pluginName}] `) +
`${chalk.cyan(enhanceAppFile)} Not Found.`
chalk.gray(`[${pluginName}] `)
+ `${chalk.cyan(enhanceAppFile)} Not Found.`
)
}
}
@@ -26,8 +26,8 @@ exports.flattenPlugin = function (
if (!valid) {
if (pluginOptions !== undefined) {
logger.warn(
`[${chalk.gray(shortcut)}] ` +
`Invalid value for "pluginOptions" ${chalk.cyan(name)}: ${warnMsg}`
`[${chalk.gray(shortcut)}] `
+ `Invalid value for "pluginOptions" ${chalk.cyan(name)}: ${warnMsg}`
)
}
pluginOptions = {}
@@ -69,8 +69,8 @@ exports.normalizePluginsConfig = function (pluginsConfig) {
if (!valid) {
if (pluginsConfig !== undefined) {
logger.warn(
`[${chalk.gray('config')}] ` +
`Invalid value for "plugin" field : ${warnMsg}`
`[${chalk.gray('config')}] `
+ `Invalid value for "plugin" field : ${warnMsg}`
)
}
pluginsConfig = []
@@ -130,8 +130,8 @@ module.exports = class AppContext {
const siteConfig = this.siteConfig
const shouldUseLastUpdated = (
themeConfig.lastUpdated ||
Object.keys(siteConfig.locales && themeConfig.locales || {})
themeConfig.lastUpdated
|| Object.keys(siteConfig.locales && themeConfig.locales || {})
.some(base => themeConfig.locales[base].lastUpdated)
)
@@ -38,19 +38,19 @@ exports.getCacheLoaderOptions = function (siteConfig, cliOptions, cwd, isProd) {
siteConfig.markdown
? JSON.stringify(siteConfig.markdown)
: ''
) +
(
)
+ (
siteConfig.markdown && siteConfig.markdown.extendMarkdown
? siteConfig.markdown.extendMarkdown.toString()
: ''
) +
(
)
+ (
siteConfig.extendMarkdown
? siteConfig.extendMarkdown.toString()
: ''
) +
(siteConfig.chainWebpack || '').toString() +
(siteConfig.configureWebpack || '').toString()
)
+ (siteConfig.chainWebpack || '').toString()
+ (siteConfig.configureWebpack || '').toString()
)
})
@@ -74,8 +74,8 @@ module.exports = siteData => {
const siteTitle = this.$siteTitle
const selfTitle = page.frontmatter.home ? null : (
page.frontmatter.title || // explicit title
page.title // inferred title
page.frontmatter.title // explicit title
|| page.title // inferred title
)
return siteTitle
? selfTitle
@@ -34,10 +34,10 @@ module.exports = async function loadTheme (ctx) {
const themeResolver = getThemeResolver()
const localThemePath = path.resolve(vuepressDir, 'theme')
const useLocalTheme =
!fs.existsSync(theme) &&
fs.existsSync(localThemePath) &&
(fs.readdirSync(localThemePath)).length > 0
const useLocalTheme
= !fs.existsSync(theme)
&& fs.existsSync(localThemePath)
&& (fs.readdirSync(localThemePath)).length > 0
let themePath = null // Mandatory
let themeEntryFile = null // Optional
@@ -119,8 +119,8 @@ module.exports = async function loadTheme (ctx) {
const readdirSync = dir => fs.existsSync(dir) && fs.readdirSync(dir) || []
// built-in named layout or not.
const isInternal = componentName => componentName === 'Layout' ||
componentName === 'NotFound'
const isInternal = componentName => componentName === 'Layout'
|| componentName === 'NotFound'
const layoutComponentMap = layoutDirs
.map(
@@ -25,9 +25,9 @@ module.exports = class DevLogPlugin {
const displayUrl = `http://${displayHost}:${port}${publicPath}`
logger.success(
`${chalk.gray(`[${time}]`)} Build ${chalk.italic(stats.hash.slice(0, 6))} ` +
`finished in ${stats.endTime - stats.startTime} ms! ` +
(
`${chalk.gray(`[${time}]`)} Build ${chalk.italic(stats.hash.slice(0, 6))} `
+ `finished in ${stats.endTime - stats.startTime} ms! `
+ (
isFirst
? ''
: `${chalk.gray(`(${displayUrl})`)}`
+12 -12
View File
@@ -49,9 +49,9 @@ module.exports = function (src) {
// returned component, changes in frontmatter do not trigger proper updates
const cachedData = devCache.get(file)
if (cachedData && (
cachedData.inferredTitle !== inferredTitle ||
JSON.stringify(cachedData.frontmatterData) !== JSON.stringify(frontmatter.data) ||
headersChanged(cachedData.headers, headers)
cachedData.inferredTitle !== inferredTitle
|| JSON.stringify(cachedData.frontmatterData) !== JSON.stringify(frontmatter.data)
|| headersChanged(cachedData.headers, headers)
)) {
// frontmatter changed... need to do a full reload
module.exports.frontmatterEmitter.emit('update')
@@ -91,19 +91,19 @@ module.exports = function (src) {
if (!fs.existsSync(file) && (!altfile || !fs.existsSync(altfile))) {
this.emitWarning(
new Error(
`\nFile for relative link "${link}" does not exist.\n` +
`(Resolved file: ${file})\n`
`\nFile for relative link "${link}" does not exist.\n`
+ `(Resolved file: ${file})\n`
)
)
}
})
const res = (
`<template>\n` +
`<ContentSlotsDistributor :slot-key="$parent.slotKey">${html}</ContentSlotsDistributor>\n` +
`</template>\n` +
(hoistedTags || []).join('\n') +
`\n${dataBlockString}\n`
`<template>\n`
+ `<ContentSlotsDistributor :slot-key="$parent.slotKey">${html}</ContentSlotsDistributor>\n`
+ `</template>\n`
+ (hoistedTags || []).join('\n')
+ `\n${dataBlockString}\n`
)
cache.set(key, res)
return res
@@ -112,8 +112,8 @@ module.exports = function (src) {
function headersChanged (a, b) {
if (a.length !== b.length) return true
return a.some((h, i) => (
h.title !== b[i].title ||
h.level !== b[i].level
h.title !== b[i].title
|| h.level !== b[i].level
))
}
@@ -41,8 +41,8 @@ module.exports = md => {
return '<br>'
}).join('')
const highlightLinesWrapperCode =
`<div class="highlight-lines">${highlightLinesCode}</div>`
const highlightLinesWrapperCode
= `<div class="highlight-lines">${highlightLinesCode}</div>`
return highlightLinesWrapperCode + code
}
@@ -14,8 +14,8 @@ module.exports = md => {
const lineNumbersCode = [...Array(lines.length - 1)]
.map((line, index) => `<span class="line-number">${index + 1}</span><br>`).join('')
const lineNumbersWrapperCode =
`<div class="line-numbers-wrapper">${lineNumbersCode}</div>`
const lineNumbersWrapperCode
= `<div class="line-numbers-wrapper">${lineNumbersCode}</div>`
const finalCode = rawCode
.replace('<!--beforeend-->', `${lineNumbersWrapperCode}<!--beforeend-->`)
@@ -13,7 +13,7 @@ module.exports = md => {
const [tokens, idx] = args
const token = tokens[idx]
const rawCode = fence(...args)
return `<!--beforebegin--><div class="language-${token.info.trim()} extra-class">` +
`<!--afterbegin-->${rawCode}<!--beforeend--></div><!--afterend-->`
return `<!--beforebegin--><div class="language-${token.info.trim()} extra-class">`
+ `<!--afterbegin-->${rawCode}<!--beforeend--></div><!--afterend-->`
}
}
@@ -27,9 +27,9 @@ export default {
const anchor = anchors[i]
const nextAnchor = anchors[i + 1]
const isActive = i === 0 && scrollTop === 0 ||
(scrollTop >= anchor.parentElement.offsetTop + 10 &&
(!nextAnchor || scrollTop < nextAnchor.parentElement.offsetTop - 10))
const isActive = i === 0 && scrollTop === 0
|| (scrollTop >= anchor.parentElement.offsetTop + 10
&& (!nextAnchor || scrollTop < nextAnchor.parentElement.offsetTop - 10))
if (isActive && decodeURIComponent(this.$route.hash) !== decodeURIComponent(anchor.hash)) {
this.$vuepress.$set('disableScrollBehavior', true)
@@ -40,9 +40,9 @@ export default {
methods: {
getScrollTop () {
return window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop || 0
return window.pageYOffset
|| document.documentElement.scrollTop
|| document.body.scrollTop || 0
},
scrollToTop () {
@@ -12,9 +12,9 @@ if (SW_UPDATE_POPUP) {
export default ({ router, isServer }) => {
// Register service worker
router.onReady(() => {
if (process.env.NODE_ENV === 'production' &&
!isServer &&
SW_ENABLED) {
if (process.env.NODE_ENV === 'production'
&& !isServer
&& SW_ENABLED) {
register(`${SW_BASE_URL}service-worker.js`, {
ready () {
console.log('[vuepress:sw] Service worker is active.')
@@ -49,9 +49,9 @@ export default {
computed: {
showSuggestions () {
return (
this.focused &&
this.suggestions &&
this.suggestions.length
this.focused
&& this.suggestions
&& this.suggestions.length
)
},
@@ -65,8 +65,8 @@ export default {
const max = SEARCH_MAX_SUGGESTIONS
const localePath = this.$localePath
const matches = item => (
item.title &&
item.title.toLowerCase().indexOf(query) > -1
item.title
&& item.title.toLowerCase().indexOf(query) > -1
)
const res = []
for (let i = 0; i < pages.length; i++) {
@@ -18,17 +18,17 @@ const EXPORTED_MODULES = [
['hash-sum', 'hash']
]
const code =
[
const code
= [
...modules.map(v => getImport(v, `./${v}`)),
...EXPORTED_MODULES.map(v => Array.isArray(v) ? getImport(v[1], v[0]) : getImport(v, v))
].join('\n') +
`\n\nexport {\n` +
[
].join('\n')
+ `\n\nexport {\n`
+ [
...modules,
...EXPORTED_MODULES.map(v => Array.isArray(v) ? v[1] : v)
].map(v => ` ${v},`).join('\n') +
'\n}'
].map(v => ` ${v},`).join('\n')
+ '\n}'
fs.writeFileSync(target, code, 'utf-8')
@@ -58,8 +58,8 @@ export default {
if (document.documentElement.clientWidth < MOBILE_DESKTOP_BREAKPOINT) {
this.linksWrapMaxWidth = null
} else {
this.linksWrapMaxWidth = this.$el.offsetWidth - NAVBAR_VERTICAL_PADDING -
(this.$refs.siteName && this.$refs.siteName.offsetWidth || 0)
this.linksWrapMaxWidth = this.$el.offsetWidth - NAVBAR_VERTICAL_PADDING
- (this.$refs.siteName && this.$refs.siteName.offsetWidth || 0)
}
}
handleLinksWrapWidth()
@@ -129,9 +129,9 @@ export default {
editLinkText () {
return (
this.$themeLocaleConfig.editLinkText ||
this.$site.themeConfig.editLinkText ||
`Edit this page`
this.$themeLocaleConfig.editLinkText
|| this.$site.themeConfig.editLinkText
|| `Edit this page`
)
}
},
@@ -144,12 +144,12 @@ export default {
? docsRepo
: repo
return (
base.replace(endingSlashRE, '') +
`/src` +
`/${docsBranch}` +
(docsDir ? '/' + docsDir.replace(endingSlashRE, '') : '') +
path +
`?mode=edit&spa=0&at=${docsBranch}&fileviewer=file-view-default`
base.replace(endingSlashRE, '')
+ `/src`
+ `/${docsBranch}`
+ (docsDir ? '/' + docsDir.replace(endingSlashRE, '') : '')
+ path
+ `?mode=edit&spa=0&at=${docsBranch}&fileviewer=file-view-default`
)
}
@@ -158,10 +158,10 @@ export default {
: `https://github.com/${docsRepo}`
return (
base.replace(endingSlashRE, '') +
`/edit/${docsBranch}` +
(docsDir ? '/' + docsDir.replace(endingSlashRE, '') : '') +
path
base.replace(endingSlashRE, '')
+ `/edit/${docsBranch}`
+ (docsDir ? '/' + docsDir.replace(endingSlashRE, '') : '')
+ path
)
}
}
@@ -30,15 +30,15 @@ export default {
: selfActive
const link = renderLink(h, item.path, item.title || item.path, active)
const configDepth = $page.frontmatter.sidebarDepth ||
sidebarDepth ||
$themeLocaleConfig.sidebarDepth ||
$themeConfig.sidebarDepth
const configDepth = $page.frontmatter.sidebarDepth
|| sidebarDepth
|| $themeLocaleConfig.sidebarDepth
|| $themeConfig.sidebarDepth
const maxDepth = configDepth == null ? 1 : configDepth
const displayAllHeaders = $themeLocaleConfig.displayAllHeaders ||
$themeConfig.displayAllHeaders
const displayAllHeaders = $themeLocaleConfig.displayAllHeaders
|| $themeConfig.displayAllHeaders
if (item.type === 'auto') {
return [link, renderChildren(h, item.children, item.basePath, $route, maxDepth)]
+2 -2
View File
@@ -6,8 +6,8 @@ module.exports = (options, ctx) => ({
const { themeConfig, siteConfig } = ctx
// resolve algolia
const isAlgoliaSearch = (
themeConfig.algolia ||
Object.keys(siteConfig.locales && themeConfig.locales || {})
themeConfig.algolia
|| Object.keys(siteConfig.locales && themeConfig.locales || {})
.some(base => themeConfig.locales[base].algolia)
)
return {
@@ -68,25 +68,25 @@ export default {
const { themeConfig } = this.$site
const { frontmatter } = this.$page
if (
frontmatter.navbar === false ||
themeConfig.navbar === false) {
frontmatter.navbar === false
|| themeConfig.navbar === false) {
return false
}
return (
this.$title ||
themeConfig.logo ||
themeConfig.repo ||
themeConfig.nav ||
this.$themeLocaleConfig.nav
this.$title
|| themeConfig.logo
|| themeConfig.repo
|| themeConfig.nav
|| this.$themeLocaleConfig.nav
)
},
shouldShowSidebar () {
const { frontmatter } = this.$page
return (
!frontmatter.home &&
frontmatter.sidebar !== false &&
this.sidebarItems.length
!frontmatter.home
&& frontmatter.sidebar !== false
&& this.sidebarItems.length
)
},
@@ -9,11 +9,11 @@ export default {
watch: {
'$route' (to, from) {
if (
to.path !== from.path &&
to.path !== from.path
// Only reload if the ad has been loaded
// otherwise it's possible that the script is appended but
// the ads are not loaded yet. This would result in duplicated ads.
this.$el.querySelector('#carbonads')
&& this.$el.querySelector('#carbonads')
) {
this.$el.innerHTML = ''
this.load()
+3 -3
View File
@@ -15,9 +15,9 @@ module.exports = function checkEnv (pkg) {
if (!semver.satisfies(process.version, requiredVersion)) {
console.log(chalk.red(
`\n[vuepress] minimum Node version not met:` +
`\nYou are using Node ${process.version}, but VuePress ` +
`requires Node ${requiredVersion}.\nPlease upgrade your Node version.\n`
`\n[vuepress] minimum Node version not met:`
+ `\nYou are using Node ${process.version}, but VuePress `
+ `requires Node ${requiredVersion}.\nPlease upgrade your Node version.\n`
))
process.exit(1)
}
@@ -20,8 +20,8 @@ module.exports = async function (cli, options) {
const inferredUserDocsDirectory = await inferUserDocsDirectory(pwd)
logger.developer('inferredUserDocsDirectory', inferredUserDocsDirectory)
const needPrepareBeforeLaunchCLI = inferredUserDocsDirectory &&
(isHelpFlag(argv[0]) || isUnknownCommandHelp(argv))
const needPrepareBeforeLaunchCLI = inferredUserDocsDirectory
&& (isHelpFlag(argv[0]) || isUnknownCommandHelp(argv))
logger.developer('needPrepareBeforeLaunchCLI', needPrepareBeforeLaunchCLI)