breaking change:

1. 部分配置更改

feat:
1. 移除 messenger 聊天插件
2. 更新 fackbook 版本號
3. 增加 香港繁體、日文和韓語
4. 使用的新的複製api 代替舊的
5. 增加 umami 分析
6. 增加 umami 獲取訪問量/訪客數
7. snackbar 增加透明度
8. 文章頁下, nav fixed 下 顯示文章標題

improvement:
1. 代碼優化
2. 修改部分用語
3. 回復之前的相對時間邏輯
4. timeline tag 樣式優化
5. 優化 seo
6. 優化 artalk 的最新評論

fix:
1. tag-hide toggle 圓角問題
2. lazyload 為 false 時,artalk 無法正常加載評論的 bug
3. 修復 gallery 出現抖動的 bug
pull/1564/head^2
Jerry 1 month ago
parent 48212b9610
commit d8a1fa6417

@ -86,7 +86,7 @@ npm i hexo-theme-butterfly
- [x] Share (Sharejs/Addtoany) - [x] Share (Sharejs/Addtoany)
- [X] Comment (Disqus/Disqusjs/Livere/Gitalk/Valine/Waline/Utterances/Facebook Comments/Twikoo/Giscus/Remark42/artalk) - [X] Comment (Disqus/Disqusjs/Livere/Gitalk/Valine/Waline/Utterances/Facebook Comments/Twikoo/Giscus/Remark42/artalk)
- [x] Multiple Comment System Support - [x] Multiple Comment System Support
- [x] Online Chats (Chatra/Tidio/Daovoice/Crisp/messenger) - [x] Online Chats (Chatra/Tidio/Daovoice/Crisp)
- [x] Web analytics - [x] Web analytics
- [x] Google AdSense - [x] Google AdSense
- [x] Webmaster Verification - [x] Webmaster Verification

@ -86,7 +86,7 @@ theme: butterfly
- [x] 多種分享系統Sharejs/Addtoany - [x] 多種分享系統Sharejs/Addtoany
- [X] 多種評論系統Disqus/Disqusjs/Livere/Gitalk/Valine/Waline/Utterances/Facebook Comments/Twikoo/Giscus/Remark42/artalk - [X] 多種評論系統Disqus/Disqusjs/Livere/Gitalk/Valine/Waline/Utterances/Facebook Comments/Twikoo/Giscus/Remark42/artalk
- [x] 支持雙評論部署 - [x] 支持雙評論部署
- [x] 多種在線聊天Chatra/Tidio/Daovoice/Crisp/messenger - [x] 多種在線聊天Chatra/Tidio/Daovoice/Crisp
- [x] 多種分析系統 - [x] 多種分析系統
- [x] 谷歌廣告/手動廣告位置 - [x] 谷歌廣告/手動廣告位置
- [x] 各種站長驗證 - [x] 各種站長驗證

@ -645,7 +645,7 @@ artalk:
# -------------------------------------- # --------------------------------------
chat: chat:
# Choose: chatra/tidio/daovoice/crisp/messenger # Choose: chatra/tidio/daovoice/crisp
# Leave it empty if you don't need chat # Leave it empty if you don't need chat
use: use:
# Chat Button [recommend] # Chat Button [recommend]
@ -670,11 +670,6 @@ daovoice:
crisp: crisp:
website_id: website_id:
# https://developers.facebook.com/docs/messenger-platform/discovery/facebook-chat-plugin/
messenger:
pageID:
lang: zh_TW
# -------------------------------------- # --------------------------------------
# Analysis # Analysis
# -------------------------------------- # --------------------------------------
@ -691,6 +686,20 @@ cloudflare_analytics:
# https://clarity.microsoft.com/ # https://clarity.microsoft.com/
microsoft_clarity: microsoft_clarity:
# https://umami.is/
umami_analytics:
enable: false
# For self-hosted setups, configure the hostname of the Umami instance
serverURL:
website_id:
option:
UV_PV:
site_uv: false
site_pv: false
page_pv: false
# Umami Cloud (API key) / self-hosted Umami (token)
token:
# -------------------------------------- # --------------------------------------
# Advertisement # Advertisement
# -------------------------------------- # --------------------------------------
@ -787,29 +796,29 @@ beautify:
# Specify the field to beautify (site or post) # Specify the field to beautify (site or post)
field: post field: post
# Specify the icon to be used as a prefix for the title, such as '\f0c1' # Specify the icon to be used as a prefix for the title, such as '\f0c1'
title-prefix-icon: title_prefix_icon:
# Specify the color of the title prefix icon, such as '#F47466' # Specify the color of the title prefix icon, such as '#F47466'
title-prefix-icon-color: title_prefix_icon_color:
# Global font settings # Global font settings
# Don't modify the following settings unless you know how they work # Don't modify the following settings unless you know how they work
font: font:
global-font-size: global_font_size:
code-font-size: code_font_size:
font-family: font_family:
code-font-family: code_font_family:
# Font settings for the site title and site subtitle # Font settings for the site title and site subtitle
blog_title_font: blog_title_font:
font_link: font_link:
font-family: font_family:
# The setting of divider icon # The setting of divider icon
hr_icon: hr_icon:
enable: true enable: true
# The unicode value of Font Awesome icon, such as '\3423' # The unicode value of Font Awesome icon, such as '\3423'
icon: icon:
icon-top: icon_top:
# Typewriter Effect # Typewriter Effect
# https://github.com/disjukr/activate-power-mode # https://github.com/disjukr/activate-power-mode

@ -4,11 +4,11 @@ footer:
copy: copy:
success: Copy Successful success: Copy Successful
error: Copy Error error: Copy Failed
noSupport: Browser Not Supported noSupport: Browser Not Supported
page: page:
articles: Articles articles: All Articles
tag: Tag tag: Tag
category: Category category: Category
archives: Archives archives: Archives
@ -29,26 +29,26 @@ post:
author: Author author: Author
link: Link link: Link
copyright_notice: Copyright Notice copyright_notice: Copyright Notice
copyright_content: 'All articles in this blog are licensed under <a href="%s">%s</a> unless stating additionally.' copyright_content: 'All articles on this blog are licensed under <a href="%s">%s</a> unless otherwise stated.'
recommend: Related Articles recommend: Related Articles
edit: Edited on edit: Edit
search: search:
title: Search title: Search
load_data: Loading the Database load_data: Loading Database
input_placeholder: Search for Posts input_placeholder: Search for Posts
algolia_search: algolia_search:
hits_empty: "We didn't find any results for the search: ${query}." hits_empty: 'No results found for: ${query}'
hits_stats: '${hits} results found in ${time} ms' hits_stats: '${hits} results found in ${time} ms'
local_search: local_search:
hits_empty: "We didn't find any results for the search: ${query}" hits_empty: 'No results found for: ${query}'
hits_stats: '${hits} results found' hits_stats: '${hits} articles found'
pagination: pagination:
prev: Previous prev: Previous
next: Next next: Next
comment: Comment comment: Comments
aside: aside:
articles: Articles articles: Articles
@ -58,29 +58,29 @@ aside:
card_categories: Categories card_categories: Categories
card_tags: Tags card_tags: Tags
card_archives: Archives card_archives: Archives
card_recent_post: Recent Post card_recent_post: Recent Posts
card_webinfo: card_webinfo:
headline: Info headline: Website Info
article_name: Article article_name: Article Count
runtime: runtime:
name: Runtime name: Runtime
unit: days unit: days
last_push_date: last_push_date:
name: Last Update name: Last Update
site_wordcount: Total Count site_wordcount: Total Word Count
site_uv_name: UV site_uv_name: Unique Visitors
site_pv_name: PV site_pv_name: Page Views
more_button: View More more_button: View More
card_newest_comments: card_newest_comments:
headline: Latest Comments headline: Latest Comments
loading_text: loading... loading_text: Loading...
error: Unable to retrieve comments, please check the configuration error: Unable to retrieve comments, please check the configuration
zero: No comments zero: No comments
image: image image: Image
link: link link: Link
code: code code: Code
card_toc: Contents card_toc: Contents
card_post_series: Series card_post_series: Post Series
date_suffix: date_suffix:
just: Just now just: Just now
@ -93,21 +93,21 @@ donate: Sponsor
share: Share share: Share
rightside: rightside:
readmode_title: Read Mode readmode_title: Reading Mode
translate_title: Toggle Between Traditional Chinese And Simplified Chinese translate_title: Toggle Between Traditional and Simplified Chinese
night_mode_title: Toggle Between Light And Dark Mode night_mode_title: Toggle Between Light and Dark Mode
back_to_top: Back To Top back_to_top: Back to Top
toc: Table Of Contents toc: Table of Contents
scroll_to_comment: Scroll To Comments scroll_to_comment: Scroll to Comments
setting: Setting setting: Settings
aside: Toggle between Single-column and Double-column aside: Toggle Between Single-column and Double-column
chat: Chat chat: Chat
copy_copyright: copy_copyright:
author: Author author: Author
link: Link link: Link
source: Source source: Source
info: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source. info: Copyright belongs to the author. For commercial use, please contact the author for authorization. For non-commercial use, please indicate the source.
Snackbar: Snackbar:
chs_to_cht: You have switched to Traditional Chinese chs_to_cht: You have switched to Traditional Chinese

@ -4,11 +4,11 @@ footer:
copy: copy:
success: Copy Successful success: Copy Successful
error: Copy Error error: Copy Failed
noSupport: Browser Not Supported noSupport: Browser Not Supported
page: page:
articles: Articles articles: All Articles
tag: Tag tag: Tag
category: Category category: Category
archives: Archives archives: Archives
@ -29,26 +29,26 @@ post:
author: Author author: Author
link: Link link: Link
copyright_notice: Copyright Notice copyright_notice: Copyright Notice
copyright_content: 'All articles in this blog are licensed under <a href="%s">%s</a> unless stating additionally.' copyright_content: 'All articles on this blog are licensed under <a href="%s">%s</a> unless otherwise stated.'
recommend: Related Articles recommend: Related Articles
edit: Edited on edit: Edit
search: search:
title: Search title: Search
load_data: Loading the Database load_data: Loading Database
input_placeholder: Search for Posts input_placeholder: Search for Posts
algolia_search: algolia_search:
hits_empty: "We didn't find any results for the search: ${query}." hits_empty: 'No results found for: ${query}'
hits_stats: '${hits} results found in ${time} ms' hits_stats: '${hits} results found in ${time} ms'
local_search: local_search:
hits_empty: "We didn't find any results for the search: ${query}" hits_empty: 'No results found for: ${query}'
hits_stats: '${hits} results found' hits_stats: '${hits} articles found'
pagination: pagination:
prev: Previous prev: Previous
next: Next next: Next
comment: Comment comment: Comments
aside: aside:
articles: Articles articles: Articles
@ -58,29 +58,29 @@ aside:
card_categories: Categories card_categories: Categories
card_tags: Tags card_tags: Tags
card_archives: Archives card_archives: Archives
card_recent_post: Recent Post card_recent_post: Recent Posts
card_webinfo: card_webinfo:
headline: Info headline: Website Info
article_name: Article article_name: Article Count
runtime: runtime:
name: Runtime name: Runtime
unit: days unit: days
last_push_date: last_push_date:
name: Last Update name: Last Update
site_wordcount: Total Count site_wordcount: Total Word Count
site_uv_name: UV site_uv_name: Unique Visitors
site_pv_name: PV site_pv_name: Page Views
more_button: View More more_button: View More
card_newest_comments: card_newest_comments:
headline: Latest Comments headline: Latest Comments
loading_text: loading... loading_text: Loading...
error: Unable to retrieve comments, please check the configuration error: Unable to retrieve comments, please check the configuration
zero: No comments zero: No comments
image: image image: Image
link: link link: Link
code: code code: Code
card_toc: Contents card_toc: Contents
card_post_series: Series card_post_series: Post Series
date_suffix: date_suffix:
just: Just now just: Just now
@ -93,21 +93,21 @@ donate: Sponsor
share: Share share: Share
rightside: rightside:
readmode_title: Read Mode readmode_title: Reading Mode
translate_title: Toggle Between Traditional Chinese And Simplified Chinese translate_title: Toggle Between Traditional and Simplified Chinese
night_mode_title: Toggle Between Light And Dark Mode night_mode_title: Toggle Between Light and Dark Mode
back_to_top: Back To Top back_to_top: Back to Top
toc: Table Of Contents toc: Table of Contents
scroll_to_comment: Scroll To Comments scroll_to_comment: Scroll to Comments
setting: Setting setting: Settings
aside: Toggle between Single-column and Double-column aside: Toggle Between Single-column and Double-column
chat: Chat chat: Chat
copy_copyright: copy_copyright:
author: Author author: Author
link: Link link: Link
source: Source source: Source
info: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source. info: Copyright belongs to the author. For commercial use, please contact the author for authorization. For non-commercial use, please indicate the source.
Snackbar: Snackbar:
chs_to_cht: You have switched to Traditional Chinese chs_to_cht: You have switched to Traditional Chinese

@ -0,0 +1,121 @@
footer:
framework: フレームワーク
theme: テーマ
copy:
success: コピー成功
error: コピー失敗
noSupport: ブラウザが対応していません
page:
articles: 記事一覧
tag: タグ
category: カテゴリ
archives: アーカイブ
card_post_count: コメント数
no_title: タイトルなし
post:
created: 作成日
updated: 更新日
wordcount: 総文字数
min2read: 読む時間
min2read_unit:
page_pv: 閲覧数
comments: コメント数
copyright:
author: 著者
link: リンク
copyright_notice: 著作権表示
copyright_content: 'このブログのすべての記事は、<a href="%s">%s</a> ライセンスの下で提供されており、特に明記されていない限り、すべての権利を留保します。転載時には出典を明記してください: <a href="%s">%s</a>。'
recommend: 関連記事
edit: 編集
search:
title: 検索
load_data: データベースを読み込んでいます
input_placeholder: 記事を検索
algolia_search:
hits_empty: '${query} の検索結果が見つかりませんでした。'
hits_stats: '${hits} 件の結果が ${time}ms で見つかりました'
local_search:
hits_empty: '${query} の検索結果が見つかりませんでした。'
hits_stats: '${hits} 件の記事が見つかりました'
pagination:
prev: 前へ
next: 次へ
comment: コメント
aside:
articles: 記事
tags: タグ
categories: カテゴリ
card_announcement: お知らせ
card_categories: カテゴリ
card_tags: タグ
card_archives: アーカイブ
card_recent_post: 最近の記事
card_webinfo:
headline: サイト情報
article_name: 記事数
runtime:
name: 稼働時間
unit:
last_push_date:
name: 最終更新日
site_wordcount: 総文字数
site_uv_name: ユーザー数
site_pv_name: ページビュー数
more_button: もっと見る
card_newest_comments:
headline: 最新コメント
loading_text: ローディング中...
error: コメントを取得できませんでした。設定を確認してください。
zero: コメントがありません
image: 画像
link: リンク
code: コード
card_toc: 目次
card_post_series: シリーズ記事
date_suffix:
just: たった今
min: 分前
hour: 時間前
day: 日前
month: ヶ月前
donate: 寄付
share: 共有
rightside:
readmode_title: 読書モード
translate_title: 簡体字と繁体字の切り替え
night_mode_title: ライトモード/ダークモード切り替え
back_to_top: トップに戻る
toc: 目次
scroll_to_comment: コメントへ移動
setting: 設定
aside: シングルカラムとダブルカラムの切り替え
chat: チャット
copy_copyright:
author: 著者
link: リンク
source: ソース
info: 著作権は著者に帰属します。商業的利用の場合は著者に連絡して許可を得てください。非商業的利用の場合は出典を明記してください。
Snackbar:
chs_to_cht: 繁体字に切り替えました
cht_to_chs: 簡体字に切り替えました
day_to_night: ダークモードに切り替えました
night_to_day: ライトモードに切り替えました
loading: ローディング中...
load_more: もっと見る
error404: ページが見つかりません

@ -0,0 +1,121 @@
footer:
framework: 프레임워크
theme: 테마
copy:
success: 복사 성공
error: 복사 실패
noSupport: 브라우저가 지원되지 않음
page:
articles: 모든 글
tag: 태그
category: 카테고리
archives: 아카이브
card_post_count: 댓글 수
no_title: 제목 없음
post:
created: 작성일
updated: 수정일
wordcount: 총 글자 수
min2read: 읽기 시간
min2read_unit:
page_pv: 조회수
comments: 댓글
copyright:
author: 작성자
link: 링크
copyright_notice: 저작권 고지
copyright_content: '이 블로그의 모든 글은 <a href="%s">%s</a> 라이선스를 따르며, 별도로 명시되지 않는 한 모든 권리를 보유합니다. 재배포 시 출처를 명시해 주세요: <a href="%s">%s</a>.'
recommend: 관련 글
edit: 편집
search:
title: 검색
load_data: 데이터베이스 로드 중
input_placeholder: 글 검색
algolia_search:
hits_empty: '${query}에 대한 결과를 찾을 수 없습니다.'
hits_stats: '${hits}개의 결과를 ${time}ms 만에 찾음'
local_search:
hits_empty: '${query}에 대한 결과를 찾을 수 없습니다.'
hits_stats: '${hits}개의 글을 찾음'
pagination:
prev: 이전
next: 다음
comment: 댓글
aside:
articles:
tags: 태그
categories: 카테고리
card_announcement: 공지
card_categories: 카테고리
card_tags: 태그
card_archives: 아카이브
card_recent_post: 최근 글
card_webinfo:
headline: 사이트 정보
article_name: 글 수
runtime:
name: 운영 시간
unit:
last_push_date:
name: 마지막 업데이트
site_wordcount: 총 글자 수
site_uv_name: 방문자 수
site_pv_name: 총 조회수
more_button: 더 보기
card_newest_comments:
headline: 최신 댓글
loading_text: 로딩 중...
error: 댓글을 가져올 수 없습니다. 설정을 확인해 주세요.
zero: 댓글 없음
image: 이미지
link: 링크
code: 코드
card_toc: 목차
card_post_series: 시리즈 글
date_suffix:
just: 방금
min: 분 전
hour: 시간 전
day: 일 전
month: 달 전
donate: 후원
share: 공유
rightside:
readmode_title: 읽기 모드
translate_title: 번체와 간체 전환
night_mode_title: 라이트/다크 모드 전환
back_to_top: 맨 위로
toc: 목차
scroll_to_comment: 댓글로 이동
setting: 설정
aside: 단일/이중 열 전환
chat: 채팅
copy_copyright:
author: 작성자
link: 링크
source: 출처
info: 저작권은 작성자에게 있습니다. 상업적 사용을 위해서는 작성자의 허가를 받아야 하며, 비상업적 사용 시에는 출처를 명시해 주세요.
Snackbar:
chs_to_cht: 번체로 전환되었습니다.
cht_to_chs: 간체로 전환되었습니다.
day_to_night: 다크 모드로 전환되었습니다.
night_to_day: 라이트 모드로 전환되었습니다.
loading: 로딩 중...
load_more: 더 보기
error404: 페이지를 찾을 수 없습니다.

@ -4,45 +4,45 @@ footer:
copy: copy:
success: 复制成功 success: 复制成功
error: 复制错误 error: 复制失败
noSupport: 浏览器不支持 noSupport: 浏览器不支持
page: page:
articles: 文章总览 articles: 全部文章
tag: 标签 tag: 标签
category: 分类 category: 分类
archives: 归档 archives: 归档
card_post_count: 条评论 card_post_count: 条评论
no_title: no_title:
post: post:
created: 发表于 created: 发表于
updated: 更新于 updated: 更新于
wordcount: 字数总计 wordcount: 字数
min2read: 阅读时长 min2read: 阅读时长
min2read_unit: 分钟 min2read_unit: 分钟
page_pv: 阅读 page_pv: 浏览
comments: 评论数 comments: 评论数
copyright: copyright:
author: 文章作者 author: 文章作者
link: 文章链接 link: 文章链接
copyright_notice: 版权声明 copyright_notice: 版权声明
copyright_content: '本博客所有文章除特别声明外,均采用 copyright_content: '本博客所有文章除特别声明外,均采用
<a href="%s" target="_blank">%s</a> 许可协议。转载请注明来 <a href="%s" target="_blank">%s</a>' <a href="%s" target="_blank">%s</a> 许可协议。转载请注明来 <a href="%s" target="_blank">%s</a>'
recommend: 相关推荐 recommend: 相关推荐
edit: 编辑 edit: 编辑
search: search:
title: 搜索 title: 搜索
load_data: 数据加载中 load_data: 数据加载中
input_placeholder: 搜索文章 input_placeholder: 搜索文章
algolia_search: algolia_search:
hits_empty: '到您查询的内容:${query}' hits_empty: '找到符合您查询的内容:${query}'
hits_stats: '找到 ${hits} 条结果,时 ${time} 毫秒' hits_stats: '找到 ${hits} 条结果,时 ${time} 毫秒'
local_search: local_search:
hits_empty: '到您查询的内容:${query}' hits_empty: '找到符合您查询的内容:${query}'
hits_stats: '共找到 ${hits} 篇文章' hits_stats: '共找到 ${hits} 篇文章'
pagination: pagination:
@ -61,22 +61,22 @@ aside:
card_archives: 归档 card_archives: 归档
card_recent_post: 最新文章 card_recent_post: 最新文章
card_webinfo: card_webinfo:
headline: 网站资讯 headline: 网站信息
article_name: 文章数目 article_name: 文章数目
runtime: runtime:
name: 运行时间 name: 运行时间
unit: unit:
last_push_date: last_push_date:
name: 最后更新时间 name: 最后更新时间
site_wordcount: 本站总字数 site_wordcount: 本站总字数
site_uv_name: 本站访客数 site_uv_name: 本站访客数
site_pv_name: 本站总访问 site_pv_name: 本站总浏览
more_button: 查看更多 more_button: 查看更多
card_newest_comments: card_newest_comments:
headline: 最新评论 headline: 最新评论
loading_text: 正在加载中... loading_text: 加载中...
error: 无法获取评论,请确认相关配置是否正确 error: 无法获取评论,请确认相关配置是否正确
zero: 没有评论 zero: 暂无评论
image: 图片 image: 图片
link: 链接 link: 链接
code: 代码 code: 代码
@ -96,10 +96,10 @@ share: 分享
rightside: rightside:
readmode_title: 阅读模式 readmode_title: 阅读模式
translate_title: 简繁转换 translate_title: 简繁转换
night_mode_title: 浅色和深色模式转 night_mode_title: 日间和夜间模式切
back_to_top: 回到顶部 back_to_top: 回到顶部
toc: 目录 toc: 目录
scroll_to_comment: 直达评论 scroll_to_comment: 前往评论
setting: 设置 setting: 设置
aside: 单栏和双栏切换 aside: 单栏和双栏切换
chat: 聊天 chat: 聊天
@ -111,12 +111,12 @@ copy_copyright:
info: 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 info: 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
Snackbar: Snackbar:
chs_to_cht: 已切换为繁体中文 chs_to_cht: 已切换为繁体中文
cht_to_chs: 已切换为简体中文 cht_to_chs: 已切换为简体中文
day_to_night: 已切换为深色模式 day_to_night: 已切换为深色模式
night_to_day: 已切换为浅色模式 night_to_day: 已切换为浅色模式
loading: 加载中... loading: 加载中...
load_more: 加载更多 load_more: 加载更多
error404: 页面没有找到 error404: 页面找到

@ -0,0 +1,121 @@
footer:
framework: 框架
theme: 主題
copy:
success: 複製成功
error: 複製失敗
noSupport: 瀏覽器不支援
page:
articles: 全部文章
tag: 標籤
category: 分類
archives: 歸檔
card_post_count: 條評論
no_title: 無標題
post:
created: 發表於
updated: 更新於
wordcount: 字數統計
min2read: 閱讀時間
min2read_unit: 分鐘
page_pv: 瀏覽量
comments: 評論數
copyright:
author: 文章作者
link: 文章連結
copyright_notice: 版權聲明
copyright_content: '除特別聲明外,本博客所有文章均採用<a href="%s">%s</a> 授權協議。轉載請註明出處:<a href="%s">%s</a>。'
recommend: 相關文章
edit: 編輯
search:
title: 搜尋
load_data: 正在加載數據庫
input_placeholder: 搜尋文章
algolia_search:
hits_empty: '未找到相關內容:${query}'
hits_stats: '找到 ${hits} 條結果,耗時 ${time} 毫秒'
local_search:
hits_empty: '未找到相關內容:${query}'
hits_stats: '找到 ${hits} 篇文章'
pagination:
prev: 上一頁
next: 下一頁
comment: 評論
aside:
articles: 文章
tags: 標籤
categories: 分類
card_announcement: 公告
card_categories: 分類
card_tags: 標籤
card_archives: 歸檔
card_recent_post: 最新文章
card_webinfo:
headline: 網站資訊
article_name: 文章數目
runtime:
name: 運行時間
unit:
last_push_date:
name: 最後更新時間
site_wordcount: 總字數
site_uv_name: 訪客數
site_pv_name: 總瀏覽量
more_button: 查看更多
card_newest_comments:
headline: 最新評論
loading_text: 正在加載...
error: 無法取得評論,請確認配置是否正確
zero: 暫無評論
image: 圖片
link: 連結
code: 代碼
card_toc: 目錄
card_post_series: 系列文章
date_suffix:
just: 剛剛
min: 分鐘前
hour: 小時前
day: 天前
month: 個月前
donate: 贊助
share: 分享
rightside:
readmode_title: 閱讀模式
translate_title: 簡繁轉換
night_mode_title: 切換日夜模式
back_to_top: 回到頂部
toc: 目錄
scroll_to_comment: 前往評論
setting: 設定
aside: 單欄與雙欄切換
chat: 聊天
copy_copyright:
author: 作者
link: 連結
source: 來源
info: 版權屬於作者所有。商業用途請聯絡作者獲得授權,非商業用途請註明出處。
Snackbar:
chs_to_cht: 已切換為繁體中文
cht_to_chs: 已切換為簡體中文
day_to_night: 已切換為深色模式
night_to_day: 已切換為淺色模式
loading: 正在加載...
load_more: 加載更多
error404: 未找到頁面

@ -4,45 +4,44 @@ footer:
copy: copy:
success: 複製成功 success: 複製成功
error: 複製錯誤 error: 複製失敗
noSupport: 瀏覽器不支援 noSupport: 瀏覽器不支援
page: page:
articles: 文章總覽 articles: 所有文章
tag: 標籤 tag: 標籤
category: 分類 category: 分類
archives: 歸檔 archives: 歸檔
card_post_count: 評論 card_post_count: 評論
no_title: no_title:
post: post:
created: 發表於 created: 發表於
updated: 更新於 updated: 更新於
wordcount: 字數總計 wordcount: 字數
min2read: 閱讀時 min2read: 閱讀時
min2read_unit: 分鐘 min2read_unit: 分鐘
page_pv: 閱讀 page_pv: 瀏覽
comments: 評論數 comments: 評論數
copyright: copyright:
author: 文章作者 author: 文章作者
link: 文章連結 link: 文章連結
copyright_notice: 版權宣告 copyright_notice: 版權聲明
copyright_content: '本部落格所有文章除特別宣告外,均採用 copyright_content: '本部落格所有文章除特別聲明外,均採用<a href="%s" target="_blank">%s</a> 授權協議。轉載請註明來源 <a href="%s" target="_blank">%s</a>'
<a href="%s" target="_blank">%s</a> 許可協議。轉載請註明來自 <a href="%s" target="_blank">%s</a>'
recommend: 相關推薦 recommend: 相關推薦
edit: 編輯 edit: 編輯
search: search:
title: 搜尋 title: 搜尋
load_data: 資料載入中 load_data: 資料載入中
input_placeholder: 搜尋文章 input_placeholder: 搜尋文章
algolia_search: algolia_search:
hits_empty: '找不到您查詢的內容:${query}' hits_empty: '找不到符合您查詢的內容:${query}'
hits_stats: '找到 ${hits} 條結果,用時 ${time} 毫秒' hits_stats: '找到 ${hits} 筆結果,耗時 ${time} 毫秒'
local_search: local_search:
hits_empty: '找不到您查詢的內容:${query}' hits_empty: '找不到符合您查詢的內容:${query}'
hits_stats: '共找到 ${hits} 篇文章' hits_stats: '共找到 ${hits} 篇文章'
pagination: pagination:
@ -62,21 +61,21 @@ aside:
card_recent_post: 最新文章 card_recent_post: 最新文章
card_webinfo: card_webinfo:
headline: 網站資訊 headline: 網站資訊
article_name: 文章數 article_name: 文章數
runtime: runtime:
name: 已執行時間 name: 行時間
unit: unit:
last_push_date: last_push_date:
name: 最後更新時間 name: 最後更新時間
site_wordcount: 本站總字數 site_wordcount: 總字數
site_uv_name: 本站訪客數 site_uv_name: 訪客數
site_pv_name: 本站總訪問 site_pv_name: 總瀏覽
more_button: 檢視更多 more_button: 檢視更多
card_newest_comments: card_newest_comments:
headline: 最新評論 headline: 最新評論
loading_text: 正在載入中... loading_text: 載入中...
error: 無法獲取評論,請確認相關配置是否正確 error: 無法獲取評論,請確認相關配置是否正確
zero: 沒有評論 zero: 尚無評論
image: 圖片 image: 圖片
link: 連結 link: 連結
code: 程式碼 code: 程式碼
@ -95,11 +94,11 @@ share: 分享
rightside: rightside:
readmode_title: 閱讀模式 readmode_title: 閱讀模式
translate_title: 繁轉換 translate_title: 轉換
night_mode_title: 淺色和深色模式轉 night_mode_title: 日夜模式切
back_to_top: 回到頂 back_to_top: 回到頂
toc: 目錄 toc: 目錄
scroll_to_comment: 直達評論 scroll_to_comment: 前往評論
setting: 設定 setting: 設定
aside: 單欄和雙欄切換 aside: 單欄和雙欄切換
chat: 聊天 chat: 聊天
@ -108,15 +107,15 @@ copy_copyright:
author: 作者 author: 作者
link: 連結 link: 連結
source: 來源 source: 來源
info: 著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。 info: 著作權歸作者所有。如需商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。
Snackbar: Snackbar:
chs_to_cht: 已切換為繁體中文 chs_to_cht: 已切換為繁體中文
cht_to_chs: 已切換為簡體中文 cht_to_chs: 已切換為簡體中文
day_to_night: 已切換為深色模式 day_to_night: 已切換為深色模式
night_to_day: 已切換為淺色模式 night_to_day: 已切換為淺色模式
loading: 載入中... loading: 載入中...
load_more: 載入更多 load_more: 載入更多
error404: 頁面沒有找到 error404: 找不到頁面

@ -5,10 +5,8 @@ div
if theme.translate.enable if theme.translate.enable
script(src=url_for(theme.asset.translate)) script(src=url_for(theme.asset.translate))
if theme.lightbox === 'medium_zoom' if theme.lightbox
script(src=url_for(theme.asset.medium_zoom)) script(src=url_for(theme.asset[theme.lightbox]))
else if theme.lightbox === 'fancybox'
script(src=url_for(theme.asset.fancybox))
if theme.instantpage if theme.instantpage
script(src=url_for(theme.asset.instantpage), type='module') script(src=url_for(theme.asset.instantpage), type='module')
@ -30,7 +28,6 @@ div
include ./third-party/subtitle.pug include ./third-party/subtitle.pug
include ./third-party/math/index.pug include ./third-party/math/index.pug
include ./third-party/abcjs/index.pug include ./third-party/abcjs/index.pug
if commentsJsLoad if commentsJsLoad
@ -39,26 +36,24 @@ div
!= partial("includes/third-party/prismjs", {}, { cache: true }) != partial("includes/third-party/prismjs", {}, { cache: true })
if theme.aside.enable && theme.aside.card_newest_comments.enable if theme.aside.enable && theme.aside.card_newest_comments.enable
if theme.pjax.enable if theme.pjax.enable || (!is_post() && page.aside !== false)
!= partial("includes/third-party/newest-comments/index", {}, { cache: true })
else if (!is_post() && page.aside !== false)
!= partial("includes/third-party/newest-comments/index", {}, { cache: true }) != partial("includes/third-party/newest-comments/index", {}, { cache: true })
!= fragment_cache('injectBottom', function(){return injectHtml(theme.inject.bottom)}) != fragment_cache('injectBottom', function(){return injectHtml(theme.inject.bottom)})
!= partial("includes/third-party/effect", {}, { cache: true }) != partial("includes/third-party/effect", {}, { cache: true })
!= partial("includes/third-party/chat/index", {}, { cache: true }) != partial("includes/third-party/chat/index", {}, { cache: true })
if theme.aplayerInject && theme.aplayerInject.enable if theme.aplayerInject && theme.aplayerInject.enable
if theme.pjax.enable || theme.aplayerInject.per_page if theme.pjax.enable || theme.aplayerInject.per_page || page.aplayer
include ./third-party/aplayer.pug
else if page.aplayer
include ./third-party/aplayer.pug include ./third-party/aplayer.pug
if theme.pjax.enable if theme.pjax.enable
!= partial("includes/third-party/pjax", {}, { cache: true }) != partial("includes/third-party/pjax", {}, { cache: true })
if theme.umami_analytics.enable
!= partial("includes/third-party/umami_analytics", {}, { cache: true })
if theme.busuanzi.site_uv || theme.busuanzi.site_pv || theme.busuanzi.page_pv if theme.busuanzi.site_uv || theme.busuanzi.site_pv || theme.busuanzi.page_pv
script(async data-pjax src= theme.asset.busuanzi || '//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js') script(async data-pjax src= theme.asset.busuanzi || '//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js')

@ -1,11 +1,12 @@
#footer-wrap #footer-wrap
if theme.footer.owner.enable if theme.footer.owner.enable
- var now = new Date() - const currentYear = new Date().getFullYear()
- var nowYear = now.getFullYear() - const sinceYear = theme.footer.owner.since
if theme.footer.owner.since && theme.footer.owner.since != nowYear .copyright
.copyright!= `&copy;${theme.footer.owner.since} - ${nowYear} By ${config.author}` if sinceYear && sinceYear != currentYear
!= `&copy;${sinceYear} - ${currentYear} By ${config.author}`
else else
.copyright!= `&copy;${nowYear} By ${config.author}` != `&copy;${currentYear} By ${config.author}`
if theme.footer.copyright if theme.footer.copyright
.framework-info .framework-info
span= _p('footer.framework') + ' ' span= _p('footer.framework') + ' '
@ -14,4 +15,4 @@
span= _p('footer.theme') + ' ' span= _p('footer.theme') + ' '
a(href='https://github.com/jerryc127/hexo-theme-butterfly')= 'Butterfly' a(href='https://github.com/jerryc127/hexo-theme-butterfly')= 'Butterfly'
if theme.footer.custom_text if theme.footer.custom_text
.footer_custom_text!=`${theme.footer.custom_text}` .footer_custom_text!= theme.footer.custom_text

@ -1,11 +1,13 @@
link(rel="manifest" href=url_for(theme.pwa.manifest)) - const { manifest, theme_color, apple_touch_icon, favicon_32_32, favicon_16_16, mask_icon } = theme.pwa
if(theme.pwa.theme_color)
meta(name="msapplication-TileColor" content=theme.pwa.theme_color) link(rel="manifest" href=url_for(manifest))
if(theme.pwa.apple_touch_icon) if theme_color
link(rel="apple-touch-icon" sizes="180x180" href=url_for(theme.pwa.apple_touch_icon)) meta(name="msapplication-TileColor" content=theme_color)
if(theme.pwa.favicon_32_32) if apple_touch_icon
link(rel="icon" type="image/png" sizes="32x32" href=url_for(theme.pwa.favicon_32_32)) link(rel="apple-touch-icon" sizes="180x180" href=url_for(apple_touch_icon))
if(theme.pwa.favicon_16_16) if favicon_32_32
link(rel="icon" type="image/png" sizes="16x16" href=url_for(theme.pwa.favicon_16_16)) link(rel="icon" type="image/png" sizes="32x32" href=url_for(favicon_32_32))
if(theme.pwa.mask_icon) if favicon_16_16
link(rel="mask-icon" href=url_for(theme.pwa.mask_icon) color="#5bbad5") link(rel="icon" type="image/png" sizes="16x16" href=url_for(favicon_16_16))
if mask_icon
link(rel="mask-icon" href=url_for(mask_icon) color="#5bbad5")

@ -25,11 +25,10 @@ if !theme.disable_top_img && page.top_img !== false
if top_img !== false if top_img !== false
- bg_img = getBgPath(top_img) - bg_img = getBgPath(top_img)
- headerClassName = is_home() ? 'full_page' : 'not-home-page' - headerClassName = is_home() ? 'full_page' : is_post() ? 'post-bg' : 'not-home-page'
- headerClassName = is_post() ? 'post-bg' : headerClassName
header#page-header(class=`${headerClassName + isFixedClass}` style=bg_img) header#page-header(class=`${headerClassName + isFixedClass}` style=bg_img)
!=partial('includes/header/nav', {}, {cache: true}) include ./nav.pug
if top_img !== false if top_img !== false
if is_post() if is_post()
include ./post-info.pug include ./post-info.pug
@ -40,7 +39,7 @@ header#page-header(class=`${headerClassName+isFixedClass}` style=bg_img)
- var loadSubJs = true - var loadSubJs = true
#site-subtitle #site-subtitle
span#subtitle span#subtitle
if(theme.social) if theme.social
#site_social_icons #site_social_icons
!=partial('includes/header/social', {}, {cache: true}) !=partial('includes/header/social', {}, {cache: true})
#scroll-down #scroll-down
@ -48,3 +47,7 @@ header#page-header(class=`${headerClassName+isFixedClass}` style=bg_img)
else else
#page-site-info #page-site-info
h1#site-title=page.title || page.tag || page.category h1#site-title=page.title || page.tag || page.category
else
//- improvement seo
if !is_post()
h1.title-seo=page.title || page.tag || page.category || config.title

@ -3,25 +3,25 @@ if theme.menu
each value, label in theme.menu each value, label in theme.menu
if typeof value !== 'object' if typeof value !== 'object'
.menus_item .menus_item
- const valueArray = value.split('||') - const [link, icon] = value.split('||').map(part => trim(part))
a.site-page(href=url_for(trim(valueArray[0]))) a.site-page(href=url_for(link))
if valueArray[1] if icon
i.fa-fw(class=trim(valueArray[1])) i.fa-fw(class=icon)
span= ' ' + label span= ' ' + label
else else
.menus_item .menus_item
- const labelArray = label.split('||') - const [groupLabel, groupIcon, groupClass] = label.split('||').map(part => trim(part))
- const hideClass = labelArray[2] && trim(labelArray[2]) === 'hide' ? 'hide' : '' - const hideClass = groupClass === 'hide' ? 'hide' : ''
span.site-page.group(class=`${hideClass}`) span.site-page.group(class=hideClass)
if labelArray[1] if groupIcon
i.fa-fw(class=trim(labelArray[1])) i.fa-fw(class=groupIcon)
span=' '+ trim(labelArray[0]) span= ' ' + groupLabel
i.fas.fa-chevron-down i.fas.fa-chevron-down
ul.menus_item_child ul.menus_item_child
each val, lab in value each val, lab in value
- const valArray = val.split('||') - const [childLink, childIcon] = val.split('||').map(part => trim(part))
li li
a.site-page.child(href=url_for(trim(valArray[0]))) a.site-page.child(href=url_for(childLink))
if valArray[1] if childIcon
i.fa-fw(class=trim(valArray[1])) i.fa-fw(class=childIcon)
span= ' ' + lab span= ' ' + lab

@ -1,13 +1,15 @@
nav#nav nav#nav
span#blog-info span#blog-info
a(href=url_for('/') title=config.title) a.nav-site-title(href=url_for('/'))
if theme.nav.logo if theme.nav.logo
img.site-icon(src=url_for(theme.nav.logo) alt='Logo') img.site-icon(src=url_for(theme.nav.logo) alt='Logo')
if theme.nav.display_title if theme.nav.display_title
span.site-name=config.title span.site-name=config.title
if is_post()
a.nav-page-title(href=url_for('/'))
span.site-name=(page.title || config.title)
#menus #menus
if (theme.search.use) if theme.search.use
#search-button #search-button
span.site-page.social-icon.search span.site-page.social-icon.search
i.fas.fa-search.fa-fw i.fas.fa-search.fa-fw
@ -18,5 +20,3 @@ nav#nav
#toggle-menu #toggle-menu
span.site-page span.site-page
i.fas.fa-bars.fa-fw i.fas.fa-bars.fa-fw

@ -7,9 +7,9 @@
#post-meta #post-meta
.meta-firstline .meta-firstline
if (theme.post_meta.post.date_type) if theme.post_meta.post.date_type
span.post-meta-date span.post-meta-date
if (theme.post_meta.post.date_type === 'both') if theme.post_meta.post.date_type === 'both'
i.far.fa-calendar-alt.fa-fw.post-meta-icon i.far.fa-calendar-alt.fa-fw.post-meta-icon
span.post-meta-label= _p('post.created') span.post-meta-label= _p('post.created')
time.post-meta-date-created(datetime=date_xml(page.date) title=_p('post.created') + ' ' + full_date(page.date))= date(page.date, config.date_format) time.post-meta-date-created(datetime=date_xml(page.date) title=_p('post.created') + ' ' + full_date(page.date))= date(page.date, config.date_format)
@ -25,20 +25,19 @@
i.fa-fw.post-meta-icon(class=date_icon) i.fa-fw.post-meta-icon(class=date_icon)
span.post-meta-label= date_title span.post-meta-label= date_title
time(datetime=date_xml(page[date_type]) title=date_title + ' ' + full_date(page[date_type]))= date(page[date_type], config.date_format) time(datetime=date_xml(page[date_type]) title=date_title + ' ' + full_date(page[date_type]))= date(page[date_type], config.date_format)
if (theme.post_meta.post.categories && page.categories.data.length > 0) if theme.post_meta.post.categories && page.categories.data.length > 0
span.post-meta-categories span.post-meta-categories
if (theme.post_meta.post.date_type) if theme.post_meta.post.date_type
span.post-meta-separator | span.post-meta-separator |
each item, index in page.categories.data each item, index in page.categories.data
i.fas.fa-inbox.fa-fw.post-meta-icon i.fas.fa-inbox.fa-fw.post-meta-icon
a(href=url_for(item.path)).post-meta-categories #[=item.name] a(href=url_for(item.path)).post-meta-categories #[=item.name]
if (index < page.categories.data.length - 1) if index < page.categories.data.length - 1
i.fas.fa-angle-right.post-meta-separator i.fas.fa-angle-right.post-meta-separator
.meta-secondline .meta-secondline
- let postWordcount = theme.wordcount.enable && (theme.wordcount.post_wordcount || theme.wordcount.min2read) - let postWordcount = theme.wordcount.enable && (theme.wordcount.post_wordcount || theme.wordcount.min2read)
if (postWordcount) if postWordcount
span.post-meta-separator | span.post-meta-separator |
span.post-meta-wordcount span.post-meta-wordcount
if theme.wordcount.post_wordcount if theme.wordcount.post_wordcount
@ -55,34 +54,49 @@
//- for pv and count //- for pv and count
mixin pvBlock(parent_id, parent_class, parent_title) mixin pvBlock(parent_id, parent_class, parent_title)
span.post-meta-separator | span.post-meta-separator |
span(class=parent_class id=parent_id data-flag-title=page.title) span(class=parent_class id=parent_id data-flag-title=parent_title)
i.far.fa-eye.fa-fw.post-meta-icon i.far.fa-eye.fa-fw.post-meta-icon
span.post-meta-label= _p('post.page_pv') + ':' span.post-meta-label= _p('post.page_pv') + ':'
if block if block
block block
- const commentUse = comments.use - const commentUse = comments.use && comments.use[0]
if page.comments !== false && commentUse && !comments.lazyload if page.comments !== false && commentUse && !comments.lazyload
if commentUse[0] === 'Valine' && theme.valine.visitor case commentUse
when 'Valine'
if theme.valine.visitor
+pvBlock(url_for(page.path), 'leancloud_visitors', page.title) +pvBlock(url_for(page.path), 'leancloud_visitors', page.title)
span.leancloud-visitors-count span.leancloud-visitors-count
i.fa-solid.fa-spinner.fa-spin i.fa-solid.fa-spinner.fa-spin
else if commentUse[0] === 'Waline' && theme.waline.pageview when 'Waline'
if theme.waline.pageview
+pvBlock('', '', '') +pvBlock('', '', '')
span.waline-pageview-count(data-path=url_for(page.path)) span.waline-pageview-count(data-path=url_for(page.path))
i.fa-solid.fa-spinner.fa-spin i.fa-solid.fa-spinner.fa-spin
else if commentUse[0] === 'Twikoo' && theme.twikoo.visitor when 'Twikoo'
if theme.twikoo.visitor
+pvBlock('', '', '') +pvBlock('', '', '')
span#twikoo_visitors span#twikoo_visitors
i.fa-solid.fa-spinner.fa-spin i.fa-solid.fa-spinner.fa-spin
else if commentUse[0] === 'Artalk' && theme.artalk.visitor when 'Artalk'
if theme.artalk.visitor
+pvBlock('', '', '') +pvBlock('', '', '')
span#ArtalkPV span#ArtalkPV
i.fa-solid.fa-spinner.fa-spin i.fa-solid.fa-spinner.fa-spin
default
if theme.umami_analytics.enable && theme.umami_analytics.UV_PV.page_pv
+pvBlock('', '', '')
span#umamiPV(data-path=url_for(page.path))
i.fa-solid.fa-spinner.fa-spin
else if theme.busuanzi.page_pv else if theme.busuanzi.page_pv
+pvBlock('', 'post-meta-pv-cv', '') +pvBlock('', 'post-meta-pv-cv', '')
span#busuanzi_value_page_pv span#busuanzi_value_page_pv
i.fa-solid.fa-spinner.fa-spin i.fa-solid.fa-spinner.fa-spin
else
if theme.umami_analytics.enable && theme.umami_analytics.UV_PV.page_pv
+pvBlock('', '', '')
span#umamiPV(data-path=url_for(page.path))
i.fa-solid.fa-spinner.fa-spin
else if theme.busuanzi.page_pv else if theme.busuanzi.page_pv
+pvBlock('', 'post-meta-pv-cv', '') +pvBlock('', 'post-meta-pv-cv', '')
span#busuanzi_value_page_pv span#busuanzi_value_page_pv

@ -1,4 +1,8 @@
each url, icon in theme.social each url, icon in theme.social
a.social-icon(href=url_for(trim(url.split('||')[0])) target="_blank" -
title=url.split('||')[1] === undefined ? '' : trim(url.split('||')[1])) const [link, title, color] = url.split('||').map(i => trim(i))
i(class=icon style=url.split('||')[2] === undefined ? '' : `color: ${trim(url.split('||')[2]).replace(/[\'\"]/g, '')};`) const href = url_for(link)
const iconStyle = color ? `color: ${color.replace(/[\'\"]/g, '')};` : ''
const iconTitle = title || ''
a.social-icon(href=href target="_blank" title=iconTitle)
i(class=icon style=iconStyle)

@ -9,7 +9,6 @@ html(lang=config.language data-theme=theme.display_mode class=htmlClassHideAside
head head
include ./head.pug include ./head.pug
body body
if theme.preloader.enable
!=partial('includes/loading/index', {}, {cache: true}) !=partial('includes/loading/index', {}, {cache: true})
if theme.background if theme.background

@ -24,10 +24,10 @@ script.
} }
preloader.initLoading() preloader.initLoading()
window.addEventListener('load',() => { preloader.endLoading() }) window.addEventListener('load', preloader.endLoading)
if (!{theme.pjax && theme.pjax.enable}) { if (!{theme.pjax && theme.pjax.enable}) {
btf.addGlobalFn('pjaxSend', () => { preloader.initLoading() }, 'preloader_init') btf.addGlobalFn('pjaxSend', preloader.initLoading, 'preloader_init')
btf.addGlobalFn('pjaxComplete', () => { preloader.endLoading() }, 'preloader_end') btf.addGlobalFn('pjaxComplete', preloader.endLoading, 'preloader_end')
} }
})() })()

@ -1,3 +1,4 @@
if theme.preloader.enable
if theme.preloader.source === 1 if theme.preloader.source === 1
include ./fullpage-loading.pug include ./fullpage-loading.pug
else else

@ -1,14 +1,14 @@
mixin articleSort(posts) mixin articleSort(posts)
.article-sort .article-sort
- var year - let year
- posts.each(function (article) { - posts.forEach(article => {
- let tempYear = date(article.date, 'YYYY') - const tempYear = date(article.date, 'YYYY')
- let no_cover = article.cover === false || !theme.cover.archives_enable ? 'no-article-cover' : '' - const noCoverClass = article.cover === false || !theme.cover.archives_enable ? 'no-article-cover' : ''
- let title = article.title || _p('no_title') - const title = article.title || _p('no_title')
if tempYear !== year if tempYear !== year
- year = tempYear - year = tempYear
.article-sort-item.year= year .article-sort-item.year= year
.article-sort-item(class=no_cover) .article-sort-item(class=noCoverClass)
if article.cover && theme.cover.archives_enable if article.cover && theme.cover.archives_enable
a.article-sort-item-img(href=url_for(article.path) title=title) a.article-sort-item-img(href=url_for(article.path) title=title)
if article.cover_type === 'img' if article.cover_type === 'img'

@ -1,19 +1,16 @@
mixin indexPostUI() mixin indexPostUI()
- let indexLayout = theme.index_layout - const indexLayout = theme.index_layout
- let masonryLayoutClass = (indexLayout === 6 || indexLayout === 7) ? 'masonry' : '' - const masonryLayoutClass = (indexLayout === 6 || indexLayout === 7) ? 'masonry' : ''
#recent-posts.recent-posts.nc(class=masonryLayoutClass) #recent-posts.recent-posts.nc(class=masonryLayoutClass)
.recent-post-items .recent-post-items
each article, index in page.posts.data each article, index in page.posts.data
.recent-post-item .recent-post-item
- - const link = article.link || article.path
let link = article.link || article.path - const title = article.title || _p('no_title')
let title = article.title || _p('no_title') - const leftOrRight = indexLayout === 3 ? (index % 2 === 0 ? 'left' : 'right') : (indexLayout === 2 ? 'right' : '')
let leftOrRight = indexLayout === 3 - const post_cover = article.cover
? index%2 == 0 ? 'left' : 'right' - const no_cover = article.cover === false || !theme.cover.index_enable ? 'no-cover' : ''
: indexLayout === 2 ? 'right' : ''
let post_cover = article.cover
let no_cover = article.cover === false || !theme.cover.index_enable ? 'no-cover' : ''
-
if post_cover && theme.cover.index_enable if post_cover && theme.cover.index_enable
.post_cover(class=leftOrRight) .post_cover(class=leftOrRight)
a(href=url_for(link) title=title) a(href=url_for(link) title=title)
@ -23,13 +20,13 @@ mixin indexPostUI()
div.post-bg(style=`background: ${post_cover}`) div.post-bg(style=`background: ${post_cover}`)
.recent-post-info(class=no_cover) .recent-post-info(class=no_cover)
a.article-title(href=url_for(link) title=title) a.article-title(href=url_for(link) title=title)
if (is_home() && (article.top || article.sticky > 0)) if is_home() && (article.top || article.sticky > 0)
i.fas.fa-thumbtack.sticky i.fas.fa-thumbtack.sticky
= title = title
.article-meta-wrap .article-meta-wrap
if (theme.post_meta.page.date_type) if theme.post_meta.page.date_type
span.post-meta-date span.post-meta-date
if (theme.post_meta.page.date_type === 'both') if theme.post_meta.page.date_type === 'both'
i.far.fa-calendar-alt i.far.fa-calendar-alt
span.article-meta-label=_p('post.created') span.article-meta-label=_p('post.created')
time.post-meta-date-created(datetime=date_xml(article.date) title=_p('post.created') + ' ' + full_date(article.date))= date(article.date, config.date_format) time.post-meta-date-created(datetime=date_xml(article.date) title=_p('post.created') + ' ' + full_date(article.date))= date(article.date, config.date_format)
@ -38,28 +35,28 @@ mixin indexPostUI()
span.article-meta-label=_p('post.updated') span.article-meta-label=_p('post.updated')
time.post-meta-date-updated(datetime=date_xml(article.updated) title=_p('post.updated') + ' ' + full_date(article.updated))= date(article.updated, config.date_format) time.post-meta-date-updated(datetime=date_xml(article.updated) title=_p('post.updated') + ' ' + full_date(article.updated))= date(article.updated, config.date_format)
else else
- let data_type_updated = theme.post_meta.page.date_type === 'updated' - const data_type_updated = theme.post_meta.page.date_type === 'updated'
- let date_type = data_type_updated ? 'updated' : 'date' - const date_type = data_type_updated ? 'updated' : 'date'
- let date_icon = data_type_updated ? 'fas fa-history' :'far fa-calendar-alt' - const date_icon = data_type_updated ? 'fas fa-history' : 'far fa-calendar-alt'
- let date_title = data_type_updated ? _p('post.updated') : _p('post.created') - const date_title = data_type_updated ? _p('post.updated') : _p('post.created')
i(class=date_icon) i(class=date_icon)
span.article-meta-label= date_title span.article-meta-label= date_title
time(datetime=date_xml(article[date_type]) title=date_title + ' ' + full_date(article[date_type]))= date(article[date_type], config.date_format) time(datetime=date_xml(article[date_type]) title=date_title + ' ' + full_date(article[date_type]))= date(article[date_type], config.date_format)
if (theme.post_meta.page.categories && article.categories.data.length > 0) if theme.post_meta.page.categories && article.categories.data.length > 0
span.article-meta span.article-meta
span.article-meta-separator | span.article-meta-separator |
each item, index in article.categories.data each item, index in article.categories.data
i.fas.fa-inbox i.fas.fa-inbox
a(href=url_for(item.path)).article-meta__categories #[=item.name] a(href=url_for(item.path)).article-meta__categories #[=item.name]
if (index < article.categories.data.length - 1) if index < article.categories.data.length - 1
i.fas.fa-angle-right.article-meta-link i.fas.fa-angle-right.article-meta-link
if (theme.post_meta.page.tags && article.tags.length > 0) if theme.post_meta.page.tags && article.tags.length > 0
span.article-meta.tags span.article-meta.tags
span.article-meta-separator | span.article-meta-separator |
each item, index in article.tags.data each item, index in article.tags.data
i.fas.fa-tag i.fas.fa-tag
a(href=url_for(item.path)).article-meta__tags #[=item.name] a(href=url_for(item.path)).article-meta__tags #[=item.name]
if (index < article.tags.data.length - 1) if index < article.tags.data.length - 1
span.article-meta-link #[='•'] span.article-meta-link #[='•']
mixin countBlockInIndex mixin countBlockInIndex
@ -119,7 +116,7 @@ mixin indexPostUI()
.content!= truncate(article.content, theme.index_post_content.length) .content!= truncate(article.content, theme.index_post_content.length)
if theme.ad && theme.ad.index if theme.ad && theme.ad.index
if (index + 1) % 3 == 0 if (index + 1) % 3 === 0
.recent-post-item.ads-wrap!= theme.ad.index .recent-post-item.ads-wrap!= theme.ad.index
include ../pagination.pug include ../pagination.pug

@ -1,8 +1,8 @@
if theme.post_copyright.enable && page.copyright !== false if theme.post_copyright.enable && page.copyright !== false
- let author = page.copyright_author || config.author - const author = page.copyright_author || config.author
- let authorHref = page.copyright_author_href || theme.post_copyright.author_href || config.url - const authorHref = page.copyright_author_href || theme.post_copyright.author_href || config.url
- let url = page.copyright_url || page.permalink - const url = page.copyright_url || page.permalink
- let info = page.copyright_info || _p('post.copyright.copyright_content', theme.post_copyright.license_url, theme.post_copyright.license, config.url, config.title) - const info = page.copyright_info || _p('post.copyright.copyright_content', theme.post_copyright.license_url, theme.post_copyright.license, config.url, config.title)
.post-copyright .post-copyright
.post-copyright__author .post-copyright__author
span.post-copyright-meta span.post-copyright-meta

@ -5,9 +5,8 @@
.reward-main .reward-main
ul.reward-all ul.reward-all
each item in theme.reward.QR_code each item in theme.reward.QR_code
- var clickTo = item.link ? item.link : item.img - const clickTo = item.link || item.img
li.reward-item li.reward-item
a(href=url_for(clickTo) target='_blank') a(href=url_for(clickTo) target='_blank')
img.post-qr-code-img(src=url_for(item.img) alt=item.text) img.post-qr-code-img(src=url_for(item.img) alt=item.text)
.post-qr-code-desc=item.text .post-qr-code-desc=item.text

@ -1,4 +1,4 @@
if theme.abcjs && theme.abcjs.enable if theme.abcjs.enable
if theme.abcjs.per_page if theme.abcjs.per_page
if is_post() || is_page() if is_post() || is_page()
include ./abcjs.pug include ./abcjs.pug

@ -1,5 +1,5 @@
- const fbSDKVer = 'v16.0' - const fbSDKVer = 'v20.0'
- const fbSDK = theme.chat.use === 'messenger' ? `https://connect.facebook.net/${theme.facebook_comments.lang}/sdk/xfbml.customerchat.js#xfbml=1&version=${fbSDKVer}` : `https://connect.facebook.net/${theme.facebook_comments.lang}/sdk.js#xfbml=1&version=${fbSDKVer}` - const fbSDK = `https://connect.facebook.net/${theme.facebook_comments.lang}/sdk.js#xfbml=1&version=${fbSDKVer}`
script. script.
(()=>{ (()=>{

@ -15,22 +15,15 @@ script.
Chatra('show') Chatra('show')
} }
window.ChatraSetup = { window.ChatraSetup = { startHidden: true }
startHidden: true
}
window.chatBtnFn = () => { window.chatBtnFn = () => {
const isShow = document.getElementById('chatra').classList.contains('chatra--expanded') document.getElementById('chatra').classList.contains('chatra--expanded') ? close() : open()
isShow ? close() : open()
} }
} else if (isChatHideShow) { } else if (isChatHideShow) {
window.chatBtn = { window.chatBtn = {
hide: () => { hide: () => Chatra('hide'),
Chatra('hide') show: () => Chatra('show')
},
show: () => {
Chatra('show')
}
} }
} }
@ -44,7 +37,6 @@ script.
s.src = 'https://call.chatra.io/chatra.js' s.src = 'https://call.chatra.io/chatra.js'
if (d.head) d.head.appendChild(s) if (d.head) d.head.appendChild(s)
})(document, window, 'Chatra') })(document, window, 'Chatra')
})() })()

@ -20,26 +20,18 @@ script.
$crisp.push(["do", "chat:open"]) $crisp.push(["do", "chat:open"])
} }
const close = () => { const close = () => $crisp.push(["do", "chat:hide"])
$crisp.push(["do", "chat:hide"])
}
close() close()
$crisp.push(["on", "chat:closed", function() {
close()
}])
window.chatBtnFn = () => { $crisp.push(["on", "chat:closed", close])
$crisp.is("chat:visible") ? close() : open()
} window.chatBtnFn = () => $crisp.is("chat:visible") ? close() : open()
} else if (isChatHideShow) { } else if (isChatHideShow) {
window.chatBtn = { window.chatBtn = {
hide: () => { hide: () => $crisp.push(["do", "chat:hide"]),
$crisp.push(["do", "chat:hide"]) show: () => $crisp.push(["do", "chat:show"])
},
show: () => {
$crisp.push(["do", "chat:show"])
}
} }
} }
})() })()

@ -7,5 +7,3 @@ case theme.chat.use
include ./daovoice.pug include ./daovoice.pug
when 'crisp' when 'crisp'
include ./crisp.pug include ./crisp.pug
when 'messenger'
include ./messenger.pug

@ -1,44 +0,0 @@
- let { pageID, lang } = theme.messenger
- lang = theme.comments.use && theme.comments.use.includes('Facebook Comments') ? theme.facebook_comments.lang : lang
#fb-customer-chat.fb-customerchat(page_id=pageID attribution='biz_inbox')
script.
(() => {
document.getElementById('fb-root') ? '' : document.body.insertAdjacentHTML('afterend', '<div id="fb-root"></div>')
window.fbAsyncInit = function() {
FB.init({
xfbml: true,
version: 'v16.0'
});
};
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = 'https://connect.facebook.net/!{lang}/sdk/xfbml.customerchat.js';
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
const isChatBtn = !{theme.chat.rightside_button}
const isChatHideShow = !{theme.chat.button_hide_show}
if (isChatBtn) {
window.chatBtnFn = () => {
const isShow = document.querySelector('.fb_customer_chat_bounce_in_v2')
isShow ? FB.CustomerChat.hide() : FB.CustomerChat.show()
}
} else if (isChatHideShow) {
window.chatBtn = {
hide: () => {
FB.CustomerChat.hide()
},
show: () => {
FB.CustomerChat.show(false)
}
}
}
})()

@ -33,12 +33,8 @@ script.
} }
} else if (isChatHideShow) { } else if (isChatHideShow) {
window.chatBtn = { window.chatBtn = {
hide: () => { hide: () => window.tidioChatApi && window.tidioChatApi.hide(),
window.tidioChatApi && window.tidioChatApi.hide() show: () => window.tidioChatApi && window.tidioChatApi.show()
},
show: () => {
window.tidioChatApi && window.tidioChatApi.show()
}
} }
} }
})() })()

@ -48,7 +48,7 @@ script.
if ('!{use[0]}' === 'Artalk' || !!{lazyload}) { if ('!{use[0]}' === 'Artalk' || !!{lazyload}) {
if (!{lazyload}) btf.loadComment(document.getElementById('artalk-wrap'), loadArtalk) if (!{lazyload}) btf.loadComment(document.getElementById('artalk-wrap'), loadArtalk)
else loadArtalk() else setTimeout(loadArtalk, 100)
} else { } else {
window.loadOtherComment = loadArtalk window.loadOtherComment = loadArtalk
} }

@ -1,5 +1,5 @@
- const fbSDKVer = 'v16.0' - const fbSDKVer = 'v20.0'
- const fbSDK = theme.chat.use === 'messenger' ? `https://connect.facebook.net/${theme.facebook_comments.lang}/sdk/xfbml.customerchat.js#xfbml=1&version=${fbSDKVer}` : `https://connect.facebook.net/${theme.facebook_comments.lang}/sdk.js#xfbml=1&version=${fbSDKVer}` - const fbSDK = `https://connect.facebook.net/${theme.facebook_comments.lang}/sdk.js#xfbml=1&version=${fbSDKVer}`
script. script.
(()=>{ (()=>{

@ -1,18 +1,10 @@
case theme.math.use case theme.math.use
when 'mathjax' when 'mathjax'
if theme.math.per_page if (theme.math.per_page && (is_post() || is_page())) || page.mathjax
if is_post() || is_page()
include ./mathjax.pug
else
if page.mathjax
include ./mathjax.pug include ./mathjax.pug
when 'katex' when 'katex'
if theme.math.per_page if (theme.math.per_page && (is_post() || is_page())) || page.katex
if is_post() || is_page()
include ./katex.pug
else
if page.katex
include ./katex.pug include ./katex.pug
if theme.mermaid.enable if theme.mermaid.enable

@ -1,15 +1,15 @@
script. script.
(async () => { (async () => {
const showKatex = () => { const showKatex = () => {
const mathElements = document.querySelectorAll('#article-container .katex') document.querySelectorAll('#article-container .katex').forEach(el => el.classList.add('katex-show'))
mathElements.length && mathElements.forEach((el) => {
el.classList.add('katex-show')
})
} }
if (!window.katex_js_css) { if (!window.katex_js_css) {
window.katex_js_css = true window.katex_js_css = true
await btf.getCSS('!{url_for(theme.asset.katex)}') await btf.getCSS('!{url_for(theme.asset.katex)}')
if (!{theme.math.katex.copy_tex}) await btf.getScript('!{url_for(theme.asset.katex_copytex)}') if (!{theme.math.katex.copy_tex}) {
await btf.getScript('!{url_for(theme.asset.katex_copytex)}')
}
} }
showKatex() showKatex()

@ -1,13 +1,13 @@
script. script.
(() => { (() => {
const runMermaid = (ele) => { const runMermaid = ele => {
window.loadMermaid = true window.loadMermaid = true
const theme = document.documentElement.getAttribute('data-theme') === 'dark' ? '!{theme.mermaid.theme.dark}' : '!{theme.mermaid.theme.light}' const theme = document.documentElement.getAttribute('data-theme') === 'dark' ? '!{theme.mermaid.theme.dark}' : '!{theme.mermaid.theme.light}'
Array.from(ele).forEach((item, index) => { ele.forEach((item, index) => {
const mermaidSrc = item.firstElementChild const mermaidSrc = item.firstElementChild
const mermaidThemeConfig = '%%{init:{ \'theme\':\'' + theme + '\'}}%%\n' const mermaidThemeConfig = `%%{init:{ 'theme':'${theme}'}}%%\n`
const mermaidID = 'mermaid-' + index const mermaidID = `mermaid-${index}`
const mermaidDefinition = mermaidThemeConfig + mermaidSrc.textContent const mermaidDefinition = mermaidThemeConfig + mermaidSrc.textContent
const renderFn = mermaid.render(mermaidID, mermaidDefinition) const renderFn = mermaid.render(mermaidID, mermaidDefinition)

@ -2,106 +2,63 @@
- const avatarCdn = (option !== null && option.gravatar && option.gravatar.mirror) || '' - const avatarCdn = (option !== null && option.gravatar && option.gravatar.mirror) || ''
- const avatarDefault = (option !== null && option.gravatar && (option.gravatar.params || option.gravatar.default)) || '' - const avatarDefault = (option !== null && option.gravatar && (option.gravatar.params || option.gravatar.default)) || ''
!= partial("includes/third-party/newest-comments/common.pug", {}, { cache: true })
script. script.
window.addEventListener('load', () => { window.addEventListener('load', () => {
const changeContent = (content) => { const keyName = 'artalk-newest-comments'
if (content === '') return content const { changeContent, generateHtml, run } = window.newestComments
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 => { const getAvatarValue = async () => {
let result = '' const predefinedAvatarCdn = '!{avatarCdn}'
const predefinedAvatarDefault = '!{avatarDefault}'
if (array.length) { const avatarDefaultFormat = e => e.startsWith('d=') ? e : `d=${e}`
for (let i = 0; i < array.length; i++) {
result += '<div class=\'aside-list-item\'>'
if (!{theme.aside.card_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') if (predefinedAvatarCdn && predefinedAvatarDefault) {
$dom && ($dom && ($dom.innerHTML= result)) return { avatarCdn: predefinedAvatarCdn, avatarDefault: avatarDefaultFormat(predefinedAvatarDefault) }
window.lazyLoadInstance && window.lazyLoadInstance.update()
window.pjax && window.pjax.refresh($dom)
} }
const getSetting = async () => {
try { try {
const res = await fetch('!{server}/api/v2/conf', { method: 'GET' }) const res = await fetch('!{server}/api/v2/conf')
return await res.json() const result = await res.json()
const { mirror, params, default: defaults } = result.frontend_conf.gravatar
const avatarCdn = predefinedAvatarCdn || mirror
let avatarDefault = avatarDefaultFormat(predefinedAvatarDefault || params || defaults)
return { avatarCdn, avatarDefault}
} catch (e) { } catch (e) {
console.log(e) console.error(e)
return { avatarCdn: predefinedAvatarCdn, avatarDefault: avatarDefaultFormat(predefinedAvatarDefault) }
} }
} }
const headerList = {
method: 'GET',
}
const searchParams = new URLSearchParams({ const searchParams = new URLSearchParams({
'site_name': '!{site}', 'site_name': '!{site}',
'limit': '!{theme.aside.card_newest_comments.limit}', 'limit': '!{theme.aside.card_newest_comments.limit}',
}) })
const getComment = async () => { const getComment = async (ele) => {
try { try {
const res = await fetch(`!{server}/api/v2/stats/latest_comments?${searchParams}`, headerList) const res = await fetch(`!{server}/api/v2/stats/latest_comments?${searchParams}`)
const result = await res.json() const result = await res.json()
const avatarStr = await getSetting() const { avatarCdn, avatarDefault } = await getAvatarValue()
const { mirror, params, default:defaults } = avatarStr.frontend_conf.gravatar const artalk = result.data.map(e => {
const avatarCdn = '!{avatarCdn}' || mirror const avatar = avatarCdn && e.email_encrypted ? `${avatarCdn}${e.email_encrypted}?${avatarDefault}` : ''
let avatarDefault = '!{avatarDefault}' || params || defaults
avatarDefault = avatarDefault.startsWith('d=') ? avatarDefault : `d=${avatarDefault}`
const artalk = result.data.map(function (e) {
return { return {
'avatar': `${avatarCdn}${e.email_encrypted}?${avatarDefault}`, 'avatar': avatar,
'content': changeContent(e.content_marked), 'content': changeContent(e.content_marked),
'nick': e.nick, 'nick': e.nick,
'url': e.page_url, 'url': e.page_url,
'date': e.date, 'date': e.date,
} }
}) })
btf.saveToLocal.set('artalk-newest-comments', JSON.stringify(artalk), !{theme.aside.card_newest_comments.storage}/(60*24)) btf.saveToLocal.set(keyName, JSON.stringify(artalk), !{theme.aside.card_newest_comments.storage}/(60*24))
generateHtml(artalk) generateHtml(artalk, ele)
} catch (e) { } catch (e) {
console.log(e) console.log(e)
const $dom = document.querySelector('#card-newest-comments .aside-list') ele.textContent= "!{_p('aside.card_newest_comments.error')}"
$dom.textContent= "!{_p('aside.card_newest_comments.error')}"
} }
} }
const newestCommentInit = () => { run(keyName, getComment)
if (document.querySelector('#card-newest-comments .aside-list')) {
const data = btf.saveToLocal.get('artalk-newest-comments')
if (data) {
generateHtml(JSON.parse(data))
} else {
getComment()
}
}
}
newestCommentInit()
btf.addGlobalFn('pjaxComplete', newestCommentInit, 'artalk_newestComment')
}) })

@ -0,0 +1,60 @@
script.
window.newestComments = {
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(/<code>.*?<\/code>/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
},
generateHtml: (array, ele) => {
let result = ''
if (array.length) {
for (let i = 0; i < array.length; i++) {
result += '<div class="aside-list-item">'
if (!{theme.aside.card_newest_comments.avatar} && array[i].avatar) {
const imgAttr = '!{theme.lazyload.enable ? "data-lazy-src" : "src"}'
result += `<a href="${array[i].url}" class="thumbnail"><img ${imgAttr}="${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")}'
}
ele.innerHTML = result
window.lazyLoadInstance && window.lazyLoadInstance.update()
window.pjax && window.pjax.refresh(ele)
},
newestCommentInit: (name, getComment) => {
const $dom = document.querySelector('#card-newest-comments .aside-list')
if ($dom) {
const data = btf.saveToLocal.get(name)
if (data) {
newestComments.generateHtml(JSON.parse(data), $dom)
} else {
getComment($dom)
}
}
},
run: (name, getComment) => {
newestComments.newestCommentInit(name, getComment)
btf.addGlobalFn('pjaxComplete', () => newestComments.newestCommentInit(name, getComment), name)
}
}

@ -1,20 +1,11 @@
!= partial("includes/third-party/newest-comments/common.pug", {}, { cache: true })
script. script.
window.addEventListener('load', () => { window.addEventListener('load', () => {
const changeContent = (content) => { const keyName = 'disqus-newest-comments'
if (content === '') return content const { changeContent, generateHtml, run } = window.newestComments
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(/<code>.*?<\/code>/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 getComment = () => { const getComment = ele => {
fetch('https://disqus.com/api/3.0/forums/listPosts.json?forum=!{forum}&related=thread&limit=!{theme.aside.card_newest_comments.limit}&api_key=!{apiKey}') fetch('https://disqus.com/api/3.0/forums/listPosts.json?forum=!{forum}&related=thread&limit=!{theme.aside.card_newest_comments.limit}&api_key=!{apiKey}')
.then(response => response.json()) .then(response => response.json())
.then(data => { .then(data => {
@ -28,54 +19,15 @@ script.
} }
}) })
btf.saveToLocal.set('disqus-newest-comments', JSON.stringify(disqusArray), !{theme.aside.card_newest_comments.storage}/(60*24)) btf.saveToLocal.set(keyName, JSON.stringify(disqusArray), !{theme.aside.card_newest_comments.storage}/(60*24))
generateHtml(disqusArray) generateHtml(disqusArray, ele)
}).catch(e => { }).catch(e => {
const $dom = document.querySelector('#card-newest-comments .aside-list') console.error(e)
$dom.textContent= "!{_p('aside.card_newest_comments.error')}" ele.textContent= "!{_p('aside.card_newest_comments.error')}"
}) })
} }
const generateHtml = array => { run(keyName, getComment)
let result = ''
if (array.length) {
for (let i = 0; i < array.length; i++) {
result += '<div class=\'aside-list-item\'>'
if (!{theme.aside.card_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> / ${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 && ($dom.innerHTML= result)
window.lazyLoadInstance && window.lazyLoadInstance.update()
window.pjax && window.pjax.refresh($dom)
}
const newestCommentInit = () => {
if (document.querySelector('#card-newest-comments .aside-list')) {
const data = btf.saveToLocal.get('disqus-newest-comments')
if (data) {
generateHtml(JSON.parse(data))
} else {
getComment()
}
}
}
newestCommentInit()
btf.addGlobalFn('pjaxComplete', newestCommentInit, 'disqus_newestComment')
}) })

@ -1,20 +1,11 @@
!= partial("includes/third-party/newest-comments/common.pug", {}, { cache: true })
script. script.
window.addEventListener('load', () => { window.addEventListener('load', () => {
const changeContent = (content) => { const keyName = 'github-newest-comments'
if (content === '') return content const { changeContent, generateHtml, run } = window.newestComments
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 findTrueUrl = (array) => { const findTrueUrl = (array, ele) => {
Promise.all(array.map(item => Promise.all(array.map(item =>
fetch(item.url).then(resp => resp.json()).then(data => { fetch(item.url).then(resp => resp.json()).then(data => {
let urlArray = data.body ? data.body.match(/(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/ig) : [] let urlArray = data.body ? data.body.match(/(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/ig) : []
@ -35,12 +26,12 @@ script.
} }
}) })
btf.saveToLocal.set('github-newest-comments', JSON.stringify(array), !{theme.aside.card_newest_comments.storage}/(60*24)) btf.saveToLocal.set(keyName, JSON.stringify(array), !{theme.aside.card_newest_comments.storage}/(60*24))
generateHtml(array) generateHtml(array, ele)
}); });
} }
const getComment = () => { const getComment = ele => {
fetch('https://api.github.com/repos/!{userRepo}/issues/comments?sort=updated&direction=desc&per_page=!{theme.aside.card_newest_comments.limit}&page=1',{ fetch('https://api.github.com/repos/!{userRepo}/issues/comments?sort=updated&direction=desc&per_page=!{theme.aside.card_newest_comments.limit}&page=1',{
"headers": { "headers": {
Accept: 'application/vnd.github.v3.html+json' Accept: 'application/vnd.github.v3.html+json'
@ -54,57 +45,16 @@ script.
'content': changeContent(item.body_html || item.body), 'content': changeContent(item.body_html || item.body),
'nick': item.user.login, 'nick': item.user.login,
'url': item.issue_url, 'url': item.issue_url,
'date': item.updated_at, 'date': item.updated_at
'githubUrl': item.html_url
} }
}) })
findTrueUrl(githubArray) findTrueUrl(githubArray, ele)
}).catch(e => { }).catch(e => {
const $dom = document.querySelector('#card-newest-comments .aside-list') console.error(e)
$dom.textContent= "!{_p('aside.card_newest_comments.error')}" ele.textContent= "!{_p('aside.card_newest_comments.error')}"
}) })
} }
run(keyName, getComment)
const generateHtml = array => {
let result = ''
if (array.length) {
for (let i = 0; i < array.length; i++) {
result += '<div class=\'aside-list-item\'>'
if (!{theme.aside.card_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 && ($dom.innerHTML= result)
window.lazyLoadInstance && window.lazyLoadInstance.update()
window.pjax && window.pjax.refresh($dom)
}
const newestCommentInit = () => {
if (document.querySelector('#card-newest-comments .aside-list')) {
const data = btf.saveToLocal.get('github-newest-comments')
if (data) {
generateHtml(JSON.parse(data))
} else {
getComment()
}
}
}
newestCommentInit()
btf.addGlobalFn('pjaxComplete', newestCommentInit, 'github_newestComment')
}) })

@ -2,52 +2,14 @@
script. script.
window.addEventListener('load', () => { window.addEventListener('load', () => {
const changeContent = (content) => { const keyName = 'remark42-newest-comments'
if (content === '') return content const { changeContent, generateHtml, run } = window.newestComments
content = content.replace(/<img.*?src="(.*?)"?[^\>]+>/ig, '[!{_p("aside.card_newest_comments.image")}]') // replace image link const getComment = ele => {
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.aside.card_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 && ($dom.innerHTML= result)
window.lazyLoadInstance && window.lazyLoadInstance.update()
window.pjax && window.pjax.refresh($dom)
}
const getComment = () => {
fetch('!{host}/api/v1/last/!{theme.aside.card_newest_comments.limit}?site=!{siteId}') fetch('!{host}/api/v1/last/!{theme.aside.card_newest_comments.limit}?site=!{siteId}')
.then(response => response.json()) .then(response => response.json())
.then(data => { .then(data => {
const remark42 = data.map(function (e) { const remark42 = data.map(e => {
return { return {
'avatar': e.user.picture, 'avatar': e.user.picture,
'content': changeContent(e.text), 'content': changeContent(e.text),
@ -56,25 +18,13 @@ script.
'date': e.time, 'date': e.time,
} }
}) })
btf.saveToLocal.set('remark42-newest-comments', JSON.stringify(remark42), !{theme.aside.card_newest_comments.storage}/(60*24)) btf.saveToLocal.set(keyName, JSON.stringify(remark42), !{theme.aside.card_newest_comments.storage}/(60*24))
generateHtml(remark42) generateHtml(remark42, ele)
}).catch(e => { }).catch(e => {
const $dom = document.querySelector('#card-newest-comments .aside-list') console.error(e)
$dom.textContent= "!{_p('aside.card_newest_comments.error')}" ele.textContent= "!{_p('aside.card_newest_comments.error')}"
}) })
} }
const newestCommentInit = () => { run(keyName, getComment)
if (document.querySelector('#card-newest-comments .aside-list')) {
const data = btf.saveToLocal.get('remark42-newest-comments')
if (data) {
generateHtml(JSON.parse(data))
} else {
getComment()
}
}
}
newestCommentInit()
btf.addGlobalFn('pjaxComplete', newestCommentInit, 'remark42_newestComment')
}) })

@ -1,27 +1,18 @@
!= partial("includes/third-party/newest-comments/common.pug", {}, { cache: true })
script. script.
window.addEventListener('load', () => { window.addEventListener('load', () => {
const changeContent = (content) => { const keyName = 'twikoo-newest-comments'
if (content === '') return content const { changeContent, generateHtml, run } = window.newestComments
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_aside.card_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 getComment = () => { const getComment = ele => {
const runTwikoo = () => { const runTwikoo = () => {
twikoo.getRecentComments({ twikoo.getRecentComments({
envId: '!{theme.twikoo.envId}', envId: '!{theme.twikoo.envId}',
region: '!{theme.twikoo.region}', region: '!{theme.twikoo.region}',
pageSize: !{theme.aside.card_newest_comments.limit}, pageSize: !{theme.aside.card_newest_comments.limit},
includeReply: true includeReply: true
}).then(function (res) { }).then(res => {
const twikooArray = res.map(e => { const twikooArray = res.map(e => {
return { return {
'content': changeContent(e.comment), 'content': changeContent(e.comment),
@ -32,11 +23,11 @@ script.
} }
}) })
btf.saveToLocal.set('twikoo-newest-comments', JSON.stringify(twikooArray), !{theme.aside.card_newest_comments.storage}/(60*24)) btf.saveToLocal.set(keyName, JSON.stringify(twikooArray), !{theme.aside.card_newest_comments.storage}/(60*24))
generateHtml(twikooArray) generateHtml(twikooArray, ele)
}).catch(function (err) { }).catch(err => {
const $dom = document.querySelector('#card-newest-comments .aside-list') console.error(err)
$dom.textContent= "!{_p('aside.card_newest_comments.error')}" ele.textContent= "!{_p('aside.card_newest_comments.error')}"
}) })
} }
@ -47,46 +38,7 @@ script.
} }
} }
const generateHtml = array => { run(keyName, getComment)
let result = ''
if (array.length) {
for (let i = 0; i < array.length; i++) {
result += '<div class=\'aside-list-item\'>'
if (!{theme.aside.card_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 && ($dom.innerHTML= result)
window.lazyLoadInstance && window.lazyLoadInstance.update()
window.pjax && window.pjax.refresh($dom)
}
const newestCommentInit = () => {
if (document.querySelector('#card-newest-comments .aside-list')) {
const data = btf.saveToLocal.get('twikoo-newest-comments')
if (data) {
generateHtml(JSON.parse(data))
} else {
getComment()
}
}
}
newestCommentInit()
btf.addGlobalFn('pjaxComplete', newestCommentInit, 'twikoo_newestComment')
}) })

@ -1,21 +1,12 @@
- let default_avatar = theme.valine.avatar - let default_avatar = theme.valine.avatar
script(src=url_for(theme.asset.blueimp_md5)) script(src=url_for(theme.asset.blueimp_md5))
!= partial("includes/third-party/newest-comments/common.pug", {}, { cache: true })
script. script.
window.addEventListener('load', () => { window.addEventListener('load', () => {
const changeContent = (content) => { const keyName = 'valine-newest-comments'
if (content === '') return content const { changeContent, generateHtml, run } = window.newestComments
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 getIcon = (icon, mail) => { const getIcon = (icon, mail) => {
if (icon) return icon if (icon) return icon
@ -24,34 +15,7 @@ script.
return iconUrl return iconUrl
} }
const generateHtml = array => { const getComment = ele => {
let result = ''
if (array.length) {
for (let i = 0; i < array.length; i++) {
result += '<div class=\'aside-list-item\'>'
if (!{theme.aside.card_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 && ($dom.innerHTML= result)
window.lazyLoadInstance && window.lazyLoadInstance.update()
window.pjax && window.pjax.refresh($dom)
}
const getComment = () => {
const serverURL = '!{theme.valine.serverURLs || `https://${theme.valine.appId.substring(0,8)}.api.lncldglobal.com` }' const serverURL = '!{theme.valine.serverURLs || `https://${theme.valine.appId.substring(0,8)}.api.lncldglobal.com` }'
var settings = { var settings = {
@ -66,7 +30,7 @@ script.
fetch(`${serverURL}/1.1/classes/Comment?limit=!{theme.aside.card_newest_comments.limit}&order=-createdAt`,settings) fetch(`${serverURL}/1.1/classes/Comment?limit=!{theme.aside.card_newest_comments.limit}&order=-createdAt`,settings)
.then(response => response.json()) .then(response => response.json())
.then(data => { .then(data => {
const valineArray = data.results.map(function (e) { const valineArray = data.results.map(e => {
return { return {
'avatar': getIcon(e.QQAvatar, e.mail), 'avatar': getIcon(e.QQAvatar, e.mail),
'content': changeContent(e.comment), 'content': changeContent(e.comment),
@ -75,25 +39,13 @@ script.
'date': e.updatedAt, 'date': e.updatedAt,
} }
}) })
btf.saveToLocal.set('valine-newest-comments', JSON.stringify(valineArray), !{theme.aside.card_newest_comments.storage}/(60*24)) btf.saveToLocal.set(keyName, JSON.stringify(valineArray), !{theme.aside.card_newest_comments.storage}/(60*24))
generateHtml(valineArray) generateHtml(valineArray, ele)
}).catch(e => { }).catch(e => {
const $dom = document.querySelector('#card-newest-comments .aside-list') console.error(e)
$dom.textContent= "!{_p('aside.card_newest_comments.error')}" ele.textContent= "!{_p('aside.card_newest_comments.error')}"
}) })
} }
const newestCommentInit = () => { run(keyName, getComment)
if (document.querySelector('#card-newest-comments .aside-list')) {
const data = btf.saveToLocal.get('valine-newest-comments')
if (data) {
generateHtml(JSON.parse(data))
} else {
getComment()
}
}
}
newestCommentInit()
btf.addGlobalFn('pjaxComplete', newestCommentInit, 'valine_newestComment')
}) })

@ -1,49 +1,13 @@
- const serverURL = theme.waline.serverURL.replace(/\/$/, '') - const serverURL = theme.waline.serverURL.replace(/\/$/, '')
!= partial("includes/third-party/newest-comments/common.pug", {}, { cache: true })
script. script.
window.addEventListener('load', () => { window.addEventListener('load', () => {
const changeContent = content => { const keyName = 'waline-newest-comments'
if (content === '') return content const { changeContent, generateHtml, run } = window.newestComments
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.aside.card_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'> const getComment = async (ele) => {
<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 && ($dom.innerHTML= result)
window.lazyLoadInstance && window.lazyLoadInstance.update()
window.pjax && window.pjax.refresh($dom)
}
const getComment = async () => {
try { try {
const res = await fetch('!{serverURL}/api/comment?type=recent&count=!{theme.aside.card_newest_comments.limit}', { method: 'GET' }) const res = await fetch('!{serverURL}/api/comment?type=recent&count=!{theme.aside.card_newest_comments.limit}', { method: 'GET' })
const result = await res.json() const result = await res.json()
@ -56,26 +20,13 @@ script.
'date': e.time || e.insertedAt 'date': e.time || e.insertedAt
} }
}) })
btf.saveToLocal.set('waline-newest-comments', JSON.stringify(walineArray), !{theme.aside.card_newest_comments.storage}/(60*24)) btf.saveToLocal.set(keyName, JSON.stringify(walineArray), !{theme.aside.card_newest_comments.storage}/(60*24))
generateHtml(walineArray) generateHtml(walineArray, ele)
} catch (err) { } catch (err) {
console.error(err) console.error(err)
const $dom = document.querySelector('#card-newest-comments .aside-list') ele.textContent= "!{_p('aside.card_newest_comments.error')}"
$dom.textContent= "!{_p('aside.card_newest_comments.error')}"
}
}
const newestCommentInit = () => {
if (document.querySelector('#card-newest-comments .aside-list')) {
const data = btf.saveToLocal.get('waline-newest-comments')
if (data) {
generateHtml(JSON.parse(data))
} else {
getComment()
}
} }
} }
newestCommentInit() run(keyName, getComment)
btf.addGlobalFn('pjaxComplete', newestCommentInit, 'waline_newestComment')
}) })

@ -1,7 +1,7 @@
- var pjaxExclude = 'a:not([target="_blank"])' - var pjaxExclude = 'a:not([target="_blank"])'
if theme.pjax.exclude if theme.pjax.exclude
each val in theme.pjax.exclude each val in theme.pjax.exclude
- pjaxExclude = pjaxExclude + `:not([href="${val}"])` - pjaxExclude += `:not([href="${val}"])`
- let pjaxSelectors = ['head > title', '#config-diff', '#body-wrap', '#rightside-config-hide', '#rightside-config-show', '.js-pjax'] - let pjaxSelectors = ['head > title', '#config-diff', '#body-wrap', '#rightside-config-hide', '#rightside-config-show', '.js-pjax']
@ -14,9 +14,10 @@ if choose
script(src=url_for(theme.asset.pjax)) script(src=url_for(theme.asset.pjax))
script. script.
let pjaxSelectors = !{JSON.stringify(pjaxSelectors)} (() => {
const pjaxSelectors = !{JSON.stringify(pjaxSelectors)}
var pjax = new Pjax({ window.pjax = new Pjax({
elements: '!{pjaxExclude}', elements: '!{pjaxExclude}',
selectors: pjaxSelectors, selectors: pjaxSelectors,
cacheBust: false, cacheBust: false,
@ -26,18 +27,17 @@ script.
const triggerPjaxFn = (val) => { const triggerPjaxFn = (val) => {
if (!val) return if (!val) return
Object.values(val).forEach(fn => { fn() }) Object.values(val).forEach(fn => fn())
} }
document.addEventListener('pjax:send', function () { document.addEventListener('pjax:send', () => {
// removeEventListener // removeEventListener
btf.removeGlobalFnEvent('pjaxSendOnce') btf.removeGlobalFnEvent('pjaxSendOnce')
btf.removeGlobalFnEvent('themeChange') btf.removeGlobalFnEvent('themeChange')
// reset readmode // reset readmode
const $bodyClassList = document.body.classList const $bodyClassList = document.body.classList
$bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode') if ($bodyClassList.contains('read-mode')) $bodyClassList.remove('read-mode')
triggerPjaxFn(window.globalFn.pjaxSend) triggerPjaxFn(window.globalFn.pjaxSend)
}) })
@ -60,3 +60,4 @@ script.
pjax.loadUrl('!{url_for("/404.html")}') pjax.loadUrl('!{url_for("/404.html")}')
} }
}) })
})()

@ -0,0 +1,65 @@
- let { serverURL, website_id, option, UV_PV } = theme.umami_analytics
- const isServerURL = !!serverURL
- const baseURL = serverURL ? serverURL.replace(/\/$/, '') : 'https://cloud.umami.is'
- const apiUrl = serverURL ? serverURL.replace(/\/$/, '') + '/api' : 'https://api.umami.is/v1'
script.
(() => {
const option = !{JSON.stringify(option)}
const config = !{JSON.stringify(UV_PV)}
const runTrack = () => {
umami.track(props => ({ ...props, url: window.location.pathname, title: GLOBAL_CONFIG_SITE.title }))
}
const loadUmamiJS = () => {
btf.getScript('!{baseURL}/script.js', {
'data-website-id': '!{website_id}',
'data-auto-track': 'false',
...option
}).then(runTrack)
}
const getData = async (isPost) => {
const now = Date.now()
const keyUrl = isPost ? `&url=${window.location.pathname}` : ''
const headerList = { 'Accept': 'application/json' }
if (!{isServerURL}) headerList['Authorization'] = `Bearer ${config.token}`
else headerList['x-umami-api-key'] = config.token
const res = await fetch(`!{apiUrl}/websites/!{website_id}/stats?startAt=0000000000&endAt=${now}${keyUrl}`, {
method: "GET",
headers: headerList
})
return await res.json()
}
const insertData = async () => {
try {
if (GLOBAL_CONFIG_SITE.isPost && config.page_pv) {
const pagePV = document.getElementById('umamiPV')
if (pagePV) {
const data = await getData(true)
pagePV.textContent = data.pageviews.value
}
} else {
const data = (config.site_uv || config.site_pv) && await getData()
if (config.site_uv) {
const siteUV = document.getElementById('umami-site-uv')
if (siteUV) siteUV.textContent = data.visitors.value
}
if (config.site_pv) {
const sitePV = document.getElementById('umami-site-pv')
if (sitePV) sitePV.textContent = data.pageviews.value
}
}
} catch (e) {
console.error('Failed to load Umami Analytics:', e)
}
}
btf.addGlobalFn('pjaxComplete', runTrack, 'umami_analytics_run_track')
btf.addGlobalFn('pjaxComplete', insertData, 'umami_analytics_insert')
loadUmamiJS()
insertData()
})()

@ -17,12 +17,22 @@ if theme.aside.card_webinfo.enable
.webinfo-item .webinfo-item
.item-name=_p('aside.card_webinfo.site_wordcount') + " :" .item-name=_p('aside.card_webinfo.site_wordcount') + " :"
.item-count=totalcount(site) .item-count=totalcount(site)
if theme.busuanzi.site_uv if theme.umami_analytics.enable && theme.umami_analytics.UV_PV.site_uv
.webinfo-item
.item-name= _p('aside.card_webinfo.site_uv_name') + " :"
.item-count#umami-site-uv
i.fa-solid.fa-spinner.fa-spin
else if theme.busuanzi.site_uv
.webinfo-item .webinfo-item
.item-name= _p('aside.card_webinfo.site_uv_name') + " :" .item-name= _p('aside.card_webinfo.site_uv_name') + " :"
.item-count#busuanzi_value_site_uv .item-count#busuanzi_value_site_uv
i.fa-solid.fa-spinner.fa-spin i.fa-solid.fa-spinner.fa-spin
if theme.busuanzi.site_pv if theme.umami_analytics.enable && theme.umami_analytics.UV_PV.site_pv
.webinfo-item
.item-name= _p('aside.card_webinfo.site_pv_name') + " :"
.item-count#umami-site-pv
i.fa-solid.fa-spinner.fa-spin
else if theme.busuanzi.site_pv
.webinfo-item .webinfo-item
.item-name= _p('aside.card_webinfo.site_pv_name') + " :" .item-name= _p('aside.card_webinfo.site_pv_name') + " :"
.item-count#busuanzi_value_site_pv .item-count#busuanzi_value_site_pv

@ -11,7 +11,7 @@ block content
#page(class=noCardLayout) #page(class=noCardLayout)
if top_img === false && page.title if top_img === false && page.title
h1.page-title= page.title .page-title= page.title
case page.type case page.type
when 'tags' when 'tags'

@ -1,6 +1,6 @@
{ {
"name": "hexo-theme-butterfly", "name": "hexo-theme-butterfly",
"version": "5.0.0-b1", "version": "5.0.0-b2",
"description": "A Simple and Card UI Design theme for Hexo", "description": "A Simple and Card UI Design theme for Hexo",
"main": "package.json", "main": "package.json",
"scripts": { "scripts": {

@ -6,9 +6,12 @@ hexo.extend.filter.register('before_generate', () => {
const themeConfig = hexo.theme.config const themeConfig = hexo.theme.config
let { use } = themeConfig.comments let { use } = themeConfig.comments
if (!use) return if (!use) return
if (typeof use === 'string') {
use = use.split(',') // 確保 use 是一個陣列
} use = Array.isArray(use) ? use : use.split(',')
const newArray = use.map(item => item.toLowerCase().replace(/\b[a-z]/g, s => s.toUpperCase()))
themeConfig.comments.use = newArray // 將每個項目轉換為小寫並將首字母大寫
themeConfig.comments.use = use.map(item =>
item.trim().toLowerCase().replace(/\b[a-z]/g, s => s.toUpperCase())
)
}) })

@ -386,14 +386,22 @@ hexo.extend.filter.register('before_generate', () => {
crisp: { crisp: {
website_id: null website_id: null
}, },
messenger: {
pageID: null,
lang: 'zh_TW'
},
baidu_analytics: null, baidu_analytics: null,
google_analytics: null, google_analytics: null,
cloudflare_analytics: null, cloudflare_analytics: null,
microsoft_clarity: null, microsoft_clarity: null,
umami_analytics: {
enable: false,
serverURL: null,
website_id: null,
option: null,
UV_PV: {
site_uv: false,
site_pv: false,
page_pv: false,
token: null
}
},
google_adsense: { google_adsense: {
enable: false, enable: false,
auto_ads: true, auto_ads: true,
@ -425,23 +433,23 @@ hexo.extend.filter.register('before_generate', () => {
beautify: { beautify: {
enable: false, enable: false,
field: 'post', field: 'post',
'title-prefix-icon': null, title_prefix_icon: null,
'title-prefix-icon-color': null title_prefix_icon_color: null
}, },
font: { font: {
'global-font-size': null, global_font_size: null,
'code-font-size': null, code_font_size: null,
'font-family': null, font_family: null,
'code-font-family': null code_font_family: null
}, },
blog_title_font: { blog_title_font: {
font_link: null, font_link: null,
'font-family': null font_family: null
}, },
hr_icon: { hr_icon: {
enable: true, enable: true,
icon: null, icon: null,
'icon-top': null icon_top: null
}, },
activate_power_mode: { activate_power_mode: {
enable: false, enable: false,

@ -1,98 +1,68 @@
/**
* Butterfly
* for aside archives
*/
'use strict' 'use strict'
hexo.extend.helper.register('aside_archives', function (options = {}) { hexo.extend.helper.register('aside_archives', function (options = {}) {
const { config } = this const { config, page, site, url_for, _p } = this
const archiveDir = config.archive_dir const archiveDir = config.archive_dir
const { timezone } = config const { timezone } = config
const lang = toMomentLocale(this.page.lang || this.page.language || config.language) const lang = toMomentLocale(page.lang || page.language || config.language)
let { format } = options
const type = options.type || 'monthly' const type = options.type || 'monthly'
const { transform } = options const format = options.format || (type === 'monthly' ? 'MMMM YYYY' : 'YYYY')
const showCount = Object.prototype.hasOwnProperty.call(options, 'show_count') ? options.show_count : true const showCount = Object.prototype.hasOwnProperty.call(options, 'show_count') ? options.show_count : true
const order = options.order || -1 const order = options.order || -1
const limit = options.limit
const compareFunc = type === 'monthly' const compareFunc = type === 'monthly'
? (yearA, monthA, yearB, monthB) => yearA === yearB && monthA === monthB ? (yearA, monthA, yearB, monthB) => yearA === yearB && monthA === monthB
: (yearA, monthA, yearB, monthB) => yearA === yearB : (yearA, monthA, yearB, monthB) => yearA === yearB
const limit = options.limit
let result = ''
if (!format) { const posts = site.posts.sort('date', order)
format = type === 'monthly' ? 'MMMM YYYY' : 'YYYY' if (!posts.length) return ''
}
const posts = this.site.posts.sort('date', order)
if (!posts.length) return result
const data = [] const data = []
let length = 0
posts.forEach(post => { posts.forEach(post => {
// Clone the date object to avoid pollution
let date = post.date.clone() let date = post.date.clone()
if (timezone) date = date.tz(timezone) if (timezone) date = date.tz(timezone)
const year = date.year() const year = date.year()
const month = date.month() + 1 const month = date.month() + 1
const lastData = data[length - 1]
if (!lastData || !compareFunc(lastData.year, lastData.month, year, month)) { if (!data.length || !compareFunc(data[data.length - 1].year, data[data.length - 1].month, year, month)) {
if (lang) date = date.locale(lang) if (lang) date = date.locale(lang)
const name = date.format(format) data.push({ name: date.format(format), year, month, count: 1 })
length = data.push({
name,
year,
month,
count: 1
})
} else { } else {
lastData.count++ data[data.length - 1].count++
} }
}) })
const link = item => { const link = item => {
let url = `${archiveDir}/${item.year}/` let url = `${archiveDir}/${item.year}/`
if (type === 'monthly') { if (type === 'monthly') {
if (item.month < 10) url += '0' url += item.month < 10 ? `0${item.month}/` : `${item.month}/`
url += `${item.month}/`
} }
return url_for(url)
return this.url_for(url)
} }
const len = data.length const len = data.length
const Judge = limit === 0 ? len : Math.min(len, limit) const limitLength = limit === 0 ? len : Math.min(len, limit)
result += `<div class="item-headline"><i class="fas fa-archive"></i><span>${this._p('aside.card_archives')}</span>` let result = `
<div class="item-headline">
if (len > Judge) { <i class="fas fa-archive"></i>
result += `<a class="card-more-btn" href="${this.url_for(archiveDir)}/" title="${this._p('aside.more_button')}"> <span>${_p('aside.card_archives')}</span>
<i class="fas fa-angle-right"></i></a>` ${len > limitLength ? `<a class="card-more-btn" href="${url_for(archiveDir)}/" title="${_p('aside.more_button')}"><i class="fas fa-angle-right"></i></a>` : ''}
} </div>
<ul class="card-archive-list">
result += '</div><ul class="card-archive-list">' `
for (let i = 0; i < Judge; i++) { for (let i = 0; i < limitLength; i++) {
const item = data[i] const item = data[i]
result += `
result += '<li class="card-archive-list-item">' <li class="card-archive-list-item">
<a class="card-archive-list-link" href="${link(item)}">
result += `<a class="card-archive-list-link" href="${link(item)}">` <span class="card-archive-list-date">${options.transform ? options.transform(item.name) : item.name}</span>
result += '<span class="card-archive-list-date">' ${showCount ? `<span class="card-archive-list-count">${item.count}</span>` : ''}
result += transform ? transform(item.name) : item.name </a>
result += '</span>' </li>
`
if (showCount) {
result += `<span class="card-archive-list-count">${item.count}</span>`
}
result += '</a>'
result += '</li>'
} }
result += '</ul>' result += '</ul>'
@ -100,12 +70,6 @@ hexo.extend.helper.register('aside_archives', function (options = {}) {
}) })
const toMomentLocale = function (lang) { const toMomentLocale = function (lang) {
if (lang === undefined) {
return undefined
}
// moment.locale('') equals moment.locale('en')
// moment.locale(null) equals moment.locale('en')
if (!lang || lang === 'en' || lang === 'default') { if (!lang || lang === 'en' || lang === 'default') {
return 'en' return 'en'
} }

@ -1,66 +1,52 @@
/**
* Butterfly
* for aside categories
*/
'use strict' 'use strict'
hexo.extend.helper.register('aside_categories', function (categories, options) { hexo.extend.helper.register('aside_categories', function (categories, options = {}) {
if (!options && (!categories || !Object.prototype.hasOwnProperty.call(categories, 'length')) if (!categories || !Object.prototype.hasOwnProperty.call(categories, 'length')) {
) { options = categories || {}
options = categories
categories = this.site.categories categories = this.site.categories
} }
if (!categories || !categories.length) return '' if (!categories || !categories.length) return ''
options = options || {}
const { config } = this const { config } = this
const showCount = Object.prototype.hasOwnProperty.call(options, 'show_count') const showCount = Object.prototype.hasOwnProperty.call(options, 'show_count') ? options.show_count : true
? options.show_count
: true
const depth = options.depth ? parseInt(options.depth, 10) : 0 const depth = options.depth ? parseInt(options.depth, 10) : 0
const orderby = options.orderby || 'name' const orderby = options.orderby || 'name'
const order = options.order || 1 const order = options.order || 1
const categoryDir = this.url_for(config.category_dir) const categoryDir = this.url_for(config.category_dir)
const limit = options.limit === 0 ? categories.length : options.limit const limit = options.limit === 0 ? categories.length : (options.limit || categories.length)
const isExpand = options.expand !== 'none' const isExpand = options.expand !== 'none'
const expandClass = isExpand && options.expand === true ? 'expand' : '' const expandClass = isExpand && options.expand === true ? 'expand' : ''
const buttonLabel = this._p('aside.more_button') const buttonLabel = this._p('aside.more_button')
const prepareQuery = (parent) => {
const query = {} const prepareQuery = parent => {
if (parent) { query.parent = parent } else { query.parent = { $exists: false } } const query = parent ? { parent } : { parent: { $exists: false } }
return categories.find(query).sort(orderby, order).filter((cat) => cat.length) return categories.find(query).sort(orderby, order).filter(cat => cat.length)
} }
let expandBtn = ''
const hierarchicalList = (t, level, parent, topparent = true) => { const hierarchicalList = (remaining, level = 0, parent) => {
let result = '' let result = ''
const isTopParent = topparent if (remaining > 0) {
if (t > 0) { prepareQuery(parent).forEach(cat => {
prepareQuery(parent).forEach((cat, i) => { if (remaining > 0) {
if (t > 0) { remaining -= 1
t = t - 1 let child = ''
let child
if (!depth || level + 1 < depth) { if (!depth || level + 1 < depth) {
const childList = hierarchicalList(t, level + 1, cat._id, false) const childList = hierarchicalList(remaining, level + 1, cat._id)
child = childList[0] child = childList.result
t = childList[1] remaining = childList.remaining
} }
const parentClass = isExpand && isTopParent && child ? 'parent' : '' const parentClass = isExpand && !parent && child ? 'parent' : ''
result += `<li class="card-category-list-item ${parentClass}">` result += `<li class="card-category-list-item ${parentClass}">`
result += `<a class="card-category-list-link" href="${this.url_for(cat.path)}">` result += `<a class="card-category-list-link" href="${this.url_for(cat.path)}">`
result += `<span class="card-category-list-name">${cat.name}</span>` result += `<span class="card-category-list-name">${cat.name}</span>`
if (showCount) { if (showCount) {
result += `<span class="card-category-list-count">${cat.length}</span>` result += `<span class="card-category-list-count">${cat.length}</span>`
} }
if (isExpand && isTopParent && child) { if (isExpand && !parent && child) {
expandBtn = ' expandBtn'
result += `<i class="fas fa-caret-left ${expandClass}"></i>` result += `<i class="fas fa-caret-left ${expandClass}"></i>`
} }
@ -74,26 +60,22 @@ hexo.extend.helper.register('aside_categories', function (categories, options) {
} }
}) })
} }
return { result, remaining }
return [result, t]
} }
const list = hierarchicalList(limit, 0) const list = hierarchicalList(limit)
const moreButton = function () { const moreButton = categories.length > limit
if (categories.length <= limit) return '' ? `<a class="card-more-btn" href="${categoryDir}/" title="${buttonLabel}">
const moreHtml = `<a class="card-more-btn" href="${categoryDir}/" title="${buttonLabel}">
<i class="fas fa-angle-right"></i></a>` <i class="fas fa-angle-right"></i></a>`
: ''
return moreHtml
}
return `<div class="item-headline"> return `<div class="item-headline">
<i class="fas fa-folder-open"></i> <i class="fas fa-folder-open"></i>
<span>${this._p('aside.card_categories')}</span> <span>${this._p('aside.card_categories')}</span>
${moreButton()} ${moreButton}
</div> </div>
<ul class="card-category-list${expandBtn}" id="aside-cat-list"> <ul class="card-category-list${isExpand && list.result ? ' expandBtn' : ''}" id="aside-cat-list">
${list[0]} ${list.result}
</ul>` </ul>`
}) })

@ -1,14 +1,3 @@
/**
* Butterfly
* inject js to head
*
* addGlobalFn
* pjaxSendOnce - remove in pjaxSend
* pjaxCompleteOnce - remove in pjaxComplete
* pjaxSend - run in pjaxSend
* pjaxComplete - run in pjaxComplete
*/
'use strict' 'use strict'
hexo.extend.helper.register('inject_head_js', function () { hexo.extend.helper.register('inject_head_js', function () {
@ -16,93 +5,62 @@ hexo.extend.helper.register('inject_head_js', function () {
const start = darkmode.start || 6 const start = darkmode.start || 6
const end = darkmode.end || 18 const end = darkmode.end || 18
const { theme_color } = hexo.theme.config const { theme_color } = hexo.theme.config
const themeColorLight = (theme_color && theme_color.enable && theme_color.meta_theme_color_light) || '#ffffff' const themeColorLight = theme_color && theme_color.enable ? theme_color.meta_theme_color_light : '#ffffff'
const themeColorDark = (theme_color && theme_color.enable && theme_color.meta_theme_color_dark) || '#0d0d0d' const themeColorDark = theme_color && theme_color.enable ? theme_color.meta_theme_color_dark : '#0d0d0d'
const createCustonJs = () => { const createCustomJs = () => `
return `
const saveToLocal = { const saveToLocal = {
set: (key, value, ttl) => { set: (key, value, ttl) => {
if (ttl === 0) return if (!ttl) return
const now = Date.now() const expiry = Date.now() + ttl * 86400000
const expiry = now + ttl * 86400000 localStorage.setItem(key, JSON.stringify({ value, expiry }))
const item = {
value,
expiry
}
localStorage.setItem(key, JSON.stringify(item))
}, },
get: key => { get: key => {
const itemStr = localStorage.getItem(key) const itemStr = localStorage.getItem(key)
if (!itemStr) return undefined
if (!itemStr) { const { value, expiry } = JSON.parse(itemStr)
return undefined if (Date.now() > expiry) {
}
const item = JSON.parse(itemStr)
const now = Date.now()
if (now > item.expiry) {
localStorage.removeItem(key) localStorage.removeItem(key)
return undefined return undefined
} }
return item.value return value
} }
} }
window.btf = { window.btf = {
saveToLocal: saveToLocal, saveToLocal,
getScript: (url, attr = {}) => new Promise((resolve, reject) => { getScript: (url, attr = {}) => new Promise((resolve, reject) => {
const script = document.createElement('script') const script = document.createElement('script')
script.src = url script.src = url
script.async = true script.async = true
script.onerror = reject Object.entries(attr).forEach(([key, val]) => script.setAttribute(key, val))
script.onload = script.onreadystatechange = function() { script.onload = script.onreadystatechange = () => {
const loadState = this.readyState if (!script.readyState || /loaded|complete/.test(script.readyState)) resolve()
if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
script.onload = script.onreadystatechange = null
resolve()
} }
script.onerror = reject
Object.keys(attr).forEach(key => {
script.setAttribute(key, attr[key])
})
document.head.appendChild(script) document.head.appendChild(script)
}), }),
getCSS: (url, id) => new Promise((resolve, reject) => {
getCSS: (url, id = false) => new Promise((resolve, reject) => {
const link = document.createElement('link') const link = document.createElement('link')
link.rel = 'stylesheet' link.rel = 'stylesheet'
link.href = url link.href = url
if (id) link.id = id if (id) link.id = id
link.onerror = reject link.onload = link.onreadystatechange = () => {
link.onload = link.onreadystatechange = function() { if (!link.readyState || /loaded|complete/.test(link.readyState)) resolve()
const loadState = this.readyState
if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
link.onload = link.onreadystatechange = null
resolve()
} }
link.onerror = reject
document.head.appendChild(link) document.head.appendChild(link)
}), }),
addGlobalFn: (key, fn, name = false, parent = window) => { addGlobalFn: (key, fn, name = false, parent = window) => {
const pjaxEnable = ${pjax.enable} if (!${pjax.enable} && key.startsWith('pjax')) return
if (!pjaxEnable && key.startsWith('pjax')) return
const globalFn = parent.globalFn || {} const globalFn = parent.globalFn || {}
const keyObj = globalFn[key] || {} globalFn[key] = globalFn[key] || {}
if (name && globalFn[key][name]) return
if (name && keyObj[name]) return globalFn[key][name || Object.keys(globalFn[key]).length] = fn
name = name || Object.keys(keyObj).length
keyObj[name] = fn
globalFn[key] = keyObj
parent.globalFn = globalFn parent.globalFn = globalFn
} }
} }
` `
}
const createDarkmodeJs = () => { const createDarkmodeJs = () => {
if (!darkmode.enable) return '' if (!darkmode.enable) return ''
@ -124,71 +82,61 @@ hexo.extend.helper.register('inject_head_js', function () {
btf.activateDarkMode = activateDarkMode btf.activateDarkMode = activateDarkMode
btf.activateLightMode = activateLightMode btf.activateLightMode = activateLightMode
const t = saveToLocal.get('theme') const theme = saveToLocal.get('theme')
` `
const autoChangeMode = darkmode.autoChangeMode switch (darkmode.autoChangeMode) {
case 1:
if (autoChangeMode === 1) {
darkmodeJs += ` darkmodeJs += `
const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches const mediaQueryDark = window.matchMedia('(prefers-color-scheme: dark)')
const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches const mediaQueryLight = window.matchMedia('(prefers-color-scheme: light)')
const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches
const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified if (theme === undefined) {
if (mediaQueryLight.matches) activateLightMode()
if (t === undefined) { else if (mediaQueryDark.matches) activateDarkMode()
if (isLightMode) activateLightMode() else {
else if (isDarkMode) activateDarkMode() const hour = new Date().getHours()
else if (isNotSpecified || hasNoSupport) {
const now = new Date()
const hour = now.getHours()
const isNight = hour <= ${start} || hour >= ${end} const isNight = hour <= ${start} || hour >= ${end}
isNight ? activateDarkMode() : activateLightMode() isNight ? activateDarkMode() : activateLightMode()
} }
window.matchMedia('(prefers-color-scheme: dark)').addListener(e => { mediaQueryDark.addEventListener('change', () => {
if (saveToLocal.get('theme') === undefined) { if (saveToLocal.get('theme') === undefined) {
e.matches ? activateDarkMode() : activateLightMode() e.matches ? activateDarkMode() : activateLightMode()
} }
}) })
} else if (t === 'light') activateLightMode() } else {
else activateDarkMode() theme === 'light' ? activateLightMode() : activateDarkMode()
}
` `
} else if (autoChangeMode === 2) { break
case 2:
darkmodeJs += ` darkmodeJs += `
const now = new Date() const hour = new Date().getHours()
const hour = now.getHours()
const isNight = hour <= ${start} || hour >= ${end} const isNight = hour <= ${start} || hour >= ${end}
if (t === undefined) isNight ? activateDarkMode() : activateLightMode() if (theme === undefined) isNight ? activateDarkMode() : activateLightMode()
else if (t === 'light') activateLightMode() else theme === 'light' ? activateLightMode() : activateDarkMode()
else activateDarkMode()
` `
} else { break
default:
darkmodeJs += ` darkmodeJs += `
if (t === 'dark') activateDarkMode() theme === 'dark' ? activateDarkMode() : theme === 'light' ? activateLightMode() : null
else if (t === 'light') activateLightMode()
` `
} }
return darkmodeJs return darkmodeJs
} }
const createAsideStatus = () => { const createAsideStatusJs = () => {
if (!aside.enable || !aside.button) return '' if (!aside.enable || !aside.button) return ''
return ` return `
const asideStatus = saveToLocal.get('aside-status') const asideStatus = saveToLocal.get('aside-status')
if (asideStatus !== undefined) { if (asideStatus !== undefined) {
if (asideStatus === 'hide') { document.documentElement.classList.toggle('hide-aside', asideStatus === 'hide')
document.documentElement.classList.add('hide-aside')
} else {
document.documentElement.classList.remove('hide-aside')
}
} }
` `
} }
const createDetectApple = () => { const createDetectAppleJs = () => `
return `
const detectApple = () => { const detectApple = () => {
if (/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)) { if (/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)) {
document.documentElement.classList.add('apple') document.documentElement.classList.add('apple')
@ -196,7 +144,13 @@ hexo.extend.helper.register('inject_head_js', function () {
} }
detectApple() detectApple()
` `
}
return `<script>(()=>{${createCustonJs() + createDarkmodeJs() + createAsideStatus() + createDetectApple()}})()</script>` return `<script>
(() => {
${createCustomJs()}
${createDarkmodeJs()}
${createAsideStatusJs()}
${createDetectAppleJs()}
})()
</script>`
}) })

@ -9,43 +9,33 @@ hexo.extend.helper.register('truncate', (content, length) => {
hexo.extend.helper.register('cloudTags', function (options = {}) { hexo.extend.helper.register('cloudTags', function (options = {}) {
const env = this const env = this
let { source, minfontsize, maxfontsize, limit, unit, orderby, order } = options let { source, minfontsize, maxfontsize, limit, unit = 'px', orderby, order } = options
unit = unit || 'px'
let result = ''
if (limit > 0) { if (limit > 0) {
source = source.limit(limit) source = source.limit(limit)
} }
const sizes = [] const sizes = [...new Set(source.map(tag => tag.length).sort((a, b) => a - b))]
source.sort('length').forEach(tag => {
const { length } = tag
if (sizes.includes(length)) return
sizes.push(length)
})
const getRandomColor = () => { const getRandomColor = () => {
const randomColor = () => Math.floor(Math.random() * 201) const randomColor = () => Math.floor(Math.random() * 201)
const r = randomColor() const r = randomColor()
const g = randomColor() const g = randomColor()
const b = randomColor() const b = randomColor()
// 確保顏色不是太暗,通過增加一個最低值
return `rgb(${Math.max(r, 50)}, ${Math.max(g, 50)}, ${Math.max(b, 50)})` return `rgb(${Math.max(r, 50)}, ${Math.max(g, 50)}, ${Math.max(b, 50)})`
} }
const generateStyle = (size, unit) => { const generateStyle = (size, unit) =>
const fontSize = parseFloat(size.toFixed(2)) + unit `font-size: ${parseFloat(size.toFixed(2)) + unit}; color: ${getRandomColor()};`
const color = getRandomColor()
return `font-size: ${fontSize}; color: ${color};`
}
const length = sizes.length - 1 const length = sizes.length - 1
source.sort(orderby, order).forEach(tag => { const result = source.sort(orderby, order).map(tag => {
const ratio = length ? sizes.indexOf(tag.length) / length : 0 const ratio = length ? sizes.indexOf(tag.length) / length : 0
const size = minfontsize + ((maxfontsize - minfontsize) * ratio) const size = minfontsize + ((maxfontsize - minfontsize) * ratio)
const style = generateStyle(size, unit) const style = generateStyle(size, unit)
result += `<a href="${env.url_for(tag.path)}" style="${style}">${tag.name}</a>` return `<a href="${env.url_for(tag.path)}" style="${style}">${tag.name}</a>`
}) }).join('')
return result return result
}) })
@ -57,9 +47,8 @@ hexo.extend.helper.register('md5', function (path) {
return crypto.createHash('md5').update(decodeURI(this.url_for(path))).digest('hex') return crypto.createHash('md5').update(decodeURI(this.url_for(path))).digest('hex')
}) })
hexo.extend.helper.register('injectHtml', function (data) { hexo.extend.helper.register('injectHtml', data => {
if (!data) return '' return data ? data.join('') : ''
return data.join('')
}) })
hexo.extend.helper.register('findArchivesTitle', function (page, menu, date) { hexo.extend.helper.register('findArchivesTitle', function (page, menu, date) {
@ -75,7 +64,8 @@ hexo.extend.helper.register('findArchivesTitle', function (page, menu, date) {
const loop = (m) => { const loop = (m) => {
for (const key in m) { for (const key in m) {
if (typeof m[key] === 'object') { if (typeof m[key] === 'object') {
loop(m[key]) const result = loop(m[key])
if (result) return result
} }
if (/\/archives\//.test(m[key])) { if (/\/archives\//.test(m[key])) {
@ -87,7 +77,7 @@ hexo.extend.helper.register('findArchivesTitle', function (page, menu, date) {
return loop(menu) || defaultTitle return loop(menu) || defaultTitle
}) })
hexo.extend.helper.register('getBgPath', function (path) { hexo.extend.helper.register('getBgPath', path => {
if (!path) return '' if (!path) return ''
const absoluteUrlPattern = /^(?:[a-z][a-z\d+.-]*:)?\/\//i const absoluteUrlPattern = /^(?:[a-z][a-z\d+.-]*:)?\/\//i

@ -2,14 +2,14 @@
hexo.extend.helper.register('groupPosts', function () { hexo.extend.helper.register('groupPosts', function () {
const getGroupArray = array => { const getGroupArray = array => {
const groups = {} return array.reduce((groups, item) => {
array.forEach(item => { const key = item.series
const Key = item.series if (key) {
if (!Key) return groups[key] = groups[key] || []
groups[Key] = groups[Key] || [] groups[key].push(item)
groups[Key].push(item) }
})
return groups return groups
}, {})
} }
const sortPosts = posts => { const sortPosts = posts => {

@ -10,11 +10,12 @@
const urlFor = require('hexo-util').url_for.bind(hexo) const urlFor = require('hexo-util').url_for.bind(hexo)
const btn = args => { const btn = args => {
args = args.join(' ').split(',') const [url = '', text = '', icon = '', option = ''] = args.join(' ').split(',').map(arg => arg.trim())
const [url = '', text = '', icon = '', option = ''] = args.map(arg => arg.trim())
return `<a class="btn-beautify ${option}" href="${urlFor(url)}" const iconHTML = icon ? `<i class="${icon}"></i>` : ''
title="${text}">${icon.length ? `<i class="${icon}"></i>` : ''}${text.length ? `<span>${text}</span>` : ''}</a>` const textHTML = text ? `<span>${text}</span>` : ''
return `<a class="btn-beautify ${option}" href="${urlFor(url)}" title="${text}">${iconHTML}${textHTML}</a>`
} }
hexo.extend.tag.register('btn', btn, { ends: false }) hexo.extend.tag.register('btn', btn, { ends: false })

@ -7,28 +7,23 @@
const urlFor = require('hexo-util').url_for.bind(hexo) const urlFor = require('hexo-util').url_for.bind(hexo)
const flinkFn = (args, content) => { const flinkFn = (args, content) => {
content = hexo.render.renderSync({ text: content, engine: 'yaml' }) const data = hexo.render.renderSync({ text: content, engine: 'yaml' })
let result = '' let result = ''
content.forEach(i => { data.forEach(item => {
const className = i.class_name ? `<div class="flink-name">${i.class_name}</div>` : '' const className = item.class_name ? `<div class="flink-name">${item.class_name}</div>` : ''
const classDesc = i.class_desc ? `<div class="flink-desc">${i.class_desc}</div>` : '' const classDesc = item.class_desc ? `<div class="flink-desc">${item.class_desc}</div>` : ''
let listResult = ''
i.link_list.forEach(j => { const listResult = item.link_list.map(link => `
listResult += `
<div class="flink-list-item"> <div class="flink-list-item">
<a href="${j.link}" title="${j.name}" target="_blank"> <a href="${link.link}" title="${link.name}" target="_blank">
<div class="flink-item-icon"> <div class="flink-item-icon">
<img class="no-lightbox" src="${j.avatar}" onerror='this.onerror=null;this.src="${urlFor(hexo.theme.config.error_img.flink)}"' alt="${j.name}" /> <img class="no-lightbox" src="${link.avatar}" onerror='this.onerror=null;this.src="${urlFor(hexo.theme.config.error_img.flink)}"' alt="${link.name}" />
</div> </div>
<div class="flink-item-name">${j.name}</div> <div class="flink-item-name">${link.name}</div>
<div class="flink-item-desc" title="${j.descr}">${j.descr}</div> <div class="flink-item-desc" title="${link.descr}">${link.descr}</div>
</a> </a>
</div>` </div>`).join('')
})
result += `${className}${classDesc}<div class="flink-list">${listResult}</div>` result += `${className}${classDesc}<div class="flink-list">${listResult}</div>`
}) })

@ -14,9 +14,10 @@ const groups = {}
hexo.extend.filter.register('before_post_render', data => { hexo.extend.filter.register('before_post_render', data => {
if (!hexo.theme.config.series.enable) return data if (!hexo.theme.config.series.enable) return data
const { layout, series } = data const { layout, series } = data
if (layout === 'post' && series) { if (layout === 'post' && series) {
groups[series] = groups[series] || [] if (!groups[series]) groups[series] = []
groups[series].push({ groups[series].push({
title: data.title, title: data.title,
path: data.path, path: data.path,
@ -47,23 +48,16 @@ function series (args) {
const itemA = isSortByTitle ? a.title.toUpperCase() : a.date const itemA = isSortByTitle ? a.title.toUpperCase() : a.date
const itemB = isSortByTitle ? b.title.toUpperCase() : b.date const itemB = isSortByTitle ? b.title.toUpperCase() : b.date
if (itemA < itemB) { return itemA < itemB ? (isAsc ? -1 : 1) : itemA > itemB ? (isAsc ? 1 : -1) : 0
return isAsc ? -1 : 1
}
if (itemA > itemB) {
return isAsc ? 1 : -1
}
return 0
} }
seriesArr.sort(compareFn) seriesArr.sort(compareFn)
let result = '' const listItems = seriesArr.map(ele =>
seriesArr.forEach(ele => { `<li><a href="${urlFor(ele.path)}" title="${ele.title}">${ele.title}</a></li>`
result += `<li><a href="${urlFor(ele.path)}" title="${ele.title}">${ele.title}</a></li>` ).join('')
})
return series.number ? `<ol class="series-items">${result}</ol>` : `<ul class="series-items">${result}</ul>` return series.number ? `<ol class="series-items">${listItems}</ol>` : `<ul class="series-items">${listItems}</ul>`
} }
hexo.extend.tag.register('series', series, { ends: false }) hexo.extend.tag.register('series', series, { ends: false })

@ -23,35 +23,27 @@ const postTabs = (args, content) => {
} }
for (let i = 0; i < matches.length; i += 2) { for (let i = 0; i < matches.length; i += 2) {
const tabParameters = matches[i].split('@') const [tabCaption = '', tabIcon = ''] = matches[i].split('@')
let postContent = matches[i + 1] let postContent = matches[i + 1]
let tabCaption = tabParameters[0] || ''
let tabIcon = tabParameters[1] || ''
postContent = hexo.render.renderSync({ text: postContent, engine: 'markdown' }).trim() postContent = hexo.render.renderSync({ text: postContent, engine: 'markdown' }).trim()
tabId += 1 tabId += 1
if (tabCaption.length === 0 && tabIcon.length === 0) tabCaption = tabName + ' ' + tabId const caption = (tabCaption || tabIcon) ? tabCaption : `${tabName} ${tabId}`
const iconHtml = tabIcon ? `<i class="${tabIcon.trim()}"></i>` : ''
const isActive = (tabActive > 0 && tabActive === tabId) || (tabActive === 0 && tabId === 1) ? ' active' : ''
const icon = tabIcon.trim() if (isActive) noDefault = false
tabIcon.length > 0 && (tabIcon = `<i class="${icon}"></i>`)
let isActive = '' tabNav += `<button type="button" class="tab${isActive}">${iconHtml}${caption.trim()}</button>`
if ((tabActive > 0 && tabActive === tabId) || (tabActive === 0 && tabId === 1)) {
isActive = ' active'
noDefault = false
}
tabNav += `<button type="button" class="tab${isActive}">${tabIcon + tabCaption.trim()}</button>`
tabContent += `<div class="tab-item-content${isActive}">${postContent}</div>` tabContent += `<div class="tab-item-content${isActive}">${postContent}</div>`
} }
const toTop = '<div class="tab-to-top"><button type="button" aria-label="scroll to top"><i class="fas fa-arrow-up"></i></button></div>' const toTop = '<div class="tab-to-top"><button type="button" aria-label="scroll to top"><i class="fas fa-arrow-up"></i></button></div>'
tabNav = `<div class="nav-tabs${noDefault ? ' no-default' : ''}">${tabNav}</div>` tabNav = `<div class="nav-tabs${noDefault ? ' no-default' : ''}">${tabNav}</div>`
tabContent = `<div class="tab-contents">${tabContent}</div>` tabContent = `<div class="tab-contents">${tabContent}</div>`
return `<div class="tabs">${tabNav + tabContent + toTop}</div>` return `<div class="tabs">${tabNav}${tabContent}${toTop}</div>`
} }
hexo.extend.tag.register('tabs', postTabs, { ends: true }) hexo.extend.tag.register('tabs', postTabs, { ends: true })

@ -35,7 +35,7 @@ const timeLineFn = (args, content) => {
result += `<div class='timeline-item'>${tlTitleHtml + tlContentHtml}</div>` result += `<div class='timeline-item'>${tlTitleHtml + tlContentHtml}</div>`
} }
return `<div class="timeline ${color}">${result}</div>` return `<div class="timeline ${color || ''}">${result}</div>`
} }
hexo.extend.tag.register('timeline', timeLineFn, { ends: true }) hexo.extend.tag.register('timeline', timeLineFn, { ends: true })

@ -15,10 +15,13 @@
text-rendering: auto text-rendering: auto
-webkit-font-smoothing: antialiased -webkit-font-smoothing: antialiased
addBorderRadius(x = 6) addBorderRadius(x = 6, hide = false)
if hexo-config('rounded_corners_ui') if hexo-config('rounded_corners_ui')
border-radius: unit(x, 'px') border-radius: unit(x, 'px')
if hide
overflow: hidden
// card hover // card hover
.cardHover .cardHover
background: var(--card-bg) background: var(--card-bg)

@ -7,12 +7,3 @@ if hexo-config('chat.rightside_button') == true
height: 1px !important height: 1px !important
opacity: 0 !important opacity: 0 !important
pointer-events: none pointer-events: none
if hexo-config('chat.use') == 'messenger'
.fb_dialog,
.fb-customerchat
visibility: hidden !important
width: 1px !important
height: 1px !important
opacity: 0 !important
pointer-events: none

@ -128,6 +128,9 @@
height: 60px height: 60px
background: 0 background: 0
.title-seo
display: none
#nav #nav
background: rgba(255, 255, 255, .8) background: rgba(255, 255, 255, .8)
box-shadow: 0 5px 6px -5px rgba(133, 133, 133, .6) box-shadow: 0 5px 6px -5px rgba(133, 133, 133, .6)
@ -157,6 +160,12 @@
.site-name .site-name
text-shadow: none text-shadow: none
& > a:first-child
display: none
& > a:last-child
display: inline
a, a,
span.site-page, span.site-page,
#toggle-menu #toggle-menu
@ -195,8 +204,10 @@
max-height: calc(100vh - 170px) max-height: calc(100vh - 170px)
#page #page
h1.page-title .page-title
margin: 8px 0 20px margin: 0 0 10px
font-weight: bold
font-size: 2em
// for not top_img // for not top_img
#post #post
@ -301,6 +312,9 @@
height: 36px height: 36px
vertical-align: middle vertical-align: middle
.nav-page-title
display: none
#toggle-menu #toggle-menu
display: none display: none
padding: 2px 0 0 6px padding: 2px 0 0 6px

@ -139,8 +139,9 @@ if hexo-config('math.use')
&:before &:before
content: none content: none
.snackbar-css .snackbar-container.snackbar-css
border-radius: 5px !important addBorderRadius(5)
opacity: .85 !important
.abc-music-sheet .abc-music-sheet
margin: 0 0 20px margin: 0 0 20px

@ -69,6 +69,7 @@
&.year &.year
font-size: 1.43em font-size: 1.43em
margin-bottom: 10px
&:hover &:hover
&:before &:before

@ -22,6 +22,6 @@
+maxWidth768() +maxWidth768()
font-size: 2em font-size: 2em
h1.page-title .page-title
& + .tag-cloud-list & + .tag-cloud-list
text-align: left text-align: left

@ -127,8 +127,12 @@
&:hover &:hover
background: var(--btn-hover-color) background: var(--btn-hover-color)
i
margin-left: 8px
i i
margin-left: 4px margin-left: 4px
transition: all .3s
.loading-container .loading-container
display: inline-block display: inline-block

@ -36,7 +36,7 @@
.toggle .toggle
margin-bottom: 20px margin-bottom: 20px
border: 1px solid $tag-hide-toggle-bg border: 1px solid $tag-hide-toggle-bg
addBorderRadius() addBorderRadius(5, true)
& > .toggle-button & > .toggle-button
padding: 6px 15px padding: 6px 15px

@ -1,7 +1,7 @@
#article-container #article-container
.timeline .timeline
margin: 0 0 20px 10px margin: 0 10px 20px
padding: 14px 20px 5px padding: 14px 0 5px 20px
border-left: 2px solid var(--timeline-color, $theme-color) border-left: 2px solid var(--timeline-color, $theme-color)
for $type in $color-types for $type in $color-types

@ -18,20 +18,20 @@ $chinseFont = $language == 'zh-CN' ? 'Microsoft YaHei' : 'Microsoft JhengHei'
$dafault-font-family = -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Helvetica Neue', Lato, Roboto, 'PingFang SC', $chinseFont, sans-serif $dafault-font-family = -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Helvetica Neue', Lato, Roboto, 'PingFang SC', $chinseFont, sans-serif
$dafault-code-font = consolas, Menlo, 'PingFang SC', $chinseFont, sans-serif $dafault-code-font = consolas, Menlo, 'PingFang SC', $chinseFont, sans-serif
$font-family = hexo-config('font.font-family') ? unquote(hexo-config('font.font-family')) : $dafault-font-family $font-family = hexo-config('font.font_family') ? unquote(hexo-config('font.font_family')) : $dafault-font-family
$code-font-family = hexo-config('font.code-font-family') ? unquote(hexo-config('font.code-font-family')) : $dafault-code-font $code-font-family = hexo-config('font.code_font_family') ? unquote(hexo-config('font.code_font_family')) : $dafault-code-font
$site-name-font = hexo-config('blog_title_font.font-family') && unquote(hexo-config('blog_title_font.font-family')) $site-name-font = hexo-config('blog_title_font.font_family') && unquote(hexo-config('blog_title_font.font_family'))
// hr // hr
$hrEnable = hexo-config('hr_icon') && hexo-config('hr_icon.enable') $hrEnable = hexo-config('hr_icon') && hexo-config('hr_icon.enable')
$hr-icon = $hrEnable && hexo-config('hr_icon.icon') ? hexo-config('hr_icon.icon') : '\f0c4' $hr-icon = $hrEnable && hexo-config('hr_icon.icon') ? hexo-config('hr_icon.icon') : '\f0c4'
$hr-icon-top = $hrEnable && hexo-config('hr_icon.icon-top') ? convert(hexo-config('hr_icon.icon-top')) : -10px $hr-icon-top = $hrEnable && hexo-config('hr_icon.icon_top') ? convert(hexo-config('hr_icon.icon_top')) : -10px
// page beatutify // page beatutify
$beautifyEnable = hexo-config('beautify.enable') $beautifyEnable = hexo-config('beautify.enable')
$title-prefix-icon = $beautifyEnable && hexo-config('beautify.title-prefix-icon') ? hexo-config('beautify.title-prefix-icon') : '\f0c1' $title-prefix-icon = $beautifyEnable && hexo-config('beautify.title_prefix_icon') ? hexo-config('beautify.title_prefix_icon') : '\f0c1'
$title-prefix-icon-color = $beautifyEnable && hexo-config('beautify.title-prefix-icon-color') ? convert(hexo-config('beautify.title-prefix-icon-color')) : $light-red $title-prefix-icon-color = $beautifyEnable && hexo-config('beautify.title_prefix_icon_color') ? convert(hexo-config('beautify.title_prefix_icon_color')) : $light-red
// Global Variables // Global Variables
$font-size = hexo-config('font.global-font-size') ? convert(hexo-config('font.global-font-size')) : 14px $font-size = hexo-config('font.global_font_size') ? convert(hexo-config('font.global_font_size')) : 14px
$code-font-size = hexo-config('font.code-font-size') ? convert(hexo-config('font.code-font-size')) : var(--global-font-size) $code-font-size = hexo-config('font.code_font_size') ? convert(hexo-config('font.code_font_size')) : var(--global-font-size)
$font-color = #1F2D3D $font-color = #1F2D3D
$text-line-height = 2 $text-line-height = 2
$index_top_img_height = hexo-config('index_top_img_height') ? convert(hexo-config('index_top_img_height')) : 100vh $index_top_img_height = hexo-config('index_top_img_height') ? convert(hexo-config('index_top_img_height')) : 100vh

@ -82,11 +82,12 @@ document.addEventListener('DOMContentLoaded', () => {
} }
} }
const copy = ctx => { const copy = async (text, ctx) => {
if (document.queryCommandSupported && document.queryCommandSupported('copy')) { try {
document.execCommand('copy') await navigator.clipboard.writeText(text)
alertInfo(ctx, GLOBAL_CONFIG.copy.success) alertInfo(ctx, GLOBAL_CONFIG.copy.success)
} else { } catch (err) {
console.error('Failed to copy: ', err)
alertInfo(ctx, GLOBAL_CONFIG.copy.noSupport) alertInfo(ctx, GLOBAL_CONFIG.copy.noSupport)
} }
} }
@ -95,14 +96,10 @@ document.addEventListener('DOMContentLoaded', () => {
const highlightCopyFn = (ele, clickEle) => { const highlightCopyFn = (ele, clickEle) => {
const $buttonParent = ele.parentNode const $buttonParent = ele.parentNode
$buttonParent.classList.add('copy-true') $buttonParent.classList.add('copy-true')
const selection = window.getSelection()
const range = document.createRange()
const preCodeSelector = isPrismjs ? 'pre code' : 'table .code pre' const preCodeSelector = isPrismjs ? 'pre code' : 'table .code pre'
range.selectNodeContents($buttonParent.querySelector(`${preCodeSelector}`)) const codeElement = $buttonParent.querySelector(preCodeSelector)
selection.removeAllRanges() if (!codeElement) return
selection.addRange(range) copy(codeElement.innerText, clickEle.previousElementSibling)
copy(clickEle.previousElementSibling)
selection.removeAllRanges()
$buttonParent.classList.remove('copy-true') $buttonParent.classList.remove('copy-true')
} }
@ -238,8 +235,8 @@ document.addEventListener('DOMContentLoaded', () => {
gap: 5, gap: 5,
isConstantSize: true, isConstantSize: true,
sizeRange: [150, 600], sizeRange: [150, 600],
useResizeObserver: true, // useResizeObserver: true,
observeChildren: true, // observeChildren: true,
useTransform: true useTransform: true
// useRecycle: false // useRecycle: false
}) })

@ -20,19 +20,31 @@ document.addEventListener('DOMContentLoaded', () => {
} }
const translateBody = (fobj) => { const translateBody = (fobj) => {
const objs = typeof fobj === 'object' ? fobj.childNodes : document.body.childNodes const nodes = typeof fobj === 'object' ? fobj.childNodes : document.body.childNodes
for (let i = 0; i < objs.length; i++) {
const obj = objs.item(i) for (const node of nodes) {
if ('BR|HR'.includes(obj.tagName) || obj === translateButtonObject) continue // Skip BR, HR tags, or the translate button object
if (['BR', 'HR'].includes(node.tagName) || node === translateButtonObject) continue
if (obj.title) obj.title = translateText(obj.title)
if (obj.alt) obj.alt = translateText(obj.alt) if (node.nodeType === Node.ELEMENT_NODE) {
if (obj.placeholder) obj.placeholder = translateText(obj.placeholder) const { tagName, title, alt, placeholder, value, type } = node
if (obj.tagName === 'INPUT' && obj.value && obj.type !== 'text' && obj.type !== 'hidden') {
obj.value = translateText(obj.value) // Translate title, alt, placeholder
} if (title) node.title = translateText(title)
if (obj.nodeType === 3) obj.data = translateText(obj.data) if (alt) node.alt = translateText(alt)
else translateBody(obj) if (placeholder) node.placeholder = translateText(placeholder)
// Translate input value except text and hidden types
if (tagName === 'INPUT' && value && type !== 'text' && type !== 'hidden') {
node.value = translateText(value)
}
// Recursively translate child nodes
translateBody(node)
} else if (node.nodeType === Node.TEXT_NODE) {
// Translate text node data
node.data = translateText(node.data)
}
} }
} }

@ -98,10 +98,10 @@
if (!more) return Math.floor(diffDay) if (!more) return Math.floor(diffDay)
if (diffMonth > 24) return datePost.toISOString().slice(0, 10) if (diffMonth > 12) return datePost.toISOString().slice(0, 10)
if (diffMonth >= 3) return `${Math.floor(diffMonth)} ${dateSuffix.month}` if (diffMonth >= 1) return `${Math.floor(diffMonth)} ${dateSuffix.month}`
if (diffDay >= 3) return `${Math.floor(diffDay)} ${dateSuffix.day}` if (diffDay >= 1) return `${Math.floor(diffDay)} ${dateSuffix.day}`
if (diffHour >= 3) return `${Math.floor(diffHour)} ${dateSuffix.hour}` if (diffHour >= 1) return `${Math.floor(diffHour)} ${dateSuffix.hour}`
if (diffMin >= 1) return `${Math.floor(diffMin)} ${dateSuffix.min}` if (diffMin >= 1) return `${Math.floor(diffMin)} ${dateSuffix.min}`
return dateSuffix.just return dateSuffix.just
}, },
@ -145,18 +145,19 @@
requestAnimationFrame(animate) requestAnimationFrame(animate)
}, },
animateIn: (ele, text) => { animateIn: (ele, animation) => {
ele.style.display = 'block' ele.style.display = 'block'
ele.style.animation = text ele.style.animation = animation
}, },
animateOut: (ele, text) => { animateOut: (ele, animation) => {
ele.addEventListener('animationend', function f () { const handleAnimationEnd = () => {
ele.style.display = '' ele.style.display = ''
ele.style.animation = '' ele.style.animation = ''
ele.removeEventListener('animationend', f) ele.removeEventListener('animationend', handleAnimationEnd)
}) }
ele.style.animation = text ele.addEventListener('animationend', handleAnimationEnd)
ele.style.animation = animation
}, },
wrap: (selector, eleType, options) => { wrap: (selector, eleType, options) => {

Loading…
Cancel
Save