mirror of
https://github.com/jerryc127/hexo-theme-butterfly.git
synced 2026-08-08 19:48:42 +08:00
improvement
This commit is contained in:
+133
-156
@@ -54,6 +54,8 @@
|
||||
(() => {
|
||||
const limitConfig = !{ JSON.stringify(page.limit || {}) }
|
||||
|
||||
const escapeHtml = str => String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''')
|
||||
|
||||
const sortDataByDate = data => data.sort((a, b) => new Date(b.date) - new Date(a.date))
|
||||
|
||||
const filterDataByLimit = (data, limit) => {
|
||||
@@ -64,49 +66,47 @@
|
||||
return data.filter(item => new Date(item.date) >= limitDate)
|
||||
}
|
||||
return data
|
||||
};
|
||||
}
|
||||
|
||||
const dateFormatter = new Intl.DateTimeFormat('en-GB', {
|
||||
timeZone: !{JSON.stringify(config.timezone || '')} || Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hour12: false
|
||||
})
|
||||
|
||||
const formatToTimeZone = (date) => {
|
||||
const fullDate = date.length === 10 ? `${date} 00:00:00` : date
|
||||
const visitorTimeZone = '#{config.timezone}' || Intl.DateTimeFormat().resolvedOptions().timeZone
|
||||
const options = {
|
||||
timeZone: visitorTimeZone,
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hour12: false
|
||||
}
|
||||
const [day, month, year, hour, minute, second] = new Intl.DateTimeFormat('en-GB', options)
|
||||
.format(new Date(fullDate))
|
||||
.match(/\d+/g)
|
||||
const [day, month, year, hour, minute, second] = dateFormatter.format(new Date(fullDate)).match(/\d+/g)
|
||||
return `${year}-${month}-${day} ${hour}:${minute}:${second}`
|
||||
}
|
||||
|
||||
const addLazyload = str => {
|
||||
const config = {
|
||||
const lazyConfig = {
|
||||
enable: !{Boolean(enable)},
|
||||
native: !{Boolean(native)},
|
||||
field: '!{field}',
|
||||
placeholder: '!{url_for(placeholder)}',
|
||||
field: !{JSON.stringify(field || '')},
|
||||
placeholder: !{JSON.stringify(url_for(placeholder))},
|
||||
}
|
||||
|
||||
if (!config.enable || config.field !== 'site') return str
|
||||
if (!lazyConfig.enable || lazyConfig.field !== 'site' || str.indexOf('<img') === -1) return str
|
||||
const parser = new DOMParser()
|
||||
const doc = parser.parseFromString(str, 'text/html')
|
||||
const images = doc.querySelectorAll('img')
|
||||
|
||||
images.forEach(img => {
|
||||
if (config.native) {
|
||||
if (lazyConfig.native) {
|
||||
img.setAttribute('loading', 'lazy')
|
||||
} else {
|
||||
const src = img.getAttribute('src')
|
||||
img.setAttribute('data-lazy-src', src)
|
||||
|
||||
if (config.placeholder) {
|
||||
img.setAttribute('src', config.placeholder)
|
||||
if (lazyConfig.placeholder) {
|
||||
img.setAttribute('src', lazyConfig.placeholder)
|
||||
} else {
|
||||
img.removeAttribute('src')
|
||||
}
|
||||
@@ -119,19 +119,18 @@
|
||||
const itemsPerPage = 8
|
||||
let totalPages = 0
|
||||
let data = []
|
||||
let inputEventsAttached = false // Flag to mark if input event listeners have been added
|
||||
|
||||
const renderData = (dataSlice) => {
|
||||
const content = dataSlice.map(item => {
|
||||
const formattedDate = formatToTimeZone(item.date)
|
||||
const tags = item.tags && item.tags.map(tag => `<span class="shuoshuo-tag">${tag}</span>`).join('') || ''
|
||||
const commentButton = item.key && !{commentsJsLoad}
|
||||
const tags = item.tags && item.tags.map(tag => `<span class="shuoshuo-tag">${escapeHtml(tag)}</span>`).join('') || ''
|
||||
const commentButton = item.key && !{commentsJsLoad || false}
|
||||
? `<div class="shuoshuo-comment-btn" onclick="addCommentToShuoshuo(event)">
|
||||
<i class="fa-solid fa-comments"></i>
|
||||
</div>`
|
||||
: ''
|
||||
const commentContainer = item.key
|
||||
? `<div class="shuoshuo-comment no-comment" data-key="${item.key}"></div>`
|
||||
? `<div class="shuoshuo-comment no-comment" data-key="${escapeHtml(item.key)}"></div>`
|
||||
: ''
|
||||
|
||||
return `
|
||||
@@ -139,10 +138,10 @@
|
||||
<div class="container">
|
||||
<div class="shuoshuo-item-header">
|
||||
<div class="shuoshuo-avatar">
|
||||
<img class="no-lightbox" src="${item.avatar || '!{url_for(theme.avatar.img)}'}">
|
||||
<img class="no-lightbox" src="${item.avatar ? escapeHtml(item.avatar) : !{JSON.stringify(url_for(theme.avatar.img))}}">
|
||||
</div>
|
||||
<div class="shuoshuo-info">
|
||||
<div class="shuoshuo-author">${item.author || '!{config.author}'}</div>
|
||||
<div class="shuoshuo-author">${item.author ? escapeHtml(item.author) : !{JSON.stringify(config.author || '')}}</div>
|
||||
<time class="shuoshuo-date" title="${formattedDate}">
|
||||
${btf.diffDate(formattedDate, true)}
|
||||
</time>
|
||||
@@ -165,70 +164,94 @@
|
||||
btf.loadLightbox(document.querySelectorAll('#article-container img:not(.no-lightbox)'))
|
||||
}
|
||||
|
||||
const setupNavEvents = (nav) => {
|
||||
nav.querySelector('.shuoshuo-prev-btn').addEventListener('click', () => {
|
||||
if (currentPage > 1) { currentPage--; renderPage(currentPage) }
|
||||
})
|
||||
nav.querySelector('.shuoshuo-next-btn').addEventListener('click', () => {
|
||||
if (currentPage < totalPages) { currentPage++; renderPage(currentPage) }
|
||||
})
|
||||
|
||||
const input = nav.querySelector('.shuoshuo-page-input')
|
||||
|
||||
input.addEventListener('focus', e => { e.target.placeholder = '' })
|
||||
input.addEventListener('blur', e => {
|
||||
if (!e.target.value.trim()) e.target.placeholder = currentPage
|
||||
})
|
||||
|
||||
input.addEventListener('input', e => {
|
||||
const value = parseInt(e.target.value) || 0
|
||||
let wasInvalid = false
|
||||
|
||||
if (value > totalPages) { e.target.value = totalPages; wasInvalid = true }
|
||||
else if (value < 1 && e.target.value !== '') { e.target.value = 1; wasInvalid = true }
|
||||
|
||||
if (wasInvalid) {
|
||||
e.target.classList.add('invalid')
|
||||
setTimeout(() => e.target.classList.remove('invalid'), 500)
|
||||
}
|
||||
})
|
||||
|
||||
input.addEventListener('keydown', e => {
|
||||
const value = e.target.value + e.key
|
||||
|
||||
if (e.key === 'Enter' || e.key === 'Backspace' || e.key === 'Delete' ||
|
||||
e.key === 'ArrowLeft' || e.key === 'ArrowRight' ||
|
||||
e.key === 'Tab' || e.ctrlKey || e.metaKey) {
|
||||
if (e.key === 'Enter') {
|
||||
const inputValue = e.target.value.trim()
|
||||
const inputPage = inputValue === '' ? currentPage : parseInt(inputValue)
|
||||
if (inputPage >= 1 && inputPage <= totalPages && inputPage !== currentPage) {
|
||||
currentPage = inputPage
|
||||
renderPage(currentPage)
|
||||
} else if (inputValue === '') {
|
||||
renderPage(currentPage)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (!/^\d$/.test(e.key)) {
|
||||
e.preventDefault()
|
||||
return
|
||||
}
|
||||
|
||||
const newValue = parseInt(value) || 0
|
||||
if (newValue > totalPages || (value.length > 1 && newValue === 0)) {
|
||||
e.preventDefault()
|
||||
e.target.classList.add('invalid')
|
||||
setTimeout(() => e.target.classList.remove('invalid'), 500)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const renderNavigation = () => {
|
||||
const container = document.getElementById('article-container')
|
||||
const existingNav = container.nextElementSibling
|
||||
if (existingNav && existingNav.classList.contains('shuoshuo-navigation')) {
|
||||
existingNav.remove()
|
||||
}
|
||||
|
||||
let nav = container.nextElementSibling
|
||||
const pageInfoTemplate = '#{__('pagination.page_info')}'
|
||||
const pageInfoText = pageInfoTemplate
|
||||
.replace(/\$\{current}/g, currentPage)
|
||||
.replace(/\$\{total}/g, totalPages)
|
||||
|
||||
const navHtml = `
|
||||
<div class="shuoshuo-navigation">
|
||||
<button onclick="window.shuoshuoPrevPage()" ${currentPage === 1 ? 'disabled' : ''}><i class="fa-solid fa-chevron-left"></i></button>
|
||||
<span class="shuoshuo-page-info">${pageInfoText}</span>
|
||||
<input type="number" class="shuoshuo-page-input" min="1" max="${totalPages}" placeholder="${currentPage}" onkeydown="window.shuoshuoHandleKeyDown(event)">
|
||||
<button onclick="window.shuoshuoNextPage()" ${currentPage === totalPages ? 'disabled' : ''}><i class="fa-solid fa-chevron-right"></i></button>
|
||||
</div>
|
||||
`
|
||||
container.insertAdjacentHTML('afterend', navHtml)
|
||||
|
||||
// Add input validation event listeners (only once)
|
||||
if (!inputEventsAttached) {
|
||||
setTimeout(() => {
|
||||
const input = document.querySelector('.shuoshuo-page-input')
|
||||
if (input) {
|
||||
// Clear placeholder when clicking the input box
|
||||
input.addEventListener('focus', (event) => {
|
||||
event.target.placeholder = ''
|
||||
})
|
||||
|
||||
// Restore placeholder if no content when losing focus
|
||||
input.addEventListener('blur', (event) => {
|
||||
if (!event.target.value.trim()) {
|
||||
event.target.placeholder = currentPage
|
||||
}
|
||||
})
|
||||
|
||||
input.addEventListener('input', (event) => {
|
||||
const value = parseInt(event.target.value) || 0
|
||||
let wasInvalid = false
|
||||
|
||||
if (value > totalPages) {
|
||||
event.target.value = totalPages
|
||||
wasInvalid = true
|
||||
} else if (value < 1 && event.target.value !== '') {
|
||||
event.target.value = 1
|
||||
wasInvalid = true
|
||||
}
|
||||
|
||||
// If value is corrected, show red and shake effect
|
||||
if (wasInvalid) {
|
||||
event.target.classList.add('invalid')
|
||||
setTimeout(() => {
|
||||
event.target.classList.remove('invalid')
|
||||
}, 500)
|
||||
}
|
||||
})
|
||||
|
||||
inputEventsAttached = true // Mark that event listeners have been added
|
||||
}
|
||||
}, 0)
|
||||
if (!nav || !nav.classList.contains('shuoshuo-navigation')) {
|
||||
nav = document.createElement('div')
|
||||
nav.className = 'shuoshuo-navigation'
|
||||
nav.innerHTML = `
|
||||
<button class="shuoshuo-prev-btn"><i class="fa-solid fa-chevron-left"></i></button>
|
||||
<span class="shuoshuo-page-info"></span>
|
||||
<input type="number" class="shuoshuo-page-input" min="1">
|
||||
<button class="shuoshuo-next-btn"><i class="fa-solid fa-chevron-right"></i></button>
|
||||
`
|
||||
container.insertAdjacentElement('afterend', nav)
|
||||
setupNavEvents(nav)
|
||||
}
|
||||
|
||||
nav.querySelector('.shuoshuo-page-info').textContent = pageInfoText
|
||||
nav.querySelector('.shuoshuo-prev-btn').disabled = currentPage === 1
|
||||
nav.querySelector('.shuoshuo-next-btn').disabled = currentPage === totalPages
|
||||
const input = nav.querySelector('.shuoshuo-page-input')
|
||||
input.max = totalPages
|
||||
input.placeholder = currentPage
|
||||
}
|
||||
|
||||
const renderPage = (page) => {
|
||||
@@ -239,79 +262,14 @@
|
||||
renderNavigation()
|
||||
}
|
||||
|
||||
window.shuoshuoPrevPage = () => {
|
||||
if (currentPage > 1) {
|
||||
currentPage--
|
||||
renderPage(currentPage)
|
||||
}
|
||||
}
|
||||
|
||||
window.shuoshuoNextPage = () => {
|
||||
if (currentPage < totalPages) {
|
||||
currentPage++
|
||||
renderPage(currentPage)
|
||||
}
|
||||
}
|
||||
|
||||
window.shuoshuoGoToPage = (page) => {
|
||||
if (typeof page === 'number') {
|
||||
// Directly jump to the specified page
|
||||
if (page >= 1 && page <= totalPages && page !== currentPage) {
|
||||
currentPage = page
|
||||
renderPage(currentPage)
|
||||
}
|
||||
} else {
|
||||
// Get page from input box
|
||||
const input = document.querySelector('.shuoshuo-page-input')
|
||||
const inputValue = input.value.trim()
|
||||
const inputPage = inputValue === '' ? currentPage : parseInt(inputValue)
|
||||
if (inputPage >= 1 && inputPage <= totalPages && inputPage !== currentPage) {
|
||||
currentPage = inputPage
|
||||
renderPage(currentPage)
|
||||
} else if (inputValue === '') {
|
||||
// If input box is empty, re-render current page (update placeholder)
|
||||
renderPage(currentPage)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
window.shuoshuoHandleKeyDown = (event) => {
|
||||
const input = event.target
|
||||
const value = input.value + event.key
|
||||
|
||||
// Allow delete, arrow keys, backspace, etc.
|
||||
if (event.key === 'Enter' || event.key === 'Backspace' || event.key === 'Delete' ||
|
||||
event.key === 'ArrowLeft' || event.key === 'ArrowRight' ||
|
||||
event.key === 'Tab' || event.ctrlKey || event.metaKey) {
|
||||
if (event.key === 'Enter') {
|
||||
window.shuoshuoGoToPage()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Only allow numbers
|
||||
if (!/^\d$/.test(event.key)) {
|
||||
event.preventDefault()
|
||||
return
|
||||
}
|
||||
|
||||
// Check if the value after input exceeds the range
|
||||
const newValue = parseInt(value) || 0
|
||||
if (newValue > totalPages || (value.length > 1 && newValue === 0)) {
|
||||
event.preventDefault()
|
||||
// Add red and shake effect
|
||||
input.classList.add('invalid')
|
||||
setTimeout(() => {
|
||||
input.classList.remove('invalid')
|
||||
}, 500)
|
||||
}
|
||||
}
|
||||
|
||||
const loadShuoshuo = async () => {
|
||||
const container = document.getElementById('article-container')
|
||||
try {
|
||||
let originData = []
|
||||
if (!{Boolean(page.shuoshuo_url)}) {
|
||||
container.innerHTML = '<div class="shuoshuo-loading"><i class="fa-solid fa-circle-notch fa-spin"></i></div>'
|
||||
const response = await fetch('!{url_for(page.shuoshuo_url)}')
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`)
|
||||
originData = await response.json()
|
||||
} else {
|
||||
const dataElement = document.getElementById('shuoshuo-data')
|
||||
@@ -319,14 +277,33 @@
|
||||
}
|
||||
|
||||
data = filterDataByLimit(sortDataByDate(originData), limitConfig)
|
||||
|
||||
totalPages = Math.ceil(data.length / itemsPerPage)
|
||||
|
||||
if (data.length === 0) {
|
||||
container.innerHTML = '<div class="shuoshuo-empty"></div>'
|
||||
return
|
||||
}
|
||||
|
||||
renderPage(currentPage)
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
container.innerHTML = '<div class="shuoshuo-error"><i class="fa-solid fa-circle-exclamation"></i></div>'
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
window.pjax ? loadShuoshuo() : window.addEventListener('load', loadShuoshuo)
|
||||
})()
|
||||
const pjaxCleanup = () => {
|
||||
const container = document.getElementById('article-container')
|
||||
if (container) {
|
||||
const nav = container.nextElementSibling
|
||||
if (nav && nav.classList.contains('shuoshuo-navigation')) nav.remove()
|
||||
}
|
||||
document.removeEventListener('pjax:send', pjaxCleanup)
|
||||
}
|
||||
|
||||
if (window.pjax) {
|
||||
document.addEventListener('pjax:send', pjaxCleanup)
|
||||
loadShuoshuo()
|
||||
} else {
|
||||
window.addEventListener('load', loadShuoshuo)
|
||||
}
|
||||
})()
|
||||
|
||||
Reference in New Issue
Block a user