Skip to content

Commit

Permalink
Merge pull request #77 from zkz098/main
Browse files Browse the repository at this point in the history
feat: 为summary添加锁 & refactor: 优化代码结构
  • Loading branch information
zkz098 authored Apr 29, 2023
2 parents 824f60f + d28c48a commit 5b9e41e
Show file tree
Hide file tree
Showing 11 changed files with 86 additions and 76 deletions.
4 changes: 1 addition & 3 deletions docs/develop/basic/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,4 @@ ShokaX的目录结构(仅包含对开发重要的部分)如下:
2. 注意ESM和CJS的区别,对于仅支持CJS的模块应使用`import xxx = require('xxx')`的形式,否则tsc后无法正常生成文件
3. 尽可能少使用`@ts-ignore`,一般除去部分遗留代码和types有问题的代码外不应出现`@ts-ignore`
4. 较通用的 interface 和 declare 应写在`library.ts`中,如果仅在一个文件中出现则写在对应文件中即可
5. 写注释,特别是奇怪的代码(例如魔法数字和神奇的正则)。对于正则表达式应提供一个示例以便理解

剩余部分正在编写
5. 写注释,特别是奇怪的代码(例如魔法数字和神奇的正则)。对于正则表达式应提供一个示例以便理解
Empty file added docs/develop/interface/dom.md
Empty file.
Empty file added docs/develop/interface/index.md
Empty file.
2 changes: 1 addition & 1 deletion layout/_partials/post/post.pug
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ article(itemscope itemtype="http://schema.org/Article" class="post block" lang=t
div(class="gallery" itemscope itemtype="http://schema.org/ImageGallery")
each photo in post.photos
img(data-src=_image_url(photo, post.path) itemprop="contentUrl")
if theme.summary.enable
if theme.summary.enable && page.layout === 'post'
div(class='tabs' id='summary')
div(class="show-btn")
div(class="nav")
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "hexo-theme-shokax",
"version": "0.2.4",
"version": "0.2.5-beta1",
"description": "a hexo theme based on shoka",
"main": "index.js",
"repository": "https://github.com/zkz098/hexo-theme-shokaX",
Expand Down
63 changes: 47 additions & 16 deletions scripts/helpers/summary_ai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,51 @@ function postMessage (path:string, content:string, dbPath:string, startMessage:s
}
}
if (config.mode === 'openai') {
const request = () => {
fetch(`${config.openai.remote}/v1/chat/completions`, {
method: 'POST',
headers: requestHeaders,
body: JSON.stringify(requestBody)
}).then((response) => {
if (!response.ok) {
throw Error('ERROR: Failed to get summary from Openai API')
}
response.json().then((data:object) => {
// @ts-ignore
const summary = data.choices[0].message.content
try {
db[path][dbPath] = summary
} catch (e) {
db ??= {}
db[path] ??= {}
db[path][dbPath] ??= ''
console.log(db[path])
db[path][dbPath] = summary
}
fs.writeFileSync('summary.json', JSON.stringify(db))
if (fs.existsSync('requested.lock')) {
fs.unlinkSync('requested.lock')
}
return summary
})
})
}

const checkTime = () => {
if (fs.existsSync('request.lock')) {
if (fs.existsSync('requested.lock')) {
setTimeout(checkTime, 1000 * 10)
return
}
// Openai API 针对个人用户限制 3 RPM,这里是30s后发送请求
fs.writeFileSync('requested.lock', '')
setTimeout(request, 1000 * 20)
fs.unlinkSync('request.lock') // TODO 需要测试
} else {
fs.writeFileSync('request.lock', '')
request()
}
}
const requestHeaders = {
'Content-Type': 'application/json',
Authorization: `Bearer ${config.openai.apikey}`
Expand All @@ -33,22 +78,8 @@ function postMessage (path:string, content:string, dbPath:string, startMessage:s
messages: [{ role: 'user', content: `${startMessage} ${content}` }],
temperature: 0.7
}
fetch(`${config.openai.remote}/v1/chat/completions`, {
method: 'POST',
headers: requestHeaders,
body: JSON.stringify(requestBody)
}).then((response) => {
if (!response.ok) {
throw Error('ERROR: Failed to get summary from Openai API')
}
response.json().then((data:object) => {
// @ts-ignore
const summary = data.choices[0].message.content
db[path][dbPath] = summary
fs.writeFileSync('summary.json', JSON.stringify(db))
return summary
})
})

checkTime()
} else {
// custom尚未支持
}
Expand Down
2 changes: 1 addition & 1 deletion source/js/_app/global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ const scrollHandle = function (event) {
const scrollPercent = Math.round(Math.min(100 * window.scrollY / contentVisibilityHeight, 100)) + '%'
// 更新回到顶部按钮的文字
if (backToTop.child('span').innerText !== scrollPercent) {
backToTop.child('span').innerText = scrollPercent;
backToTop.child('span').innerText = scrollPercent
}
// 更新百分比进度条的宽度
if ($dom('#sidebar').hasClass('affix') || $dom('#sidebar').hasClass('on')) {
Expand Down
60 changes: 20 additions & 40 deletions source/js/_app/library.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,44 +5,24 @@
*/

declare interface EventTarget {
// 设置或获取元素属性值
attr(type: string, value?: any): any

// 移除元素的指定class
removeClass(className: string): any

// 添加元素的指定class
addClass(className: string): any

// 创建并插入一个新元素
createChild(tag: string, obj: Object, positon?: string | null): HTMLElement

// 获取元素的子元素
child(selector: string): HTMLElement

// 检查元素是否有指定class
hasClass(className: string): boolean

// 设置或获取元素高度
changeOrGetHeight(h?: number | string): number

// 添加或移除元素指定class
toggleClass(className: string, display?: boolean): any

// 设置或获取元素宽度
changeOrGetWidth(w?: number | string): number

// 在指定元素后面插入当前元素
insertAfter(element: HTMLElement): void

// 将对象包装到元素中
wrapObject(obj: Object)

// 查找元素的子元素
find(selector: string): NodeListOf<HTMLElement>

// 设置或获取元素display属性
display(d?: null | string): string | any
createChild(tag: string, obj: Object, positon?: string): HTMLElement;
wrapObject(obj: Object): void;
changeOrGetHeight(h?: number | string): number;
changeOrGetWidth(w?: number | string): number;
getTop(): number;
left(): number;
attr(type: string, value: string): EventTarget;
attr(type: string):string
attr(type:string, value:null):void
insertAfter(element: HTMLElement): void;
display(d?: string): string | EventTarget;
child(selector: string): HTMLElement;
find(selector: string): NodeListOf<HTMLElement>;
_class(type: string, className: string, display?: boolean): void;
addClass(className: string): any;
removeClass(className: string): any;
toggleClass(className: string, display?: boolean): any;
hasClass(className: string): boolean;
}

declare const LOCAL: {
Expand Down Expand Up @@ -196,7 +176,7 @@ Object.assign(HTMLElement.prototype, {
}
return this.getBoundingClientRect().width
},
top: function (): number {
getTop: function (): number {
return this.getBoundingClientRect().top
},
left: function (): number {
Expand Down Expand Up @@ -488,7 +468,7 @@ const pageScroll = function (target: any, offset?: number, complete?: Function)
// 动画缓动函数
easing: 'easeInOutQuad',
// 如果 offset 存在,则滚动到 offset,如果 target 是数字,则滚动到 target,如果 target 是 DOM 元素,则滚动到下述表达式
scrollTop: offset || (typeof target === 'number' ? target : (target ? target.top() + document.documentElement.scrollTop - siteNavHeight : 0)),
scrollTop: offset || (typeof target === 'number' ? target : (target ? target.getTop() + document.documentElement.scrollTop - siteNavHeight : 0)),
// 完成回调函数
complete: function () {
complete && complete()
Expand Down
16 changes: 8 additions & 8 deletions source/js/_app/page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ const postFancybox = function (p) {
$dom.each(p + ' p.gallery', function (element) {
const box = document.createElement('div')
box.className = 'gallery'
box.attr('data-height', element.attr('data-height') || 220)
box.attr('data-height', String(element.attr('data-height') || 220))

box.innerHTML = element.innerHTML.replace(/<br>/g, '')

Expand Down Expand Up @@ -378,7 +378,7 @@ const postBeauty = function () {
}, {
root: null,
threshold: 0.5
});
})
angleDown.forEach(i => {
io.observe(i)
})
Expand Down Expand Up @@ -438,7 +438,7 @@ const tabFormat = function () {
})

box.appendChild(element)
element.attr('data-ready', true)
element.attr('data-ready', String(true))
})
}

Expand Down Expand Up @@ -631,7 +631,7 @@ const domInit = function () {
toolPlayer.player.mini()
})
}

const createIntersectionObserver = function () {
if (!window.IntersectionObserver) return
// waves在视口外时停止动画
Expand All @@ -640,17 +640,17 @@ const domInit = function () {
document.querySelectorAll('.parallax>use').forEach(i => {
i.classList.remove('stop-animation')
})
document.querySelectorAll('#imgs .item').forEach(i=>{
document.querySelectorAll('#imgs .item').forEach(i => {
i.classList.remove('stop-animation')
})
})
} else {
document.querySelectorAll('.parallax>use').forEach(i => {
i.classList.add('stop-animation')
})
// waves不可见时imgs也应该不可见了
document.querySelectorAll('#imgs .item').forEach(i=>{
document.querySelectorAll('#imgs .item').forEach(i => {
i.classList.add('stop-animation')
})
})
}
}, {
root: null,
Expand Down
11 changes: 6 additions & 5 deletions source/js/_app/player.ts
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,7 @@ const mediaPlayer = function (t, config?) {
})
if (t.player.group) {
tab.attr('data-title', t.player.options.rawList[item.group].title)
// @ts-ignore
.attr('data-id', t.player._id)
}
}
Expand Down Expand Up @@ -443,7 +444,7 @@ const mediaPlayer = function (t, config?) {
_id: utils.random(999999),
group: true,
// 加载播放列表
load: function (newList) {
load: (newList) => {
let d = ''

if (newList && newList.length > 0) {
Expand Down Expand Up @@ -504,7 +505,7 @@ const mediaPlayer = function (t, config?) {
})
},
// 根据模式切换当前曲目index
mode: function () {
mode: () => {
const total = playlist.data.length

if (!total || playlist.errnum === total) { return }
Expand All @@ -519,7 +520,7 @@ const mediaPlayer = function (t, config?) {
playlist.index = index
}

const random = function () {
const random = () => {
const p = utils.random(total)
if (playlist.index !== p) {
playlist.index = p
Expand All @@ -545,7 +546,7 @@ const mediaPlayer = function (t, config?) {
this.init()
},
// 直接设置当前曲目index
switch: function (index) {
switch: (index) => {
if (typeof index === 'number' &&
index !== playlist.index &&
playlist.current() &&
Expand Down Expand Up @@ -582,7 +583,7 @@ const mediaPlayer = function (t, config?) {
this.play()
}
},
play: function () {
play: () => {
NOWPLAYING && NOWPLAYING.player.pause()

if (playlist.current().error) {
Expand Down
2 changes: 1 addition & 1 deletion source/js/_app/vue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ Vue.createApp(
}
transition(neko, 1, function () {
setTimeout(c, 210)
}, function() {
}, function () {
neko.display('block')
})
}
Expand Down

0 comments on commit 5b9e41e

Please sign in to comment.