hexo/node_modules/hexo-theme-butterfly/layout/includes/third-party/newest-comments/waline.pug

80 lines
3.0 KiB
Plaintext
Raw Normal View History

2023-09-25 15:58:56 +08:00
script.
window.addEventListener('load', () => {
const changeContent = content => {
if (content === '') return content
content = content.replace(/<img.*?src="(.*?)"?[^\>]+>/ig, '[!{_p("aside.card_newest_comments.image")}]') // replace image link
content = content.replace(/<a[^>]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[!{_p("aside.card_newest_comments.link")}]') // replace url
content = content.replace(/<pre><code>.*?<\/pre>/gi, '[!{_p("aside.card_newest_comments.code")}]') // replace code
content = content.replace(/<[^>]+>/g,"") // remove html tag
if (content.length > 150) {
content = content.substring(0,150) + '...'
}
return content
}
const generateHtml = array => {
let result = ''
if (array.length) {
for (let i = 0; i < array.length; i++) {
result += '<div class=\'aside-list-item\'>'
if (!{theme.newest_comments.avatar}) {
const name = '!{theme.lazyload.enable ? "data-lazy-src" : "src"}'
result += `<a href='${array[i].url}' class='thumbnail'><img ${name}='${array[i].avatar}' alt='${array[i].nick}'></a>`
}
result += `<div class='content'>
<a class='comment' href='${array[i].url}' title='${array[i].content}'>${array[i].content}</a>
<div class='name'><span>${array[i].nick} / </span><time datetime="${array[i].date}">${btf.diffDate(array[i].date, true)}</time></div>
</div></div>`
}
} else {
result += '!{_p("aside.card_newest_comments.zero")}'
}
let $dom = document.querySelector('#card-newest-comments .aside-list')
$dom.innerHTML= result
window.lazyLoadInstance && window.lazyLoadInstance.update()
window.pjax && window.pjax.refresh($dom)
}
const getComment = async () => {
try {
const res = await fetch('!{theme.waline.serverURL}/api/comment?type=recent&count=!{theme.newest_comments.limit}', { method: 'GET' })
const result = await res.json()
const walineArray = result.data.map(e => {
return {
'content': changeContent(e.comment),
'avatar': e.avatar,
'nick': e.nick,
'url': e.url + '#' + e.objectId,
'date': e.time || e.insertedAt
}
})
saveToLocal.set('waline-newest-comments', JSON.stringify(walineArray), !{theme.newest_comments.storage}/(60*24))
generateHtml(walineArray)
} catch (err) {
console.error(err)
const $dom = document.querySelector('#card-newest-comments .aside-list')
$dom.textContent= "!{_p('aside.card_newest_comments.error')}"
}
}
const newestCommentInit = () => {
if (document.querySelector('#card-newest-comments .aside-list')) {
const data = saveToLocal.get('waline-newest-comments')
if (data) {
generateHtml(JSON.parse(data))
} else {
getComment()
}
}
}
newestCommentInit()
document.addEventListener('pjax:complete', newestCommentInit)
})