提交 8988acf5 编写于 作者: EvanOne(文一)'s avatar EvanOne(文一)

refactor: fully use standard coding style and lint check

上级 c4efb05b
/* global hexo */ 'use strict'
'use strict'; hexo.extend.helper.register('hexo_env', function (type) {
return this.env[type]
hexo.extend.helper.register('hexo_env', function(type) { })
return this.env[type];
});
hexo.extend.helper.register('stun_env', function (type) { hexo.extend.helper.register('stun_env', function (type) {
var env = require('../package.json'); var env = require('../package.json')
return env[type]; return env[type]
}); })
/* global hexo */ 'use strict'
'use strict'; hexo.extend.filter.register(
'after_post_render',
hexo.extend.filter.register('after_post_render', function (data) { function (data) {
var theme = hexo.theme.config; var theme = hexo.theme.config
if ( if (
!theme.external_link || !theme.external_link ||
!theme.external_link.icon || !theme.external_link.icon ||
!theme.external_link.icon.enable !theme.external_link.icon.enable
) { ) {
return; return
} }
var url = require('url'); var config = this.config
var config = this.config; var url = new URL(config.url)
var siteHost = url.parse(config.url).hostname || config.url; var siteHost = url.hostname || config.url
// Match 'a' tags that don't contain html children. // Match 'a' tags that don't contain html children.
var regPureATag = /<a([^>]*)href="([^"]*)"([^>]*)>([^<]*)<\/a>/gim; var regPureATag = /<a([^>]*)href="([^"]*)"([^>]*)>([^<]*)<\/a>/gim
data.content = data.content.replace( data.content = data.content.replace(regPureATag, function (
regPureATag, match,
function (match, attrBegin, href, attrEnd, html) { attrBegin,
href,
attrEnd,
html
) {
// Exit if the href attribute doesn't exists. // Exit if the href attribute doesn't exists.
if (!href) { if (!href) {
return match; return match
}
var link = ''
try {
link = new URL(href)
} catch (e) {
// Invalid url, e.g. Anchor link.
return match
} }
// Exit if the url has same host with `config.url`, which means isn't an external link. // Exit if the url has same host with `config.url`, which means isn't an external link.
var link = url.parse(href);
if (!link.protocol || link.hostname === siteHost) { if (!link.protocol || link.hostname === siteHost) {
return match; return match
}; }
return ( return (
'<span class="exturl">' + '<span class="exturl">' +
`<a class="exturl__link" ${attrBegin} href="${href}" ${attrEnd}>${html}</a>` + `<a class="exturl__link" ${attrBegin} href="${href}" ${attrEnd}>${html}</a>` +
`<span class="exturl__icon"><i class="${theme.external_link.icon.name}"></i></span>` + `<span class="exturl__icon"><i class="${theme.external_link.icon.name}"></i></span>` +
'</span>' '</span>'
); )
} })
); },
}, 0); 0
)
/* global hexo */ 'use strict'
'use strict'; hexo.extend.filter.register(
'after_post_render',
hexo.extend.filter.register('after_post_render', function (data) { function (data) {
data.content = data.content.replace( data.content = data.content.replace(
// Match 'img' tags width the src attribute. // Match 'img' tags width the src attribute.
/<img([^>]*)src="([^"]*)"([^>]*)>/gim, /<img([^>]*)src="([^"]*)"([^>]*)>/gim,
function (match, attrBegin, src, attrEnd) { function (match, attrBegin, src, attrEnd) {
// Exit if the src doesn't exists. // Exit if the src doesn't exists.
if (!src) { if (!src) {
return match; return match
}
var search = src.split('?')[1];
// Exit if the src doesn't include query parameter.
if (!search) {
return match;
}
var params = search.split('&').filter(i => i !== '');
// Exit if the query parameter is empty.
if (!params.length) {
return match;
}
var size = '';
var show = '';
var style = '';
params.forEach(param => {
if (param.includes('size')) {
size = param.split('=')[1] || '';
} }
if (param.includes('show')) {
show = param.split('=')[1] || ''; var search = src.split('?')[1]
// Exit if the src doesn't include query parameter.
if (!search) {
return match
} }
});
if (size !== '') { var params = search.split('&').filter(i => i !== '')
// The sign between width and height. // Exit if the query parameter is empty.
var MULTIPLY_SIGN = 'x'; if (!params.length) {
var w = size.split(MULTIPLY_SIGN)[0]; return match
var h = size.split(MULTIPLY_SIGN)[1]; }
if (w) { var size = ''
style += `width: ${w}px;`; var show = ''
var style = ''
params.forEach(param => {
if (param.includes('size')) {
size = param.split('=')[1] || ''
}
if (param.includes('show')) {
show = param.split('=')[1] || ''
}
})
if (size !== '') {
// The sign between width and height.
var MULTIPLY_SIGN = 'x'
var w = size.split(MULTIPLY_SIGN)[0]
var h = size.split(MULTIPLY_SIGN)[1]
if (w) {
style += `width: ${w}px;`
}
if (h) {
style += `height: ${h}px;`
}
} }
if (h) { if (show === 'inline') {
style += `height: ${h}px;`; style += 'display: inline-block;'
} }
}
if (show === 'inline') {
style += 'display: inline-block;';
}
return `<img ${attrBegin} src="${src}" style="${style}" ${attrEnd}>`; return `<img ${attrBegin} src="${src}" style="${style}" ${attrEnd}>`
} }
); )
}, 0); },
0
)
/* global hexo */ 'use strict'
'use strict'; hexo.extend.filter.register(
'after_post_render',
hexo.extend.filter.register('after_post_render', function (data) { function (data) {
var theme = hexo.theme.config; var theme = hexo.theme.config
if (!theme.lazyload || !theme.lazyload.enable) { if (!theme.lazyload || !theme.lazyload.enable) {
return; return
} }
data.content = data.content.replace( data.content = data.content.replace(
// Match 'img' tags width the src attribute. // Match 'img' tags width the src attribute.
/<img([^>]*)src="([^"]*)"([^>]*)>/gim, /<img([^>]*)src="([^"]*)"([^>]*)>/gim,
function (match, attrBegin, src, attrEnd) { function (match, attrBegin, src, attrEnd) {
// Exit if the src doesn't exists. // Exit if the src doesn't exists.
if (!src) { if (!src) {
return match; return match
} }
// Smallest 1 * 1 pixel transparent gif // Smallest 1 * 1 pixel transparent gif
var loadingBlock = 'data:image/gif;base64,R0lGODdhAQABAPAAAMPDwwAAACwAAAAAAQABAAACAkQBADs='; var loadingBlock =
var loadingGIF = `/${theme.images}/loading.svg`; 'data:image/gif;base64,R0lGODdhAQABAPAAAMPDwwAAACwAAAAAAQABAAACAkQBADs='
var phClassName = theme.lazyload.placeholder; var loadingGIF = `/${theme.images}/loading.svg`
var placeholder = ''; var phClassName = theme.lazyload.placeholder
var placeholder = ''
if (phClassName === 'gif') { if (phClassName === 'gif') {
placeholder = loadingGIF; placeholder = loadingGIF
} else if (phClassName === 'block') { } else if (phClassName === 'block') {
placeholder = loadingBlock; placeholder = loadingBlock
} }
var className = `lazyload lazyload-${phClassName}`; var className = `lazyload lazyload-${phClassName}`
return ` return `
<img ${attrBegin} class="${className}" <img ${attrBegin} class="${className}"
src="${placeholder}" data-src="${src}" ${attrEnd}> src="${placeholder}" data-src="${src}" ${attrEnd}>
`; `
} }
); )
}, 1); },
1
)
/* global hexo */ 'use strict'
'use strict'; hexo.extend.filter.register(
'after_post_render',
function (data) {
var theme = hexo.theme.config
var tagName = 'h[1-6]'
var attrId = 'id="([^"]*)"'
var tagNotEnd = '([^>]*)'
var regAttrId = tagNotEnd + attrId + tagNotEnd
// Match the innermost 'h1~6' tags width the id attribute.
var regHTagInnermost = new RegExp(
`<(${tagName})${regAttrId}>((?:(?!<\\/?${tagName}${regAttrId}>)(?:\\s|\\S))*?)</${tagName}>`,
'gim'
)
hexo.extend.filter.register('after_post_render', function (data) { data.content = data.content.replace(regHTagInnermost, function (
var theme = hexo.theme.config; match,
var tagName = `h[1-6]`; tName,
var attrId = `id="([^"]*)"`; attrBegin,
var tagNotEnd = `([^>]*)`; id,
var regAttrId = tagNotEnd + attrId + tagNotEnd; attrEnd,
// Match the innermost 'h1~6' tags width the id attribute. html
var regHTagInnermost = new RegExp( ) {
`<(${tagName})${regAttrId}>((?:(?!<\\/?${tagName}${regAttrId}>)(?:\\s|\\S))*?)<\/${tagName}>`,
'gim'
);
data.content = data.content.replace(
regHTagInnermost,
function (match, tName, attrBegin, id, attrEnd, html) {
if (!id) { if (!id) {
return match; return match
} }
var filterHtml = (html.replace(/<[^>]+>/gim, '') || '').trim(); var filterHtml = (html.replace(/<[^>]+>/gim, '') || '').trim()
return ` return `
<${tName} id="${id}" ${attrBegin} ${attrEnd}> <${tName} id="${id}" ${attrBegin} ${attrEnd}>
<a href="#${id}" class="heading-link"><i class="${ <a href="#${id}" class="heading-link"><i class="${theme.icon &&
theme.icon && theme.icon.post_heading theme.icon.post_heading}"></i></a>${filterHtml}</${tName}>
}"></i></a>${ `
filterHtml })
}</${tName}> },
`; 0
} )
);
}, 0);
/* global hexo */ 'use strict'
'use strict';
hexo.extend.filter.register('after_generate', function () { hexo.extend.filter.register('after_generate', function () {
var theme = hexo.theme.config; var theme = hexo.theme.config
if (!theme.shake_file) { if (!theme.shake_file) {
return; return
} }
if (!(theme.sidebar && theme.sidebar.enable)) { if (!(theme.sidebar && theme.sidebar.enable)) {
hexo.route.remove('js/sidebar.js'); hexo.route.remove('js/sidebar.js')
} }
}); })
/* global hexo */ 'use strict'
'use strict'; hexo.extend.filter.register(
'after_post_render',
function (data) {
data.content = data.content.replace(
// Match the innermost 'table' tag.
/(<table[^>]*>(?:(?!<\/?table>)(?:\s|\S))*?<\/table>)/gim,
function (match, table) {
if (!table) {
return match
}
hexo.extend.filter.register('after_post_render', function (data) { return `<div class="table-container">${table}</div>`
data.content = data.content.replace(
// Match the innermost 'table' tag.
/(<table[^>]*>(?:(?!<\/?table>)(?:\s|\S))*?<\/table>)/gim,
function (match, table) {
if (!table) {
return match;
} }
)
return `<div class="table-container">${table}</div>`; },
} 0
); )
}, 0);
/* global hexo */ 'use strict'
'use strict';
hexo.on('generateBefore', function () { hexo.on('generateBefore', function () {
var rootConfig = hexo.config; var rootConfig = hexo.config
if (hexo.locals.get) { if (hexo.locals.get) {
var data = hexo.locals.get('data'); var data = hexo.locals.get('data')
if (data && data.stun) { if (data && data.stun) {
hexo.theme.config = data.stun; hexo.theme.config = data.stun
} }
} }
hexo.theme.config.rootConfig = rootConfig; hexo.theme.config.rootConfig = rootConfig
}); })
/* global hexo */ 'use strict'
'use strict'; var pathFn = require('path')
var fs = require('hexo-fs')
var pathFn = require('path'); function friends (args) {
var fs = require('hexo-fs'); var path = pathFn.join(hexo.source_dir, args[0])
function friends(args) { fs.exists(path).then(function (exist) {
var path = pathFn.join(hexo.source_dir, args[0]);
fs.exists(path).then(function(exist) {
if (!exist) { if (!exist) {
hexo.log.error('Include file not found!'); hexo.log.error('Include file not found!')
return;
} }
}); })
return fs.readFile(path).then(function(data) { return fs.readFile(path).then(function (data) {
if (!data) { if (!data) {
hexo.log.warn('Include file empty.'); hexo.log.warn('Include file empty.')
return; return
} }
var imgClassName = 'friends-plugin__item-avatar '; var imgClassName = 'friends-plugin__item-avatar '
var theme = hexo.theme.config; var theme = hexo.theme.config
if (theme.lazyload && theme.lazyload.enable) { if (theme.lazyload && theme.lazyload.enable) {
imgClassName += `lazyload lazyload-${theme.lazyload.placeholder}`; imgClassName += `lazyload lazyload-${theme.lazyload.placeholder}`
} }
var friends = JSON.parse(data); var friends = JSON.parse(data)
var renderHtml = '<div class="friends-plugin">'; var renderHtml = '<div class="friends-plugin">'
friends.forEach(f => { friends.forEach(f => {
renderHtml += renderHtml +=
`<a class="friends-plugin__item" href="${f.url}">` + `<a class="friends-plugin__item" href="${f.url}">` +
`<img class="${imgClassName}" src="${f.avatar}" data-zoom="none">` + `<img class="${imgClassName}" src="${f.avatar}" data-zoom="none">` +
'<div class="friends-plugin__item-info">' + '<div class="friends-plugin__item-info">' +
`<p class="friends-plugin__item-info__name" title="${f.name}">${f.name}</p>` + `<p class="friends-plugin__item-info__name" title="${f.name}">${f.name}</p>` +
`<p class="friends-plugin__item-info__intro" title="${f.introduction}">${f.introduction}</p>` + `<p class="friends-plugin__item-info__intro" title="${f.introduction}">${f.introduction}</p>` +
'</div>' + '</div>' +
'</a>'; '</a>'
}); })
renderHtml += '</div>'; renderHtml += '</div>'
return renderHtml; return renderHtml
}); })
} }
hexo.extend.tag.register('friends', friends, { ends: false, async: true }); hexo.extend.tag.register('friends', friends, { ends: false, async: true })
/* global hexo */ 'use strict'
'use strict'; function note (args, content) {
var theme = hexo.theme.config
function note(args, content) { var icon = theme.icon && theme.icon.notetag_default
var theme = hexo.theme.config; var iconType = 'default'
var icon = theme.icon && theme.icon.notetag_default; var isIcon = true
var iconType = 'default';
var isIcon = true;
if (args.includes('no-icon')) { if (args.includes('no-icon')) {
isIcon = false; isIcon = false
} }
if (isIcon && theme.icon) { if (isIcon && theme.icon) {
var tagTypes = ['default', 'success', 'info', 'warning', 'danger']; var tagTypes = ['default', 'success', 'info', 'warning', 'danger']
tagTypes.forEach(type => { tagTypes.forEach(type => {
if (args.includes(type)) { if (args.includes(type)) {
icon = theme.icon[`notetag_${type}`]; icon = theme.icon[`notetag_${type}`]
iconType = type; iconType = type
} }
}); })
} }
var className = args.join(' '); var className = args.join(' ')
return ` return `
<div class="note-plugin ${className}"> <div class="note-plugin ${className}">
${ ${
...@@ -36,7 +34,7 @@ function note(args, content) { ...@@ -36,7 +34,7 @@ function note(args, content) {
.split('\n') .split('\n')
.join('')} .join('')}
</div> </div>
`; `
} }
hexo.extend.tag.register('note', note, { ends: true }); hexo.extend.tag.register('note', note, { ends: true })
/* global hexo */ 'use strict'
'use strict'; var pathFn = require('path')
var fs = require('hexo-fs')
var pathFn = require('path'); function table (args) {
var fs = require('hexo-fs'); var path = pathFn.join(hexo.source_dir, args[0])
var headers = args[1].split(',')
function table(args) { fs.exists(path).then(function (exist) {
var path = pathFn.join(hexo.source_dir, args[0]);
var headers = args[1].split(',');
fs.exists(path).then(function(exist) {
if (!exist) { if (!exist) {
hexo.log.error('Include file not found!'); hexo.log.error('Include file not found!')
return;
} }
}); })
return fs.readFile(path).then(function(data) { return fs.readFile(path).then(function (data) {
if (!data) { if (!data) {
hexo.log.warn('Include file empty.'); hexo.log.warn('Include file empty.')
return; return
} }
var tableData = JSON.parse(data); var tableData = JSON.parse(data)
var result = '<table class="table-plugin"><thead><tr>'; var result = '<table class="table-plugin"><thead><tr>'
headers.forEach(header => (result += `<th>${header}</th>`)); headers.forEach(header => (result += `<th>${header}</th>`))
result += '</tr></thead><tbody>'; result += '</tr></thead><tbody>'
tableData.forEach(item => { tableData.forEach(item => {
result += '<tr style="text-align: center;">'; result += '<tr style="text-align: center;">'
for (var key in item) { for (var key in item) {
if (item.hasOwnProperty(key)) { if (Object.prototype.hasOwnProperty.call(item, key)) {
var value = item[key]; var value = item[key]
result += `<td>${value}</td>`; result += `<td>${value}</td>`
} }
} }
result += '</tr>'; result += '</tr>'
}); })
result += '</tbody></table>'; result += '</tbody></table>'
return result; return result
}); })
} }
hexo.extend.tag.register('table', table, { ends: false, async: true }); hexo.extend.tag.register('table', table, { ends: false, async: true })
$(document).ready(function () { $(document).ready(function () {
var $menuBtn = $('.header-nav-menubtn'); var $menuBtn = $('.header-nav-menubtn')
var $menu = $('.header-nav-menu'); var $menu = $('.header-nav-menu')
var $menuItem = $('.header-nav-menu-item'); var $menuItem = $('.header-nav-menu-item')
var $submenu = $('.header-nav-submenu'); var $submenu = $('.header-nav-submenu')
var isMobile = $menuBtn.is(':visible'); var isMobile = $menuBtn.is(':visible')
var isMenuShow = false; var isMenuShow = false
var isSubmenuShow = false; var isSubmenuShow = false
function resetMenuHeight () { function resetMenuHeight () {
$menuItem.velocity( $menuItem.velocity(
...@@ -15,102 +15,104 @@ $(document).ready(function () { ...@@ -15,102 +15,104 @@ $(document).ready(function () {
}, },
{ {
complete: function () { complete: function () {
$submenu.css({ display: 'none', opacity: 0 }); $submenu.css({ display: 'none', opacity: 0 })
} }
} }
); )
} }
$(window).on( $(window).on(
'resize', 'resize',
Stun.utils.throttle(function () { Stun.utils.throttle(function () {
isMobile = $menuBtn.is(':visible'); isMobile = $menuBtn.is(':visible')
if (isMobile) { if (isMobile) {
$submenu.removeClass('hide--force'); $submenu.removeClass('hide--force')
if (isSubmenuShow) { if (isSubmenuShow) {
resetMenuHeight(); resetMenuHeight()
isSubmenuShow = false; isSubmenuShow = false
} }
} else { } else {
$submenu.css({ display: 'none', opacity: 0 }); $submenu.css({ display: 'none', opacity: 0 })
} }
}, 200) }, 200)
); )
var isNightModeFocus = true; var isNightModeFocus = true
var $nightMode = $('.mode'); var $nightMode = $('.mode')
$(document).on('click', function () { $(document).on('click', function () {
if ($menu.is(':visible')) { if ($menu.is(':visible')) {
if (isMobile && isSubmenuShow) { if (isMobile && isSubmenuShow) {
resetMenuHeight(); resetMenuHeight()
isSubmenuShow = false; isSubmenuShow = false
} }
$menu.css({ display: 'none' }); $menu.css({ display: 'none' })
isMenuShow = false; isMenuShow = false
} }
if (isNightModeFocus) { if (isNightModeFocus) {
$nightMode.removeClass('mode--focus'); $nightMode.removeClass('mode--focus')
isNightModeFocus = false; isNightModeFocus = false
} }
}); })
Stun.utils.pjaxReloadHeader = function () { Stun.utils.pjaxReloadHeader = function () {
$menuBtn = $('.header-nav-menubtn'); $menuBtn = $('.header-nav-menubtn')
$menu = $('.header-nav-menu'); $menu = $('.header-nav-menu')
$menuItem = $('.header-nav-menu-item'); $menuItem = $('.header-nav-menu-item')
$submenu = $('.header-nav-submenu'); $submenu = $('.header-nav-submenu')
isMobile = $menuBtn.is(':visible'); isMobile = $menuBtn.is(':visible')
isMenuShow = false; isMenuShow = false
isSubmenuShow = false; isSubmenuShow = false
function getNightMode () { function getNightMode () {
var nightMode = false; var nightMode = false
try { try {
if (parseInt(Stun.utils.Cookies().get(NIGHT_MODE_COOKIES_KEY))) { if (parseInt(Stun.utils.Cookies().get(NIGHT_MODE_COOKIES_KEY))) {
nightMode = true; nightMode = true
} }
} catch (err) {} } catch (err) {
return nightMode; /* empty */
}
return nightMode
} }
if (CONFIG.nightMode && CONFIG.nightMode.enable) { if (CONFIG.nightMode && CONFIG.nightMode.enable) {
var isNightMode = false; var isNightMode = false
var NIGHT_MODE_COOKIES_KEY = 'night_mode'; var NIGHT_MODE_COOKIES_KEY = 'night_mode'
$nightMode = $('.mode'); $nightMode = $('.mode')
isNightModeFocus = true; isNightModeFocus = true
if (getNightMode()) { if (getNightMode()) {
$nightMode.addClass('mode--checked'); $nightMode.addClass('mode--checked')
$nightMode.addClass('mode--focus'); $nightMode.addClass('mode--focus')
$('html').addClass('nightmode'); $('html').addClass('nightmode')
isNightMode = true; isNightMode = true
} else { } else {
isNightMode = false; isNightMode = false
} }
$('.mode').on('click', function (e) { $('.mode').on('click', function (e) {
e.stopPropagation(); e.stopPropagation()
isNightMode = !isNightMode; isNightMode = !isNightMode
isNightModeFocus = true; isNightModeFocus = true
Stun.utils.Cookies().set(NIGHT_MODE_COOKIES_KEY, isNightMode ? 1 : 0); Stun.utils.Cookies().set(NIGHT_MODE_COOKIES_KEY, isNightMode ? 1 : 0)
$nightMode.toggleClass('mode--checked'); $nightMode.toggleClass('mode--checked')
$nightMode.addClass('mode--focus'); $nightMode.addClass('mode--focus')
$('html').toggleClass('nightmode'); $('html').toggleClass('nightmode')
}); })
} }
$menuBtn.on('click', function (e) { $menuBtn.on('click', function (e) {
e.stopPropagation(); e.stopPropagation()
if (isMobile && isMenuShow && isSubmenuShow) { if (isMobile && isMenuShow && isSubmenuShow) {
resetMenuHeight(); resetMenuHeight()
isSubmenuShow = false; isSubmenuShow = false
} }
if (!isMenuShow) { if (!isMenuShow) {
isMenuShow = true; isMenuShow = true
} else { } else {
isMenuShow = false; isMenuShow = false
} }
$menu.velocity('stop').velocity( $menu.velocity('stop').velocity(
{ {
...@@ -120,91 +122,91 @@ $(document).ready(function () { ...@@ -120,91 +122,91 @@ $(document).ready(function () {
duration: isMenuShow ? 200 : 0, duration: isMenuShow ? 200 : 0,
display: isMenuShow ? 'block' : 'none' display: isMenuShow ? 'block' : 'none'
} }
); )
}); })
// Whether to allow events to bubble in the menu. // Whether to allow events to bubble in the menu.
var isBubbleInMenu = false; var isBubbleInMenu = false
$('.header-nav-submenu-item').on('click', function () { $('.header-nav-submenu-item').on('click', function () {
isBubbleInMenu = true; isBubbleInMenu = true
}); })
$menuItem.on('click', function (e) { $menuItem.on('click', function (e) {
if (!isMobile) { if (!isMobile) {
return; return
} }
var $submenu = $(this).find('.header-nav-submenu'); var $submenu = $(this).find('.header-nav-submenu')
if (!$submenu.length) { if (!$submenu.length) {
return; return
} }
if (!isBubbleInMenu) { if (!isBubbleInMenu) {
e.stopPropagation(); e.stopPropagation()
} else { } else {
isBubbleInMenu = false; isBubbleInMenu = false
} }
var menuItemHeight = $menuItem.outerHeight(); var menuItemHeight = $menuItem.outerHeight()
var submenuHeight = var submenuHeight =
menuItemHeight + Math.floor($submenu.outerHeight()) * $submenu.length; menuItemHeight + Math.floor($submenu.outerHeight()) * $submenu.length
var menuShowHeight = 0; var menuShowHeight = 0
if ($(this).outerHeight() > menuItemHeight) { if ($(this).outerHeight() > menuItemHeight) {
isSubmenuShow = false; isSubmenuShow = false
menuShowHeight = menuItemHeight; menuShowHeight = menuItemHeight
} else { } else {
isSubmenuShow = true; isSubmenuShow = true
menuShowHeight = submenuHeight; menuShowHeight = submenuHeight
} }
$submenu.css({ display: 'block', opacity: 1 }); $submenu.css({ display: 'block', opacity: 1 })
// Accordion effect. // Accordion effect.
$(this) $(this)
.velocity('stop') .velocity('stop')
.velocity({ height: menuShowHeight }, { duration: 300 }) .velocity({ height: menuShowHeight }, { duration: 300 })
.siblings() .siblings()
.velocity({ height: menuItemHeight }, { duration: 300 }); .velocity({ height: menuItemHeight }, { duration: 300 })
}); })
$menuItem.on('mouseenter', function () { $menuItem.on('mouseenter', function () {
var $submenu = $(this).find('.header-nav-submenu'); var $submenu = $(this).find('.header-nav-submenu')
if (!$submenu.length) { if (!$submenu.length) {
return; return
} }
if (!$submenu.is(':visible')) { if (!$submenu.is(':visible')) {
if (isMobile) { if (isMobile) {
$submenu.css({ display: 'block', opacity: 1 }); $submenu.css({ display: 'block', opacity: 1 })
} else { } else {
$submenu.removeClass('hide--force'); $submenu.removeClass('hide--force')
$submenu $submenu
.velocity('stop') .velocity('stop')
.velocity('transition.slideUpIn', { duration: 200 }); .velocity('transition.slideUpIn', { duration: 200 })
} }
} }
}); })
$menuItem.on('mouseleave', function () { $menuItem.on('mouseleave', function () {
var $submenu = $(this).find('.header-nav-submenu'); var $submenu = $(this).find('.header-nav-submenu')
if (!$submenu.length) { if (!$submenu.length) {
return; return
} }
if (!isMobile) { if (!isMobile) {
$submenu.addClass('hide--force'); $submenu.addClass('hide--force')
isSubmenuShow = false; isSubmenuShow = false
} }
}); })
}; }
Stun.utils.pjaxReloadScrollIcon = function () { Stun.utils.pjaxReloadScrollIcon = function () {
if (CONFIG.header && CONFIG.header.scrollDownIcon) { if (CONFIG.header && CONFIG.header.scrollDownIcon) {
$('.header-banner-arrow').on('click', function (e) { $('.header-banner-arrow').on('click', function (e) {
e.stopPropagation(); e.stopPropagation()
$('#container').velocity('scroll', { $('#container').velocity('scroll', {
offset: $('#header').outerHeight() offset: $('#header').outerHeight()
}); })
}); })
} }
}; }
// Initializaiton // Initializaiton
Stun.utils.pjaxReloadHeader(); Stun.utils.pjaxReloadHeader()
Stun.utils.pjaxReloadScrollIcon(); Stun.utils.pjaxReloadScrollIcon()
}); })
$(document).ready(function () { $(document).ready(function () {
var isHeaderEnable = CONFIG.header && CONFIG.header.enable; var isHeaderEnable = CONFIG.header && CONFIG.header.enable
var isShowHeaderOnPost = isHeaderEnable && CONFIG.header.showOnPost; var isShowHeaderOnPost = isHeaderEnable && CONFIG.header.showOnPost
// The previous distance from the page to the top. // The previous distance from the page to the top.
var prevScrollTop = 0; var prevScrollTop = 0
var isNavFix = false; var isNavFix = false
var isAnimation = true; var isAnimation = true
function headerNavScroll () { function headerNavScroll () {
var isPostPage = !!$('#is-post').length; var isPostPage = !!$('#is-post').length
var isNoHeader = !isHeaderEnable || (isPostPage && !isShowHeaderOnPost); var isNoHeader = !isHeaderEnable || (isPostPage && !isShowHeaderOnPost)
var $headerNav = $('.header-nav'); var $headerNav = $('.header-nav')
var scrollTop = Math.floor($(window).scrollTop()); var scrollTop = Math.floor($(window).scrollTop())
var delta = Math.floor(scrollTop - prevScrollTop); var delta = Math.floor(scrollTop - prevScrollTop)
if (scrollTop === 0) { if (scrollTop === 0) {
if (isNoHeader) { if (isNoHeader) {
setTimeout(function () { setTimeout(function () {
$headerNav.addClass('slider--clear'); $headerNav.addClass('slider--clear')
isAnimation = false; isAnimation = false
}, 200); }, 200)
} }
$headerNav.removeClass('header-nav--sticky'); $headerNav.removeClass('header-nav--sticky')
$headerNav.removeClass('slider--up'); $headerNav.removeClass('slider--up')
$headerNav.addClass('slider--down'); $headerNav.addClass('slider--down')
} else { } else {
if (isNoHeader && scrollTop < $headerNav.height()) { if (isNoHeader && scrollTop < $headerNav.height()) {
return false; return false
} }
var MIN_SCROLL_TO_CHANGE_NAV = 5; var MIN_SCROLL_TO_CHANGE_NAV = 5
// Make the state of nav bar not change due to tiny scrolling. // Make the state of nav bar not change due to tiny scrolling.
if (Math.abs(delta) > MIN_SCROLL_TO_CHANGE_NAV) { if (Math.abs(delta) > MIN_SCROLL_TO_CHANGE_NAV) {
if (isNoHeader) { if (isNoHeader) {
if (!isAnimation) { if (!isAnimation) {
isAnimation = true; isAnimation = true
} else { } else {
$headerNav.removeClass('slider--clear'); $headerNav.removeClass('slider--clear')
} }
} }
if (!isNavFix) { if (!isNavFix) {
isNavFix = true; isNavFix = true
} else { } else {
$headerNav.addClass('header-nav--sticky'); $headerNav.addClass('header-nav--sticky')
} }
if (delta > 0) { if (delta > 0) {
$headerNav.removeClass('slider--down'); $headerNav.removeClass('slider--down')
$headerNav.addClass('slider--up'); $headerNav.addClass('slider--up')
} else { } else {
$headerNav.removeClass('slider--up'); $headerNav.removeClass('slider--up')
$headerNav.addClass('slider--down'); $headerNav.addClass('slider--down')
} }
} else { } else {
$headerNav.addClass('header-nav--sticky'); $headerNav.addClass('header-nav--sticky')
} }
} }
prevScrollTop = scrollTop; prevScrollTop = scrollTop
} }
var isBack2topEnable = CONFIG.back2top && CONFIG.back2top.enable; var isBack2topEnable = CONFIG.back2top && CONFIG.back2top.enable
var isBack2topShow = false; var isBack2topShow = false
// Back the page to top. // Back the page to top.
function back2top () { function back2top () {
var $back2top = $('#back2top'); var $back2top = $('#back2top')
var scrollTop = $(window).scrollTop(); var scrollTop = $(window).scrollTop()
if (scrollTop !== 0) { if (scrollTop !== 0) {
if (!isBack2topShow) { if (!isBack2topShow) {
$back2top.addClass('back2top--show'); $back2top.addClass('back2top--show')
$back2top.removeClass('back2top--hide'); $back2top.removeClass('back2top--hide')
isBack2topShow = true; isBack2topShow = true
} }
} else { } else {
$back2top.addClass('back2top--hide'); $back2top.addClass('back2top--hide')
$back2top.removeClass('back2top--show'); $back2top.removeClass('back2top--show')
isBack2topShow = false; isBack2topShow = false
} }
} }
if (isBack2topEnable) { if (isBack2topEnable) {
// Initializaiton // Initializaiton
back2top(); back2top()
$('#back2top').on('click', function () { $('#back2top').on('click', function () {
$('body') $('body')
.velocity('stop') .velocity('stop')
.velocity('scroll'); .velocity('scroll')
}); })
} }
// Initializaiton // Initializaiton
headerNavScroll(); headerNavScroll()
$(window).on( $(window).on(
'scroll', 'scroll',
Stun.utils.throttle(function () { Stun.utils.throttle(function () {
headerNavScroll(); headerNavScroll()
if (isBack2topEnable) { if (isBack2topEnable) {
back2top(); back2top()
} }
}, 100) }, 100)
); )
}); })
$(document).ready(function () { $(document).ready(function () {
var tocDepth = (CONFIG.sidebar && CONFIG.sidebar.tocMaxDepth) || 4; var tocDepth = (CONFIG.sidebar && CONFIG.sidebar.tocMaxDepth) || 4
// Optimize selector by theme config. // Optimize selector by theme config.
var HEADING_SELECTOR = 'h1,h2,h3,h4,h5,h6,' var HEADING_SELECTOR = 'h1,h2,h3,h4,h5,h6,'
.slice(0, tocDepth * 3) .slice(0, tocDepth * 3)
.slice(0, -1); .slice(0, -1)
function initTocDisplay () { function initTocDisplay () {
if ($('.post-body').find(HEADING_SELECTOR)[0]) { if ($('.post-body').find(HEADING_SELECTOR)[0]) {
return; return
} }
$('.sidebar-nav').addClass('hide'); $('.sidebar-nav').addClass('hide')
$('.sidebar-toc').addClass('hide'); $('.sidebar-toc').addClass('hide')
$('.sidebar-ov').removeClass('hide'); $('.sidebar-ov').removeClass('hide')
} }
// The heading that reached the top currently. // The heading that reached the top currently.
var currHeading = null; var currHeading = null
// The heading that reached the top last time. // The heading that reached the top last time.
var lastHeading = null; var lastHeading = null
var isRemovedTocClass = false; var isRemovedTocClass = false
// Automatically expand items in the article directory // Automatically expand items in the article directory
// based on the scrolling of heading in the article. // based on the scrolling of heading in the article.
function autoSpreadToc () { function autoSpreadToc () {
var $postBody = $('.post-body'); var $postBody = $('.post-body')
var $allTocItem = $('.sidebar-toc li'); var $allTocItem = $('.sidebar-toc li')
var $headings = $postBody.find(HEADING_SELECTOR); var $headings = $postBody.find(HEADING_SELECTOR)
var $firsetChild = $headings.first(); var $firsetChild = $headings.first()
$headings.each(function () { $headings.each(function () {
var headingTop = this.getBoundingClientRect().top; var headingTop = this.getBoundingClientRect().top
// The minimum distance from the top of the browser // The minimum distance from the top of the browser
// when heading is marked as active in toc. // when heading is marked as active in toc.
var MIN_HEIGHT_TO_TOP = 5; var MIN_HEIGHT_TO_TOP = 5
if (headingTop <= MIN_HEIGHT_TO_TOP) { if (headingTop <= MIN_HEIGHT_TO_TOP) {
currHeading = this.getAttribute('id'); currHeading = this.getAttribute('id')
} }
}); })
// All heading are not to the top. // All heading are not to the top.
if ( if (
...@@ -47,38 +47,38 @@ $(document).ready(function () { ...@@ -47,38 +47,38 @@ $(document).ready(function () {
$firsetChild.offset().top - $(window).scrollTop() > 0 $firsetChild.offset().top - $(window).scrollTop() > 0
) { ) {
if (!isRemovedTocClass) { if (!isRemovedTocClass) {
$allTocItem.removeClass('active current'); $allTocItem.removeClass('active current')
isRemovedTocClass = true; isRemovedTocClass = true
} }
return; return
} }
if (currHeading !== lastHeading) { if (currHeading !== lastHeading) {
var $targetLink = $('.sidebar-toc a[href="#' + currHeading + '"]'); var $targetLink = $('.sidebar-toc a[href="#' + currHeading + '"]')
$allTocItem.removeClass('active current'); $allTocItem.removeClass('active current')
$targetLink.parents('li').addClass('active'); $targetLink.parents('li').addClass('active')
$targetLink.parent().addClass('current'); $targetLink.parent().addClass('current')
lastHeading = currHeading; lastHeading = currHeading
isRemovedTocClass = false; isRemovedTocClass = false
} }
} }
// Whether toc needs scrolling. // Whether toc needs scrolling.
var isTocScroll = false; var isTocScroll = false
// Scroll the post toc to the middle. // Scroll the post toc to the middle.
function scrollTocToMiddle () { function scrollTocToMiddle () {
var $tocWrapHeight = $('.sidebar-toc').height(); var $tocWrapHeight = $('.sidebar-toc').height()
var $tocHeight = $('.sidebar-toc > div').height(); var $tocHeight = $('.sidebar-toc > div').height()
if ($tocHeight <= $tocWrapHeight) { if ($tocHeight <= $tocWrapHeight) {
return; return
} }
var $tocWrap = $('.sidebar-toc'); var $tocWrap = $('.sidebar-toc')
var $currTocItem = $('.sidebar-toc .current a'); var $currTocItem = $('.sidebar-toc .current a')
if ($currTocItem[0] && $tocWrap[0]) { if ($currTocItem[0] && $tocWrap[0]) {
var tocTop = $currTocItem.offset().top - $tocWrap.offset().top; var tocTop = $currTocItem.offset().top - $tocWrap.offset().top
isTocScroll = tocTop > $tocWrapHeight || tocTop < 0; isTocScroll = tocTop > $tocWrapHeight || tocTop < 0
} }
if (isTocScroll) { if (isTocScroll) {
...@@ -87,27 +87,27 @@ $(document).ready(function () { ...@@ -87,27 +87,27 @@ $(document).ready(function () {
offset: -$tocWrapHeight / 2, offset: -$tocWrapHeight / 2,
duration: 500, duration: 500,
easing: 'easeOutQuart' easing: 'easeOutQuart'
}); })
} }
} }
// Distance from sidebar to top. // Distance from sidebar to top.
var sidebarToTop = 0; var sidebarToTop = 0
if (CONFIG.sidebar && CONFIG.sidebar.offsetTop) { if (CONFIG.sidebar && CONFIG.sidebar.offsetTop) {
sidebarToTop = parseInt(CONFIG.sidebar.offsetTop); sidebarToTop = parseInt(CONFIG.sidebar.offsetTop)
} }
// Sticky the sidebar when it arrived the top. // Sticky the sidebar when it arrived the top.
function sidebarSticky () { function sidebarSticky () {
var $sidebar = $('#sidebar'); var $sidebar = $('#sidebar')
var targetY = document var targetY = document
.getElementById('content-wrap') .getElementById('content-wrap')
.getBoundingClientRect().top; .getBoundingClientRect().top
if (targetY < sidebarToTop) { if (targetY < sidebarToTop) {
$sidebar.addClass('sidebar--sticky'); $sidebar.addClass('sidebar--sticky')
} else { } else {
$sidebar.removeClass('sidebar--sticky'); $sidebar.removeClass('sidebar--sticky')
} }
} }
...@@ -115,108 +115,108 @@ $(document).ready(function () { ...@@ -115,108 +115,108 @@ $(document).ready(function () {
function readProgress () { function readProgress () {
// Not on post page. // Not on post page.
if ($('#is-post').length === 0) { if ($('#is-post').length === 0) {
return; return
} }
var $post = $('.content'); var $post = $('.content')
var postTop = $post.offset().top; var postTop = $post.offset().top
var postEndTop = 0; var postEndTop = 0
var postEndHeight = 0; var postEndHeight = 0
var postReadingHeight = 0; var postReadingHeight = 0
var isEnablePostEnd = false; var isEnablePostEnd = false
var percent = 0; var percent = 0
if (CONFIG.postWidget && CONFIG.postWidget.endText) { if (CONFIG.postWidget && CONFIG.postWidget.endText) {
isEnablePostEnd = true; isEnablePostEnd = true
} }
if (isEnablePostEnd) { if (isEnablePostEnd) {
postEndTop = $('.post-ending').offset().top; postEndTop = $('.post-ending').offset().top
postEndHeight = $('.post-ending').outerHeight(); postEndHeight = $('.post-ending').outerHeight()
postReadingHeight = postEndTop - postTop + postEndHeight; postReadingHeight = postEndTop - postTop + postEndHeight
} else { } else {
postEndTop = $('.post-footer').offset().top; postEndTop = $('.post-footer').offset().top
postReadingHeight = postEndTop - postTop; postReadingHeight = postEndTop - postTop
} }
var windowHeight = $(window).height(); var windowHeight = $(window).height()
var postScrollTop = 0; var postScrollTop = 0
if ($post.length !== 0) { if ($post.length !== 0) {
postScrollTop = postScrollTop =
parseInt($post[0].getBoundingClientRect().top * -1) + windowHeight; parseInt($post[0].getBoundingClientRect().top * -1) + windowHeight
} }
var percentNum = Number($('.sidebar-reading-info__num').text()); var percentNum = Number($('.sidebar-reading-info__num').text())
postReadingHeight = parseInt(Math.abs(postReadingHeight)); postReadingHeight = parseInt(Math.abs(postReadingHeight))
percent = parseInt((postScrollTop / postReadingHeight) * 100); percent = parseInt((postScrollTop / postReadingHeight) * 100)
percent = percent > 100 ? 100 : percent < 0 ? 0 : percent; percent = percent > 100 ? 100 : percent < 0 ? 0 : percent
// Has reached the maximum or minimum // Has reached the maximum or minimum
if ( if (
(percent === 0 && percentNum === 0) || (percent === 0 && percentNum === 0) ||
(percent === 100 && percentNum === 100) (percent === 100 && percentNum === 100)
) { ) {
return; return
} }
$('.sidebar-reading-info__num').text(percent); $('.sidebar-reading-info__num').text(percent)
$('.sidebar-reading-line').css( $('.sidebar-reading-line').css(
'transform', 'transform',
'translateX(' + (percent - 100) + '%)' 'translateX(' + (percent - 100) + '%)'
); )
} }
// Initial run // Initial run
autoSpreadToc(); autoSpreadToc()
sidebarSticky(); sidebarSticky()
scrollTocToMiddle(); scrollTocToMiddle()
readProgress(); readProgress()
$(window).on('scroll', function () { $(window).on('scroll', function () {
sidebarSticky(); sidebarSticky()
}); })
$(window).on( $(window).on(
'scroll', 'scroll',
Stun.utils.throttle(function () { Stun.utils.throttle(function () {
autoSpreadToc(); autoSpreadToc()
scrollTocToMiddle(); scrollTocToMiddle()
readProgress(); readProgress()
}, 150) }, 150)
); )
Stun.utils.pjaxReloadSidebar = function () { Stun.utils.pjaxReloadSidebar = function () {
var $navToc = $('.sidebar-nav-toc'); var $navToc = $('.sidebar-nav-toc')
var $navOv = $('.sidebar-nav-ov'); var $navOv = $('.sidebar-nav-ov')
var $tocWrap = $('.sidebar-toc'); var $tocWrap = $('.sidebar-toc')
var $overview = $('.sidebar-ov'); var $overview = $('.sidebar-ov')
$navToc.on('click', function (e) { $navToc.on('click', function (e) {
e.stopPropagation(); e.stopPropagation()
if ($(this).hasClass('current')) { if ($(this).hasClass('current')) {
return; return
} }
$navToc.addClass('current'); $navToc.addClass('current')
$navOv.removeClass('current'); $navOv.removeClass('current')
$tocWrap.css('display', 'block'); $tocWrap.css('display', 'block')
$tocWrap.velocity('stop').velocity('fadeIn'); $tocWrap.velocity('stop').velocity('fadeIn')
$overview.css('display', 'none'); $overview.css('display', 'none')
$overview.velocity('stop').velocity('fadeOut'); $overview.velocity('stop').velocity('fadeOut')
}); })
$navOv.on('click', function (e) { $navOv.on('click', function (e) {
e.stopPropagation(); e.stopPropagation()
if ($(this).hasClass('current')) { if ($(this).hasClass('current')) {
return; return
} }
$navOv.addClass('current'); $navOv.addClass('current')
$navToc.removeClass('current'); $navToc.removeClass('current')
$tocWrap.css('display', 'none'); $tocWrap.css('display', 'none')
$tocWrap.velocity('stop').velocity('fadeOut'); $tocWrap.velocity('stop').velocity('fadeOut')
$overview.css('display', 'block'); $overview.css('display', 'block')
$overview.velocity('stop').velocity('fadeIn'); $overview.velocity('stop').velocity('fadeIn')
}); })
initTocDisplay(); initTocDisplay()
}; }
// Initialization // Initialization
Stun.utils.pjaxReloadSidebar(); Stun.utils.pjaxReloadSidebar()
}); })
$(document).ready(function () { $(document).ready(function () {
Stun.utils.showThemeInConsole(); Stun.utils.showThemeInConsole()
if (CONFIG.shortcuts && CONFIG.shortcuts.switchPost) { if (CONFIG.shortcuts && CONFIG.shortcuts.switchPost) {
Stun.utils.registerSwitchPost(); Stun.utils.registerSwitchPost()
} }
// Not reload this, because it's changeless. // Not reload this, because it's changeless.
if (CONFIG.externalLink) { if (CONFIG.externalLink) {
Stun.utils.addIconToExternalLink('#footer'); Stun.utils.addIconToExternalLink('#footer')
} }
Stun.utils.pjaxReloadBoot = function () { Stun.utils.pjaxReloadBoot = function () {
if (CONFIG.codeblock) { if (CONFIG.codeblock) {
var codeStyle = CONFIG.codeblock.style; var codeStyle = CONFIG.codeblock.style
if (codeStyle === 'default') { if (codeStyle === 'default') {
this.addCodeHeader(); this.addCodeHeader()
this.addCopyButton(); this.addCopyButton()
} else if (codeStyle === 'carbon') { } else if (codeStyle === 'carbon') {
this.addCodeHeader('carbon'); this.addCodeHeader('carbon')
this.addCopyButton('carbon'); this.addCopyButton('carbon')
} else if (codeStyle === 'simple') { } else if (codeStyle === 'simple') {
this.addCopyButton('simple'); this.addCopyButton('simple')
} }
this.registerCopyEvent(); this.registerCopyEvent()
} }
if (CONFIG.reward) { if (CONFIG.reward) {
this.registerShowReward(); this.registerShowReward()
} }
if (CONFIG.lazyload) { if (CONFIG.lazyload) {
this.lazyLoadImage(); this.lazyLoadImage()
} }
if (CONFIG.galleryWaterfall) { if (CONFIG.galleryWaterfall) {
this.showImageToWaterfall(); this.showImageToWaterfall()
} }
if (CONFIG.externalLink) { if (CONFIG.externalLink) {
var CONTAINER = '.archive, .post-title'; var CONTAINER = '.archive, .post-title'
this.addIconToExternalLink(CONTAINER); this.addIconToExternalLink(CONTAINER)
} }
if (CONFIG.fancybox) { if (CONFIG.fancybox) {
this.wrapImageWithFancyBox(); this.wrapImageWithFancyBox()
} else if (CONFIG.zoomImage) { } else if (CONFIG.zoomImage) {
this.registerZoomImage(); this.registerZoomImage()
} }
}; }
// Initializaiton // Initializaiton
Stun.utils.pjaxReloadBoot(); Stun.utils.pjaxReloadBoot()
}); })
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册