整理lib目录

This commit is contained in:
tangly1024
2024-03-10 13:08:18 +08:00
parent 51743512fa
commit 444e236ca6
55 changed files with 60 additions and 64 deletions

104
lib/plugins/algolia.js Normal file
View File

@@ -0,0 +1,104 @@
import BLOG from '@/blog.config'
import { getPageContentText } from '@/pages/search/[keyword]'
import algoliasearch from 'algoliasearch'
/**
* 生成全文索引
* @param {*} allPages
*/
const generateAlgoliaSearch = async({ allPages, force = false }) => {
allPages?.forEach(p => {
// 判断这篇文章是否需要重新创建索引
if (p && !p.password) {
uploadDataToAlgolia(p)
}
})
}
/**
* 上传数据
* 根据上次修改文章日期和上次更新索引数据判断是否需要更新algolia索引
*/
const uploadDataToAlgolia = async(post) => {
// Connect and authenticate with your Algolia app
const client = algoliasearch(BLOG.ALGOLIA_APP_ID, BLOG.ALGOLIA_ADMIN_APP_KEY)
// Create a new index and add a record
const index = client.initIndex(BLOG.ALGOLIA_INDEX)
if (!post) {
return
}
// 检查是否有索引
let existed
let needUpdateIndex = false
try {
existed = await index.getObject(post.id)
} catch (error) {
// 通常是不存在索引
}
if (!existed || !existed?.lastEditedDate || !existed?.lastIndexDate) {
needUpdateIndex = true
} else {
const lastEditedDate = new Date(post.lastEditedDate)
const lastIndexDate = new Date(existed.lastIndexDate)
if (lastEditedDate.getTime() > lastIndexDate.getTime()) {
needUpdateIndex = true
}
}
// 如果需要更新搜索
if (needUpdateIndex) {
const record = {
objectID: post.id,
title: post.title,
category: post.category,
tags: post.tags,
pageCover: post.pageCover,
slug: post.slug,
summary: post.summary,
lastEditedDate: post.lastEditedDate, // 更新文章时间
lastIndexDate: new Date(), // 更新索引时间
content: truncate(getPageContentText(post, post.blockMap), 9000) // 索引9000个字节因为api限制总请求内容上限1万个字节
}
// console.log('更新Algolia索引', record)
index.saveObject(record).wait().then(r => {
console.log('Algolia索引更新', r)
}).catch(err => {
console.log('Algolia异常', err)
})
}
}
/**
* 限制内容字节数
* @param {*} str
* @param {*} maxBytes
* @returns
*/
function truncate(str, maxBytes) {
let count = 0
let result = ''
for (let i = 0; i < str.length; i++) {
const code = str.charCodeAt(i)
if (code <= 0x7f) {
count += 1
} else if (code <= 0x7ff) {
count += 2
} else if (code <= 0xffff) {
count += 3
} else {
count += 4
}
if (count <= maxBytes) {
result += str[i]
} else {
break
}
}
return result
}
export { uploadDataToAlgolia, generateAlgoliaSearch }

99
lib/plugins/busuanzi.js Normal file
View File

@@ -0,0 +1,99 @@
/* eslint-disable */
let bszCaller, bszTag, scriptTag, ready
let t; let e; let n; let a = !1
let c = []
// 修复Node同构代码的问题
if (typeof document !== 'undefined') {
ready = function (t) {
return a || document.readyState === 'interactive' || document.readyState === 'complete'
? t.call(document)
: c.push(function () {
return t.call(this)
}), this
}, e = function () {
for (let t = 0, e = c.length; t < e; t++) c[t].apply(document)
c = []
}, n = function () {
a || (a = !0, e.call(window),
document.removeEventListener ? document.removeEventListener('DOMContentLoaded', n, !1) : document.attachEvent && (document.detachEvent('onreadystatechange', n), window == window.top && (clearInterval(t), t = null)))
}, document.addEventListener
? document.addEventListener('DOMContentLoaded', n, !1)
: document.attachEvent && (document.attachEvent('onreadystatechange', function () {
/loaded|complete/.test(document.readyState) && n()
}), window == window.top && (t = setInterval(function () {
try {
a || document.documentElement.doScroll('left')
} catch (t) {
return
}
n()
}, 5)))
}
bszCaller = {
fetch: function (t, e) {
const n = 'BusuanziCallback_' + Math.floor(1099511627776 * Math.random())
t = t.replace('=BusuanziCallback', '=' + n)
scriptTag = document.createElement('SCRIPT'), scriptTag.type = 'text/javascript', scriptTag.defer = !0, scriptTag.src = t, scriptTag.referrerPolicy = "no-referrer-when-downgrade", document.getElementsByTagName('HEAD')[0].appendChild(scriptTag)
window[n] = this.evalCall(e)
},
evalCall: function (e) {
return function (t) {
ready(function () {
try {
e(t), scriptTag && scriptTag.parentElement && scriptTag.parentElement.removeChild && scriptTag.parentElement.removeChild(scriptTag)
} catch (t) {
// console.log(t), bszTag.hides()
}
})
}
}
}
const fetch = () => {
bszTag && bszTag.hides()
bszCaller.fetch('//busuanzi.ibruce.info/busuanzi?jsonpCallback=BusuanziCallback', function (t) {
// console.log('不蒜子',t)
bszTag.texts(t), bszTag.shows()
})
}
bszTag = {
bszs: ['site_pv', 'page_pv', 'site_uv'],
texts: function (n) {
this.bszs.map(function (t) {
const e = document.getElementsByClassName('busuanzi_value_' + t)
if(e){
for (var element of e) {
element.innerHTML = n[t]
}
}
})
},
hides: function () {
this.bszs.map(function (t) {
const e = document.getElementsByClassName('busuanzi_container_' + t)
if(e){
for (var element of e){
element.style.display = 'none'
}
}
})
},
shows: function () {
this.bszs.map(function (t) {
const e = document.getElementsByClassName('busuanzi_container_' + t)
if(e){
for(var element of e){
element.style.display = 'inline'
}
}
})
}
}
module.exports = {
fetch
}

17
lib/plugins/gtag.js Normal file
View File

@@ -0,0 +1,17 @@
import BLOG from '@/blog.config'
// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
export const pageview = url => {
window.gtag('config', BLOG.ANALYTICS_GOOGLE_ID, {
page_path: url
})
}
// https://developers.google.com/analytics/devguides/collection/gtagjs/events
export const event = ({ action, category, label, value }) => {
window.gtag('event', action, {
event_category: category,
event_label: label,
value: value
})
}

49
lib/plugins/mailchimp.js Normal file
View File

@@ -0,0 +1,49 @@
import BLOG from '@/blog.config'
/**
* 订阅邮件-服务端接口
* @param {*} email
* @returns
*/
export default function subscribeToMailchimpApi({ email, first_name = '', last_name = '' }) {
const listId = BLOG.MAILCHIMP_LIST_ID // 替换为你的邮件列表 ID
const apiKey = BLOG.MAILCHIMP_API_KEY // 替换为你的 API KEY
if (!email || !listId || !apiKey) {
return {}
}
const data = {
email_address: email,
status: 'subscribed',
merge_fields: {
FNAME: first_name,
LNAME: last_name
}
}
return fetch(`https://us18.api.mailchimp.com/3.0/lists/${listId}/members`, {
method: 'POST',
headers: {
Authorization: `apikey ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
}
/**
* 客户端接口
* @param {*} email
* @param {*} firstName
* @param {*} lastName
* @returns
*/
export async function subscribeToNewsletter(email, firstName, lastName) {
const response = await fetch('/api/subscribe', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ email, first_name: firstName, last_name: lastName })
})
const data = await response.json()
return data
}

1696
lib/plugins/mhchem.js Normal file

File diff suppressed because it is too large Load Diff

16
lib/plugins/wow.js Normal file
View File

@@ -0,0 +1,16 @@
const { loadExternalResource } = require('../utils');
/**
* WOWjs动画结合animate.css使用很方便
* 是data-aos的平替 aos ≈ wowjs + animate
*/
export const loadWowJS = async () => {
await loadExternalResource('/css/wow/animate.css', 'css');
await loadExternalResource('https://cdnjs.cloudflare.com/ajax/libs/wow/1.1.2/wow.min.js', 'js');
// 配合animatecss 实现延时滚动动画和AOS动画相似
const WOW = window.WOW;
console.log('加载WOW动画', WOW)
if (WOW) {
new WOW().init();
}
};