refactor: enhance the user experience with PJAX

This commit is contained in:
XPoet 2020-12-30 18:11:46 +08:00
parent 141adcb1d3
commit 0abad9b9a8
19 changed files with 444 additions and 362 deletions

View File

@ -49,7 +49,9 @@ social_contact:
links:
github: # your GitHub URL
weixin: # your WeChat QR-Code URL
qq: # your QQ QR-Code URL
weibo: # your WeiBo URL
zhihu: # your ZhiHu URL
twitter: # your twitter URL
facebook: # your facebook URL
email: # your email
@ -193,6 +195,20 @@ copyright_info:
enable: true
# ---------------------------------------------------------------------------------------
# CDN
# ---------------------------------------------------------------------------------------
cdn:
enable: false
# ---------------------------------------------------------------------------------------
# PJAX
# ---------------------------------------------------------------------------------------
pjax:
enable: false
# ---------------------------------------------------------------------------------------
# Footer settings
# ---------------------------------------------------------------------------------------
@ -200,13 +216,6 @@ footer:
since: 2020
# ---------------------------------------------------------------------------------------
# CDN
# ---------------------------------------------------------------------------------------
cdn:
enable: true
# ---------------------------------------------------------------------------------------
# Keep version (Please don't modify)
# ---------------------------------------------------------------------------------------

View File

@ -5,24 +5,36 @@
&& theme.comment.gitalk.github_id
&& theme.comment.gitalk.repository
) { %>
<script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>
<script <%= theme.pjax.enable === true ? 'data-pjax' : '' %>
src="//cdn.jsdelivr.net/npm/gitalk/dist/gitalk.min.js"></script>
<div id="gitalk-container"></div>
<script>
let __gitalk__pathname = decodeURI(location.pathname);
const __gitalk__pathnameLength = __gitalk__pathname.length;
const __gitalk__pathnameMaxLength = 50;
if (__gitalk__pathnameLength > __gitalk__pathnameMaxLength) {
__gitalk__pathname = __gitalk__pathname.substring(0, __gitalk__pathnameMaxLength - 3) + '...';
<script <%= theme.pjax.enable === true ? 'data-pjax' : '' %>>
function loadGitalk() {
let __gitalk__pathname = decodeURI(location.pathname);
const __gitalk__pathnameLength = __gitalk__pathname.length;
const __gitalk__pathnameMaxLength = 50;
if (__gitalk__pathnameLength > __gitalk__pathnameMaxLength) {
__gitalk__pathname = __gitalk__pathname.substring(0, __gitalk__pathnameMaxLength - 3) + '...';
}
new Gitalk({
clientID: '<%= theme.comment.gitalk.client_id %>',
clientSecret: '<%= theme.comment.gitalk.client_secret %>',
repo: '<%= theme.comment.gitalk.repository %>',
owner: '<%= theme.comment.gitalk.github_id %>',
admin: ['<%= theme.comment.gitalk.github_id %>'],
id: __gitalk__pathname,
language: '<%= config.language %>'
}).render('gitalk-container');
}
if ('<%= theme.pjax.enable %>') {
const loadGitalkTimeout = setTimeout(() => {
loadGitalk();
clearTimeout(loadGitalkTimeout);
}, 1000);
} else {
window.addEventListener('DOMContentLoaded', loadGitalk);
}
const gitalk = new Gitalk({
clientID: '<%= theme.comment.gitalk.client_id %>',
clientSecret: '<%= theme.comment.gitalk.client_secret %>',
repo: '<%= theme.comment.gitalk.repository %>',
owner: '<%= theme.comment.gitalk.github_id %>',
admin: ['<%= theme.comment.gitalk.github_id %>'],
id: __gitalk__pathname,
language: '<%= config.language %>'
})
gitalk.render('gitalk-container')
</script>
<% } %>

View File

@ -4,42 +4,55 @@
&& theme.comment.valine.appkey
) { %>
<div class="valine-container">
<script src='//unpkg.com/valine/dist/Valine.min.js'></script>
<script <%= theme.pjax.enable === true ? 'data-pjax' : '' %>
src="//cdn.jsdelivr.net/npm/valine@latest/dist/Valine.min.js"></script>
<div id="vcomments"></div>
<script>
const temp_valine_input_meta = '<%= theme.comment.valine.meta %>';
new Valine({
el: '#vcomments',
appId: '<%= theme.comment.valine.appid %>',
appKey: '<%= theme.comment.valine.appkey %>',
meta: temp_valine_input_meta ? temp_valine_input_meta.split(',') : ['nick', 'mail', 'link'],
avatar: 'wavatar',
enableQQ: true,
placeholder: '<%= theme.comment.valine.placeholder %>',
lang: '<%= config.language %>'.toLowerCase()
});
<script <%= theme.pjax.enable === true ? 'data-pjax' : '' %>>
// Add "Author" identify
const getValineDomTimer = setInterval(() => {
const vcards = document.querySelectorAll('#vcomments .vcards .vcard');
if (vcards.length > 0) {
function loadValine() {
const temp_valine_input_meta = '<%= theme.comment.valine.meta %>';
new Valine({
el: '#vcomments',
appId: '<%= theme.comment.valine.appid %>',
appKey: '<%= theme.comment.valine.appkey %>',
meta: temp_valine_input_meta ? temp_valine_input_meta.split(',') : ['nick', 'mail', 'link'],
avatar: 'wavatar',
enableQQ: true,
placeholder: '<%= theme.comment.valine.placeholder %>',
lang: '<%= config.language %>'.toLowerCase()
});
let author = '<%= theme.base_info.author || config.author %>';
if (author) {
author = author.toLocaleLowerCase();
}
// Add "Author" identify
const getValineDomTimer = setInterval(() => {
const vcards = document.querySelectorAll('#vcomments .vcards .vcard');
if (vcards.length > 0) {
for (let vcard of vcards) {
const vnick = vcard.querySelector('.vhead .vnick');
if (vnick.innerHTML.toLocaleLowerCase() === author) {
vcard.classList.add('author');
let author = '<%= theme.base_info.author || config.author %>';
if (author) {
author = author.toLocaleLowerCase();
}
for (let vcard of vcards) {
const vnick = vcard.querySelector('.vhead .vnick');
if (vnick.innerHTML.toLocaleLowerCase() === author) {
vcard.classList.add('author');
}
}
clearInterval(getValineDomTimer);
} else {
clearInterval(getValineDomTimer);
}
clearInterval(getValineDomTimer);
} else {
clearInterval(getValineDomTimer);
}
}, 2000);
}, 2000);
}
if ('<%= theme.pjax.enable %>') {
const loadValineTimeout = setTimeout(() => {
loadValine();
clearTimeout(loadValineTimeout);
}, 1000);
} else {
window.addEventListener('DOMContentLoaded', loadValine);
}
</script>
</div>
<% } %>

View File

@ -7,8 +7,8 @@
<% } %>
<%= date(new Date(), 'YYYY') %> <i class="fas fa-heart icon-animate"></i> <a href="/"><%= theme.base_info.author || config.author %></a>
</div>
<% if (theme.website_count.busuanzi_count.enable) { %>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<% if (theme.website_count.busuanzi_count.enable === true) { %>
<script async <%= theme.pjax.enable === true ? 'data-pjax' : '' %> src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="website-count info-item">
<% if (theme.website_count.busuanzi_count.site_uv) { %>
<span id="busuanzi_container_site_uv">

View File

@ -0,0 +1,21 @@
<%- __js('js/libs/pjax.min.js') %>
<script>
window.addEventListener('DOMContentLoaded', () => {
const pjax = new Pjax({
selectors: [
'head title',
'.page-container',
'.pjax',
],
cacheBust: false,
currentUrlFullReload: false,
timeout: 0
});
window.addEventListener('pjax:complete', () => {
KEEP.refresh();
pjax.executeScripts(document.querySelectorAll('script[data-pjax], .pjax script'));
});
});
</script>

View File

@ -10,15 +10,20 @@
<%- __js('js/local-search.js') %>
<% } %>
<% if (is_post()) { %>
<%- __js('js/left-side-toggle.js') %>
<% if (theme.code_copy.enable ) { %>
<%- __js('js/code-copy.js') %>
<% } %>
<% if (theme.toc.enable) { %>
<%- __js(['js/libs/anime.min.js', 'js/toc.js']) %>
<% } %>
<% if (theme.code_copy.enable) { %>
<%- __js('js/code-copy.js') %>
<% } %>
<div class="post-scripts <%= theme.pjax.enable === true ? 'pjax' : '' %>">
<% if (theme.toc.enable && is_post()) { %>
<%- __js([
'js/left-side-toggle.js',
'js/libs/anime.min.js',
'js/toc.js'
]) %>
<% } %>
</div>
<% if (theme.pjax.enable === true) { %>
<%- partial('pjax/pjax') %>
<% } %>

View File

@ -1 +1 @@
<%- partial('page') %>
<%- partial('page') %>

View File

@ -5,4 +5,4 @@
<%- body %>
<%- partial('_partial/scripts') %>
</body>
</html>
</html>

View File

@ -12,9 +12,9 @@ const yaml = require('js-yaml');
*/
hexo.extend.helper.register('export_config', function () {
let { config, theme } = this;
let {config, theme} = this;
// ------ export language to js ------
// ------------ export language to js ------------
const languageDir = path.join(__dirname, '../../languages');
let file = fs.readdirSync(languageDir).find(v => v === `${config.language}.yml`);
file = languageDir + '/' + (file ? file : 'en.yml');
@ -24,14 +24,14 @@ hexo.extend.helper.register('export_config', function () {
} catch (e) {
console.log(e);
}
// ---------------------------------
// -----------------------------------------------
let hexo_config = {
hostname: url.parse(config.url).hostname || config.url,
root: config.root
};
if (config.search) {
hexo_config.path = config.search.path;
}
@ -41,6 +41,7 @@ hexo.extend.helper.register('export_config', function () {
style: theme.style,
local_search: theme.local_search,
side_tools: theme.side_tools,
pjax: theme.pjax,
version: theme.version,
}
@ -48,6 +49,6 @@ hexo.extend.helper.register('export_config', function () {
let KEEP = window.KEEP || {};
KEEP.hexo_config = ${JSON.stringify(hexo_config)};
KEEP.theme_config = ${JSON.stringify(theme_config)};
KEEP.language = ${JSON.stringify(languageContent)};
KEEP.language_ago = ${JSON.stringify(languageContent['ago'])};
</script>`;
});

View File

@ -1,4 +1,5 @@
window.addEventListener('DOMContentLoaded', () => {
KEEP.initBack2Top = () => {
KEEP.utils = {
...KEEP.utils,
@ -49,4 +50,5 @@ window.addEventListener('DOMContentLoaded', () => {
KEEP.utils.initBack2Top();
KEEP.utils.initBack2Bottom();
});
}

View File

@ -1,20 +1,21 @@
HTMLElement.prototype.wrap = function (wrapper) {
this.parentNode.insertBefore(wrapper, this);
this.parentNode.removeChild(this);
wrapper.appendChild(this);
};
KEEP.initCodeCopy = () => {
HTMLElement.prototype.wrap = function (wrapper) {
this.parentNode.insertBefore(wrapper, this);
this.parentNode.removeChild(this);
wrapper.appendChild(this);
};
window.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('figure.highlight').forEach(element => {
const box = document.createElement('div');
element.wrap(box);
box.classList.add('highlight-container');
box.insertAdjacentHTML('beforeend', '<div class="copy-btn"><i class="fas fa-copy"></i></div>');
var button = element.parentNode.querySelector('.copy-btn');
const button = element.parentNode.querySelector('.copy-btn');
button.addEventListener('click', event => {
var target = event.currentTarget;
var code = [...target.parentNode.querySelectorAll('.code .line')].map(line => line.innerText).join('\n');
var ta = document.createElement('textarea');
const target = event.currentTarget;
const code = [...target.parentNode.querySelectorAll('.code .line')].map(line => line.innerText).join('\n');
const ta = document.createElement('textarea');
ta.style.top = window.scrollY + 'px'; // Prevent page scrolling
ta.style.position = 'absolute';
ta.style.opacity = '0';
@ -26,7 +27,7 @@ window.addEventListener('DOMContentLoaded', () => {
ta.select();
ta.setSelectionRange(0, code.length);
ta.readOnly = false;
var result = document.execCommand('copy');
const result = document.execCommand('copy');
target.querySelector('i').className = result ? 'fas fa-check' : 'fas fa-times';
ta.blur(); // For iOS
target.blur();
@ -42,4 +43,4 @@ window.addEventListener('DOMContentLoaded', () => {
}, 300);
});
});
});
}

View File

@ -1,4 +1,5 @@
window.addEventListener('DOMContentLoaded', () => {
KEEP.initModeToggle = () => {
KEEP.utils.modeToggle = {
localStorageKey: 'KEEP',
@ -56,7 +57,7 @@ window.addEventListener('DOMContentLoaded', () => {
},
initModeToggleButton() {
this.modeToggleButton_dom.addEventListener('click', () => {
this.modeToggleButton_dom.addEventListener('click', () => {
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
this.setItemUtil('light-mode', 'dark');
} else {
@ -68,4 +69,5 @@ window.addEventListener('DOMContentLoaded', () => {
KEEP.utils.modeToggle.initModeStatus();
KEEP.utils.modeToggle.initModeToggleButton();
});
};

View File

@ -1,4 +1,4 @@
window.addEventListener('DOMContentLoaded', () => {
KEEP.initHeaderShrink = () => {
KEEP.utils.headerShrink = {
pageTemplateDom: document.querySelector('.page-main-content'),
@ -45,4 +45,4 @@ window.addEventListener('DOMContentLoaded', () => {
KEEP.utils.headerShrink.init();
KEEP.utils.headerShrink.initMenuBarButton();
KEEP.utils.headerShrink.initWindowMask();
});
}

View File

@ -1,5 +1,4 @@
window.addEventListener('DOMContentLoaded', () => {
function initLeftSideToggle() {
KEEP.utils.leftSideToggle = {
init() {
@ -34,8 +33,12 @@ window.addEventListener('DOMContentLoaded', () => {
this.leftAsideDom.style.left = isOpen ? '0' : `-${pageAsideWidth}`;
},
}
KEEP.utils.leftSideToggle.init();
KEEP.utils.leftSideToggle.initToggleBarButton();
}
});
if (KEEP.theme_config.pjax && KEEP.utils) {
initLeftSideToggle();
} else {
window.addEventListener('DOMContentLoaded', initLeftSideToggle);
}

1
source/js/libs/pjax.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -1,5 +1,4 @@
/* global CONFIG */
window.addEventListener('DOMContentLoaded', () => {
KEEP.initLocalSearch = () => {
// Search DB path
let searchPath = KEEP.hexo_config.path;
@ -251,7 +250,8 @@ window.addEventListener('DOMContentLoaded', () => {
return data;
});
// Remove loading animation
document.getElementById('no-result').innerHTML = '<i class="fas fa-search fa-5x"></i>';
const noResultDom = document.querySelector('#no-result');
noResultDom && (noResultDom.innerHTML = '<i class="fas fa-search fa-5x"></i>');
});
};
@ -301,4 +301,5 @@ window.addEventListener('DOMContentLoaded', () => {
onPopupClose();
}
});
});
}

View File

@ -7,32 +7,14 @@ window.addEventListener('DOMContentLoaded', () => {
repository: 'https://github.com/XPoet/hexo-theme-keep'
}
// print theme info
KEEP.utils.printThemeInfo();
KEEP.refresh = () => {
KEEP.initUtils();
KEEP.initHeaderShrink();
KEEP.initModeToggle();
KEEP.initLocalSearch();
KEEP.initBack2Top();
KEEP.initCodeCopy();
}
// init scroll
KEEP.utils.registerWindowScroll();
// toggle show tools list
KEEP.utils.toggleShowToolsList();
// global font adjust
KEEP.utils.globalFontAdjust();
KEEP.utils.contentAreaWidthAdjust();
// comment
KEEP.utils.goComment();
// init page height handle
KEEP.utils.initPageHeightHandle();
// init first screen height
KEEP.utils.initFirstScreenHeight();
// big image viewer handle
KEEP.utils.imageViewer();
// set how long age in home article block
KEEP.utils.setHowLongAgoInHome();
KEEP.refresh();
});

View File

@ -1,11 +1,7 @@
window.addEventListener('DOMContentLoaded', () => {
function initTOC() {
KEEP.utils.navItems = document.querySelectorAll('.post-toc-wrap .post-toc li');
KEEP.utils.articleToc_dom = document.querySelector('.article-toc');
KEEP.utils.postTocWrap_dom = document.querySelector('.post-toc-wrap');
if (KEEP.utils.navItems.length > 0) {
KEEP.utils = {
...KEEP.utils,
@ -74,21 +70,15 @@ window.addEventListener('DOMContentLoaded', () => {
KEEP.utils.leftSideToggle.changePageLayoutWhenOpenToggle(KEEP.utils.leftSideToggle.isOpenPageAside);
}
}
KEEP.utils.showPageAsideWhenHasTOC();
KEEP.utils.registerSidebarTOC();
} else {
if (KEEP.utils.postTocWrap_dom) {
KEEP.utils.postTocWrap_dom.innerHTML = '';
KEEP.utils.postTocWrap_dom.style.display = 'none';
}
if (KEEP.utils.articleToc_dom) {
KEEP.utils.articleToc_dom.style.display = 'none';
}
KEEP.utils.pageContainer_dom.removeChild(document.querySelector('.page-aside'));
}
});
}
if (KEEP.theme_config.pjax && KEEP.utils) {
initTOC();
} else {
window.addEventListener('DOMContentLoaded', initTOC);
}

View File

@ -1,238 +1,277 @@
KEEP.utils = {
KEEP.initUtils = () => {
headerProgress_dom: document.querySelector('.header-progress'),
pageTop_dom: document.querySelector('.page-main-content-top'),
firstScreen_dom: document.querySelector('.first-screen-container'),
html_root_dom: document.querySelector('html'),
KEEP.utils = {
innerHeight: window.innerHeight,
prevScrollValue: 0,
defaultFontSize: 0,
html_root_dom: document.querySelector('html'),
pageContainer_dom: document.querySelector('.page-container'),
headerProgress_dom: document.querySelector('.header-progress'),
pageTop_dom: document.querySelector('.page-main-content-top'),
firstScreen_dom: document.querySelector('.first-screen-container'),
// print theme base info
printThemeInfo() {
const themeInfo = `${KEEP.themeInfo.name} v${KEEP.themeInfo.version}`;
console.log(`\n %c ${themeInfo} %c ${KEEP.themeInfo.repository} \n`, `color: #fadfa3; background: #333; padding: 5px 0;`, `background: #fadfa3; padding: 5px 0;`);
const footThemeInfoDom = document.querySelector('.footer .info-container .theme-info a.theme-version');
if (footThemeInfoDom) {
footThemeInfoDom.setAttribute('href', KEEP.themeInfo.repository);
footThemeInfoDom.innerHTML = themeInfo;
}
},
innerHeight: window.innerHeight,
prevScrollValue: 0,
defaultFontSize: 0,
// Scroll Style Handle
styleHandleWhenScroll() {
const scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
const scrollHeight = document.body.scrollHeight || document.documentElement.scrollHeight;
const clientHeight = window.innerHeight || document.documentElement.clientHeight;
const percent = Math.round(scrollTop / (scrollHeight - clientHeight) * 100).toFixed(0);
const ProgressPercent = (scrollTop / (scrollHeight - clientHeight) * 100).toFixed(3);
// print theme base info
printThemeInfo() {
const themeInfo = `${KEEP.themeInfo.name} v${KEEP.themeInfo.version}`;
console.log(`\n %c ${themeInfo} %c ${KEEP.themeInfo.repository} \n`, `color: #fadfa3; background: #333; padding: 5px 0;`, `background: #fadfa3; padding: 5px 0;`);
const footThemeInfoDom = document.querySelector('.footer .info-container .theme-info a.theme-version');
if (footThemeInfoDom) {
footThemeInfoDom.setAttribute('href', KEEP.themeInfo.repository);
footThemeInfoDom.innerHTML = themeInfo;
}
},
if (this.headerProgress_dom) {
this.headerProgress_dom.style.visibility = percent === '0' ? 'hidden' : 'visible';
this.headerProgress_dom.style.width = `${ProgressPercent}%`;
}
// Scroll Style Handle
styleHandleWhenScroll() {
const scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
const scrollHeight = document.body.scrollHeight || document.documentElement.scrollHeight;
const clientHeight = window.innerHeight || document.documentElement.clientHeight;
const percent = Math.round(scrollTop / (scrollHeight - clientHeight) * 100).toFixed(0);
const ProgressPercent = (scrollTop / (scrollHeight - clientHeight) * 100).toFixed(3);
// hide header handle
if (scrollTop > this.prevScrollValue && scrollTop > this.innerHeight) {
this.pageTop_dom.style.transform = 'translateY(-100%)';
} else {
this.pageTop_dom.style.transform = 'translateY(0)';
}
this.prevScrollValue = scrollTop;
},
// register window scroll event
registerWindowScroll() {
window.addEventListener('scroll', () => {
// style handle when scroll
this.styleHandleWhenScroll();
// TOC scroll handle
if (KEEP.theme_config.toc.enable && KEEP.utils.hasOwnProperty('findActiveIndexByTOC')) {
KEEP.utils.findActiveIndexByTOC();
if (this.headerProgress_dom) {
this.headerProgress_dom.style.visibility = percent === '0' ? 'hidden' : 'visible';
this.headerProgress_dom.style.width = `${ProgressPercent}%`;
}
// header shrink
KEEP.utils.headerShrink.headerShrink();
});
},
// hide header handle
if (scrollTop > this.prevScrollValue && scrollTop > this.innerHeight) {
this.pageTop_dom.style.transform = 'translateY(-100%)';
} else {
this.pageTop_dom.style.transform = 'translateY(0)';
}
this.prevScrollValue = scrollTop;
},
// register window scroll event
registerWindowScroll() {
window.addEventListener('scroll', () => {
// style handle when scroll
this.styleHandleWhenScroll();
// TOC scroll handle
if (KEEP.theme_config.toc.enable && KEEP.utils.hasOwnProperty('findActiveIndexByTOC')) {
KEEP.utils.findActiveIndexByTOC();
}
// header shrink
KEEP.utils.headerShrink.headerShrink();
});
},
// toggle show tools list
toggleShowToolsList() {
document.querySelector('.tool-toggle-show').addEventListener('click', () => {
document.querySelector('.side-tools-list').classList.toggle('show');
});
},
// global font adjust
globalFontAdjust() {
const initFontSize = document.defaultView.getComputedStyle(document.body).fontSize;
const fs = Number(initFontSize.substring(0, initFontSize.length - 2));
const setFontSize = (defaultFontSize) => {
this.html_root_dom.style.fontSize = `${fs * (1 + defaultFontSize * 0.05)}px`;
}
document.querySelector('.tool-font-adjust-plus').addEventListener('click', () => {
if (this.defaultFontSize >= 5) return;
this.defaultFontSize++;
setFontSize(this.defaultFontSize);
});
document.querySelector('.tool-font-adjust-minus').addEventListener('click', () => {
if (this.defaultFontSize <= 0) return;
this.defaultFontSize--;
setFontSize(this.defaultFontSize);
});
},
// toggle content area width
contentAreaWidthAdjust() {
const toolExpandDom = document.querySelector('.tool-expand-width');
const headerContentDom = document.querySelector('.header-content');
const mainContentDom = document.querySelector('.main-content');
const iconDom = toolExpandDom.querySelector('i');
const defaultMaxWidth = KEEP.theme_config.style.content_max_width || '1000px';
const expandMaxWidth = '90%';
let headerMaxWidth = defaultMaxWidth;
let isExpand = false;
if (KEEP.theme_config.style.first_screen.enable === true) {
headerMaxWidth = parseInt(defaultMaxWidth) * 1.2 + 'px';
}
toolExpandDom.addEventListener('click', () => {
isExpand = !isExpand;
if (isExpand) {
iconDom.classList.remove('fa-arrows-alt-h');
iconDom.classList.add('fa-compress-arrows-alt');
headerContentDom.style.maxWidth = expandMaxWidth;
mainContentDom.style.maxWidth = expandMaxWidth;
} else {
iconDom.classList.remove('fa-compress-arrows-alt');
iconDom.classList.add('fa-arrows-alt-h');
headerContentDom.style.maxWidth = headerMaxWidth;
mainContentDom.style.maxWidth = defaultMaxWidth;
}
});
},
// go comment
goComment() {
this.goComment_dom = document.querySelector('.go-comment');
if (this.goComment_dom) {
this.goComment_dom.addEventListener('click', () => {
document.querySelector('#comment-anchor').scrollIntoView();
});
}
},
// get dom element height
getElementHeight(selectors) {
const dom = document.querySelector(selectors);
return dom ? dom.getBoundingClientRect().height : 0;
},
// init first screen height
initFirstScreenHeight() {
this.firstScreen_dom && (this.firstScreen_dom.style.height = this.innerHeight + 'px');
},
// init page height handle
initPageHeightHandle() {
if (this.firstScreen_dom) return;
const temp_h1 = this.getElementHeight('.header-progress');
const temp_h2 = this.getElementHeight('.page-main-content-top');
const temp_h3 = this.getElementHeight('.page-main-content-middle');
const temp_h4 = this.getElementHeight('.page-main-content-bottom');
const allDomHeight = temp_h1 + temp_h2 + temp_h3 + temp_h4;
const innerHeight = window.innerHeight;
const pb_dom = document.querySelector('.page-main-content-bottom');
if (allDomHeight < innerHeight) {
pb_dom.style.marginTop = (innerHeight - allDomHeight) + 'px';
}
},
// big image viewer
imageViewer() {
let isBigImage = false;
const showHandle = (dom, isShow) => {
document.body.style.overflow = isShow ? 'hidden' : 'auto';
dom.style.display = isShow ? 'flex' : 'none';
}
const imageViewerDom = document.querySelector('.image-viewer-container');
const targetImg = document.querySelector('.image-viewer-container img');
imageViewerDom && imageViewerDom.addEventListener('click', () => {
isBigImage = false;
showHandle(imageViewerDom, isBigImage);
});
const imgDoms = document.querySelectorAll('.markdown-body img');
if (imgDoms.length) {
imgDoms.forEach(img => {
img.addEventListener('click', () => {
isBigImage = true;
showHandle(imageViewerDom, isBigImage);
targetImg.setAttribute('src', img.getAttribute('src'))
});
});
} else {
this.pageContainer_dom.removeChild(imageViewerDom)
}
},
// set how long ago language
setHowLongAgoLanguage(p1, p2) {
return p2.replace(/%s/g, p1)
},
getHowLongAgo(timestamp) {
let l = KEEP.language_ago;
timestamp /= 1000;
const __Y = Math.floor(timestamp / (60 * 60 * 24 * 30) / 12)
const __M = Math.floor(timestamp / (60 * 60 * 24 * 30))
const __W = Math.floor(timestamp / (60 * 60 * 24) / 7)
const __d = Math.floor(timestamp / (60 * 60 * 24))
const __h = Math.floor(timestamp / (60 * 60) % 24)
const __m = Math.floor(timestamp / 60 % 60)
const __s = Math.floor(timestamp % 60)
if (__Y > 0) {
return this.setHowLongAgoLanguage(__Y, l.year)
} else if (__M > 0) {
return this.setHowLongAgoLanguage(__M, l.month)
} else if (__W > 0) {
return this.setHowLongAgoLanguage(__W, l.week)
} else if (__d > 0) {
return this.setHowLongAgoLanguage(__d, l.day)
} else if (__h > 0) {
return this.setHowLongAgoLanguage(__h, l.hour)
} else if (__m > 0) {
return this.setHowLongAgoLanguage(__m, l.minute)
} else if (__s > 0) {
return this.setHowLongAgoLanguage(__s, l.second)
}
},
setHowLongAgoInHome() {
const post = document.querySelectorAll('.home-article-meta-info .home-article-date');
post && post.forEach(v => {
v.innerHTML = this.getHowLongAgo(Date.now() - new Date(v.dataset.date).getTime())
})
}
}
// print theme info
KEEP.utils.printThemeInfo();
// init scroll
KEEP.utils.registerWindowScroll();
// toggle show tools list
toggleShowToolsList() {
document.querySelector('.tool-toggle-show').addEventListener('click', () => {
document.querySelector('.side-tools-list').classList.toggle('show');
});
},
KEEP.utils.toggleShowToolsList();
// global font adjust
globalFontAdjust() {
const initFontSize = document.defaultView.getComputedStyle(document.body).fontSize;
const fs = Number(initFontSize.substring(0, initFontSize.length - 2));
KEEP.utils.globalFontAdjust();
const setFontSize = (defaultFontSize) => {
this.html_root_dom.style.fontSize = `${fs * (1 + defaultFontSize * 0.05)}px`;
}
document.querySelector('.tool-font-adjust-plus').addEventListener('click', () => {
if (this.defaultFontSize >= 5) return;
this.defaultFontSize++;
setFontSize(this.defaultFontSize);
});
document.querySelector('.tool-font-adjust-minus').addEventListener('click', () => {
if (this.defaultFontSize <= 0) return;
this.defaultFontSize--;
setFontSize(this.defaultFontSize);
});
},
// toggle content area width
contentAreaWidthAdjust() {
const toolExpandDom = document.querySelector('.tool-expand-width');
const headerContentDom = document.querySelector('.header-content');
const mainContentDom = document.querySelector('.main-content');
const iconDom = toolExpandDom.querySelector('i');
const defaultMaxWidth = KEEP.theme_config.style.content_max_width || '1000px';
const expandMaxWidth = '90%';
let headerMaxWidth = defaultMaxWidth;
let isExpand = false;
if (KEEP.theme_config.style.first_screen.enable === true) {
headerMaxWidth = parseInt(defaultMaxWidth) * 1.2 + 'px';
}
toolExpandDom.addEventListener('click', () => {
isExpand = !isExpand;
if (isExpand) {
iconDom.classList.remove('fa-arrows-alt-h');
iconDom.classList.add('fa-compress-arrows-alt');
headerContentDom.style.maxWidth = expandMaxWidth;
mainContentDom.style.maxWidth = expandMaxWidth;
} else {
iconDom.classList.remove('fa-compress-arrows-alt');
iconDom.classList.add('fa-arrows-alt-h');
headerContentDom.style.maxWidth = headerMaxWidth;
mainContentDom.style.maxWidth = defaultMaxWidth;
}
});
},
// adjust content area width
KEEP.utils.contentAreaWidthAdjust();
// go comment
goComment() {
this.goComment_dom = document.querySelector('.go-comment');
if (this.goComment_dom) {
this.goComment_dom.addEventListener('click', () => {
document.querySelector('#comment-anchor').scrollIntoView();
});
}
},
// get dom element height
getElementHeight(selectors) {
const dom = document.querySelector(selectors);
return dom ? dom.getBoundingClientRect().height : 0;
},
// init first screen height
initFirstScreenHeight() {
this.firstScreen_dom && (this.firstScreen_dom.style.height = this.innerHeight + 'px');
},
KEEP.utils.goComment();
// init page height handle
initPageHeightHandle() {
if (this.firstScreen_dom) return;
KEEP.utils.initPageHeightHandle();
const temp_h1 = this.getElementHeight('.header-progress');
const temp_h2 = this.getElementHeight('.page-main-content-top');
const temp_h3 = this.getElementHeight('.page-main-content-middle');
const temp_h4 = this.getElementHeight('.page-main-content-bottom');
const allDomHeight = temp_h1 + temp_h2 + temp_h3 + temp_h4;
const innerHeight = window.innerHeight;
const pb_dom = document.querySelector('.page-main-content-bottom');
if (allDomHeight < innerHeight) {
pb_dom.style.marginTop = (innerHeight - allDomHeight) + 'px';
}
},
// init first screen height
KEEP.utils.initFirstScreenHeight();
// big image viewer
imageViewer() {
let isBigImage = false;
// big image viewer handle
KEEP.utils.imageViewer();
const showHandle = (dom, isShow) => {
document.body.style.overflow = isShow ? 'hidden' : 'auto';
dom.style.display = isShow ? 'flex' : 'none';
}
// set how long age in home article block
KEEP.utils.setHowLongAgoInHome();
const imageViewerDom = document.querySelector('.image-viewer-container');
const targetImg = document.querySelector('.image-viewer-container img');
imageViewerDom && imageViewerDom.addEventListener('click', () => {
isBigImage = false;
showHandle(imageViewerDom, isBigImage);
});
const imgDoms = document.querySelectorAll('.markdown-body img');
imgDoms && imgDoms.forEach(img => {
img.addEventListener('click', () => {
isBigImage = true;
showHandle(imageViewerDom, isBigImage);
targetImg.setAttribute('src', img.getAttribute('src'))
});
});
},
// set how long ago language
setHowLongAgoLanguage(p1, p2) {
return p2.replace(/%s/g, p1)
},
getHowLongAgo(timestamp) {
let l = KEEP.language
timestamp /= 1000;
const __Y = Math.floor(timestamp / (60 * 60 * 24 * 30) / 12)
const __M = Math.floor(timestamp / (60 * 60 * 24 * 30))
const __W = Math.floor(timestamp / (60 * 60 * 24) / 7)
const __d = Math.floor(timestamp / (60 * 60 * 24))
const __h = Math.floor(timestamp / (60 * 60) % 24)
const __m = Math.floor(timestamp / 60 % 60)
const __s = Math.floor(timestamp % 60)
if (__Y > 0) {
return this.setHowLongAgoLanguage(__Y, l.ago.year)
} else if (__M > 0) {
return this.setHowLongAgoLanguage(__M, l.ago.month)
} else if (__W > 0) {
return this.setHowLongAgoLanguage(__W, l.ago.week)
} else if (__d > 0) {
return this.setHowLongAgoLanguage(__d, l.ago.day)
} else if (__h > 0) {
return this.setHowLongAgoLanguage(__h, l.ago.hour)
} else if (__m > 0) {
return this.setHowLongAgoLanguage(__m, l.ago.minute)
} else if (__s > 0) {
return this.setHowLongAgoLanguage(__s, l.ago.second)
}
},
setHowLongAgoInHome() {
const post = document.querySelectorAll('.home-article-meta-info .home-article-date');
post && post.forEach(v => {
v.innerHTML = this.getHowLongAgo(Date.now() - new Date(v.dataset.date).getTime())
})
}
}