Compare commits

..

55 Commits
4.6.1 ... 4.9.0

94 changed files with 1572 additions and 1119 deletions

View File

@@ -1,7 +1,5 @@
<div align="right"> <div align="right">
Language: <a title="Chinese" href="/README_CN.md">中文</a>
🇺🇸
<a title="Chinese" href="/README_CN.md">🇨🇳</a>
</div> </div>
# hexo-theme-butterfly # hexo-theme-butterfly
@@ -14,7 +12,7 @@
![](https://cdn.jsdelivr.net/gh/jerryc127/CDN@m2/img/theme-butterfly-readme.png) ![](https://cdn.jsdelivr.net/gh/jerryc127/CDN@m2/img/theme-butterfly-readme.png)
Demo: 👍 [Butterfly](https://butterfly.js.org/) || 🤞 [CrazyWong](https://crazywong.com/) Demo: 👍 [Butterfly](https://butterfly.js.org/) || 🤞 [CrazyWong](https://blog.crazywong.com/)
Docs: 📖 [Butterfly Docs](https://butterfly.js.org/posts/21cfbf15/) Docs: 📖 [Butterfly Docs](https://butterfly.js.org/posts/21cfbf15/)
@@ -62,17 +60,17 @@ npm i hexo-theme-butterfly
- [x] Card UI Design - [x] Card UI Design
- [X] Support sub-menu - [X] Support sub-menu
- [x] Two Column designs - [x] Two-column layout
- [x] Responsive Web Design - [x] Responsive Web Design
- [x] Dark Mode - [x] Dark Mode
- [x] Pjax - [x] Pjax
- [x] Read Mode - [x] Read Mode
- [x] Conversion between Traditional and Simplified Chinese - [x] Conversion between Traditional and Simplified Chinese
- [X] TOC catalog is available for both computers and mobile phones - [X] TOC catalog is available for both computers and mobile phones
- [X] Color themes (darker/pale night/light/ocean/mac/mac light), support custom colors - [X] Built-in Syntax Highlighting Themes (darker/pale night/light/ocean/mac/mac light), also support customization
- [X] Code Blocks (Display code language/close or expand Code Blocks/Copy Button/word wrap) - [X] Code Blocks (Display code language/close or expand Code Blocks/Copy Button/word wrap)
- [X] Disable copy/Add a Copyright Notice to the Copied Text - [X] Disable copy/Add a Copyright Notice to the Copied Text
- [X] Search (Algolia SearchZ/Local Search) - [X] Search (Algolia Search/Local Search)
- [x] Mathjax and Katex - [x] Mathjax and Katex
- [x] Built-in 404 page - [x] Built-in 404 page
- [x] WordCount - [x] WordCount
@@ -81,7 +79,7 @@ npm i hexo-theme-butterfly
- [x] Share (AddThis/Sharejs/Addtoany) - [x] Share (AddThis/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/Gitter/Crisp/messenger) - [x] Online Chats (Chatra/Tidio/Daovoice/Crisp/messenger)
- [x] Web analytics - [x] Web analytics
- [x] Google AdSense - [x] Google AdSense
- [x] Webmaster Verification - [x] Webmaster Verification

View File

@@ -1,7 +1,5 @@
<div align="right"> <div align="right">
語言: <a title="English" href="/README.md">English</a>
中文
<a title="English" href="/README.md">英文</a>
</div> </div>
# hexo-theme-butterfly # hexo-theme-butterfly
@@ -14,7 +12,7 @@
![](https://cdn.jsdelivr.net/gh/jerryc127/CDN@m2/img/theme-butterfly-readme.png) ![](https://cdn.jsdelivr.net/gh/jerryc127/CDN@m2/img/theme-butterfly-readme.png)
預覽: 👍 [Butterfly](https://butterfly.js.org/) || 🤞 [CrazyWong](https://crazywong.com/) 預覽: 👍 [Butterfly](https://butterfly.js.org/) || 🤞 [CrazyWong](https://blog.crazywong.com/)
文檔: 📖 [Butterfly Docs](https://butterfly.js.org/posts/21cfbf15/) 文檔: 📖 [Butterfly Docs](https://butterfly.js.org/posts/21cfbf15/)
@@ -72,7 +70,7 @@ theme: butterfly
- [X] 內置多種代碼配色darker/pale night/light/ocean/mac/mac light可自定義代碼配色 - [X] 內置多種代碼配色darker/pale night/light/ocean/mac/mac light可自定義代碼配色
- [X] 代碼塊顯示代碼語言/關閉或展開代碼塊/代碼複製/代碼自動換行 - [X] 代碼塊顯示代碼語言/關閉或展開代碼塊/代碼複製/代碼自動換行
- [X] 可關閉文字複製/可開啟內容複製增加版權信息) - [X] 可關閉文字複製/可開啟內容複製增加版權信息)
- [X] 兩種搜索Algolia搜索和本地搜索 - [X] 兩種搜索( Algolia 搜索和本地搜索)
- [x] Mathjax 和 Katex - [x] Mathjax 和 Katex
- [x] 內置404頁面 - [x] 內置404頁面
- [x] 顯示字數統計 - [x] 顯示字數統計
@@ -81,7 +79,7 @@ theme: butterfly
- [x] 多種分享系統AddThis/Sharejs/Addtoany - [x] 多種分享系統AddThis/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/Gitter/Crisp/messenger - [x] 多種在線聊天Chatra/Tidio/Daovoice/Crisp/messenger
- [x] 多種分析系統 - [x] 多種分析系統
- [x] 谷歌廣告/手動廣告位置 - [x] 谷歌廣告/手動廣告位置
- [x] 各種站長驗證Google/Bing/Baidu/360/Yandex - [x] 各種站長驗證Google/Bing/Baidu/360/Yandex

View File

@@ -1,7 +1,13 @@
# Main menu navigation (導航目錄) # Navigation bar settings (導航欄設置)
# see https://butterfly.js.org/posts/4aa8abbe/#導航菜單 # see https://butterfly.js.org/posts/4aa8abbe/##導航欄設置-Navigation-bar-settings
# -------------------------------------- # --------------------------------------
nav:
logo: # image
display_title: true
fixed: false # fixed navigation bar
# Menu 目錄
menu: menu:
# Home: / || fas fa-home # Home: / || fas fa-home
# Archives: /archives/ || fas fa-archive # Archives: /archives/ || fas fa-archive
@@ -13,11 +19,6 @@ menu:
# Link: /link/ || fas fa-link # Link: /link/ || fas fa-link
# About: /about/ || fas fa-heart # About: /about/ || fas fa-heart
nav:
logo: # image
display_title: true
fixed: false # fixed navigation bar
# Code Blocks (代碼相關) # Code Blocks (代碼相關)
# -------------------------------------- # --------------------------------------
@@ -28,54 +29,12 @@ highlight_shrink: false # true: shrink the code blocks / false: expand the code
highlight_height_limit: false # unit: px highlight_height_limit: false # unit: px
code_word_wrap: false code_word_wrap: false
# copy settings # Social Settings (社交圖標設置)
# copyright: Add the copyright information after copied content (複製的內容後面加上版權信息)
copy:
enable: true
copyright:
enable: false
limit_count: 50
# social settings (社交圖標設置)
# formal: # formal:
# icon: link || the description # icon: link || the description || color
social: social:
# fab fa-github: https://github.com/xxxxx || Github # fab fa-github: https://github.com/xxxxx || Github || '#24292e'
# fas fa-envelope: mailto:xxxxxx@gmail.com || Email # fas fa-envelope: mailto:xxxxxx@gmail.com || Email || '#4a7dbe'
# search (搜索)
# see https://butterfly.js.org/posts/ceeb73f/#搜索系統
# --------------------------------------
# Algolia search
algolia_search:
enable: false
hits:
per_page: 6
# Local search
local_search:
enable: false
preload: false
CDN:
# Math (數學)
# --------------------------------------
# About the per_page
# if you set it to true, it will load mathjax/katex script in each page (true 表示每一頁都加載js)
# if you set it to false, it will load mathjax/katex script according to your setting (add the 'mathjax: true' in page's front-matter)
# (false 需要時加載,須在使用的 Markdown Front-matter 加上 mathjax: true)
# MathJax
mathjax:
enable: false
per_page: false
# KaTeX
katex:
enable: false
per_page: false
hide_scrollbar: true
# Image (圖片設置) # Image (圖片設置)
# -------------------------------------- # --------------------------------------
@@ -155,14 +114,6 @@ post_meta:
tags: true # true or false 文章頁是否顯示標籤 tags: true # true or false 文章頁是否顯示標籤
label: true # true or false 顯示描述性文字 label: true # true or false 顯示描述性文字
# wordcount (字數統計)
# see https://butterfly.js.org/posts/ceeb73f/#字數統計
wordcount:
enable: false
post_wordcount: true
min2read: true
total_wordcount: true
# Display the article introduction on homepage # Display the article introduction on homepage
# 1: description # 1: description
# 2: both (if the description exists, it will show description, or show the auto_excerpt) # 2: both (if the description exists, it will show description, or show the auto_excerpt)
@@ -180,6 +131,17 @@ anchor:
icon: # the unicode value of Font Awesome icon, such as '\3423' icon: # the unicode value of Font Awesome icon, such as '\3423'
auto_update: false # when you scroll in post, the URL will update according to header id. auto_update: false # when you scroll in post, the URL will update according to header id.
# figcaption (圖片描述文字)
photofigcaption: false
# copy settings
# copyright: Add the copyright information after copied content (複製的內容後面加上版權信息)
copy:
enable: true
copyright:
enable: false
limit_count: 50
# Post # Post
# -------------------------------------- # --------------------------------------
@@ -224,9 +186,6 @@ related_post:
limit: 6 # Number of posts displayed limit: 6 # Number of posts displayed
date_type: created # or created or updated 文章日期顯示創建日或者更新日 date_type: created # or created or updated 文章日期顯示創建日或者更新日
# figcaption (圖片描述文字)
photofigcaption: false
# post_pagination (分頁) # post_pagination (分頁)
# value: 1 || 2 || false # value: 1 || 2 || false
# 1: The 'next post' will link to old post # 1: The 'next post' will link to old post
@@ -243,7 +202,183 @@ noticeOutdate:
message_prev: It has been message_prev: It has been
message_next: days since the last update, the content of the article may be outdated. message_next: days since the last update, the content of the article may be outdated.
# Share System (分享功能) # Footer Settings
# --------------------------------------
footer:
owner:
enable: true
since: 2020
custom_text:
copyright: true # Copyright of theme and framework
# aside (側邊欄)
# --------------------------------------
aside:
enable: true
hide: false
button: true
mobile: true # display on mobile
position: right # left or right
display:
archive: true
tag: true
category: true
card_author:
enable: true
description:
button:
enable: true
icon: fab fa-github
text: Follow Me
link: https://github.com/xxxxxx
card_announcement:
enable: true
content: This is my Blog
card_recent_post:
enable: true
limit: 5 # if set 0 will show all
sort: date # date or updated
sort_order: # Don't modify the setting unless you know how it works
card_categories:
enable: true
limit: 8 # if set 0 will show all
expand: none # none/true/false
sort_order: # Don't modify the setting unless you know how it works
card_tags:
enable: true
limit: 40 # if set 0 will show all
color: false
orderby: random # Order of tags, random/name/length
order: 1 # Sort of order. 1, asc for ascending; -1, desc for descending
sort_order: # Don't modify the setting unless you know how it works
card_archives:
enable: true
type: monthly # yearly or monthly
format: MMMM YYYY # eg: YYYY年MM月
order: -1 # Sort of order. 1, asc for ascending; -1, desc for descending
limit: 8 # if set 0 will show all
sort_order: # Don't modify the setting unless you know how it works
card_webinfo:
enable: true
post_count: true
last_push_date: true
sort_order: # Don't modify the setting unless you know how it works
# busuanzi count for PV / UV in site
# 訪問人數
busuanzi:
site_uv: true
site_pv: true
page_pv: true
# Time difference between publish date and now (網頁運行時間)
# Formal: Month/Day/Year Time or Year/Month/Day Time
runtimeshow:
enable: false
publish_date:
# Aside widget - Newest Comments
newest_comments:
enable: false
sort_order: # Don't modify the setting unless you know how it works
limit: 6
storage: 10 # unit: mins, save data to localStorage
avatar: true
# Bottom right button (右下角按鈕)
# --------------------------------------
# Conversion between Traditional and Simplified Chinese (簡繁轉換)
translate:
enable: false
# The text of a button
default:
# the language of website (1 - Traditional Chinese/ 2 - Simplified Chinese
defaultEncoding: 2
# Time delay
translateDelay: 0
# The text of the button when the language is Simplified Chinese
msgToTraditionalChinese: '繁'
# The text of the button when the language is Traditional Chinese
msgToSimplifiedChinese: '簡'
# Read Mode (閲讀模式)
readmode: true
# dark mode
darkmode:
enable: true
# Toggle Button to switch dark/light mode
button: true
# Switch dark/light mode automatically (自動切換 dark mode和 light mode)
# autoChangeMode: 1 Following System Settings, if the system doesn't support dark mode, it will switch dark mode between 6 pm to 6 am
# autoChangeMode: 2 Switch dark mode between 6 pm to 6 am
# autoChangeMode: false
autoChangeMode: false
# Set the light mode time. The value is between 0 and 24. If not set, the default value is 6 and 18
start: # 8
end: # 22
# show scroll percent in scroll-to-top button
rightside_scroll_percent: false
# Don't modify the following settings unless you know how they work (非必要請不要修改 )
# Choose: readmode,translate,darkmode,hideAside,toc,chat,comment
# Don't repeat 不要重複
rightside_item_order:
enable: false
hide: # readmode,translate,darkmode,hideAside
show: # toc,chat,comment
# Math (數學)
# --------------------------------------
# About the per_page
# if you set it to true, it will load mathjax/katex script in each page (true 表示每一頁都加載js)
# if you set it to false, it will load mathjax/katex script according to your setting (add the 'mathjax: true' in page's front-matter)
# (false 需要時加載,須在使用的 Markdown Front-matter 加上 mathjax: true)
# MathJax
mathjax:
enable: false
per_page: false
# KaTeX
katex:
enable: false
per_page: false
hide_scrollbar: true
# search (搜索)
# see https://butterfly.js.org/posts/ceeb73f/#搜索系統
# --------------------------------------
# Algolia search
algolia_search:
enable: false
hits:
per_page: 6
# Local search
local_search:
enable: false
# Preload the search data when the page loads.
preload: false
# Show top n results per article, show all results by setting to -1
top_n_per_article: 1
# Unescape html strings to the readable one.
unescape: false
CDN:
# Docsearch
docsearch:
enable: false
appId:
apiKey:
indexName:
option:
# Share System (分享)
# -------------------------------------- # --------------------------------------
# AddThis # AddThis
@@ -407,12 +542,6 @@ daovoice:
enable: false enable: false
app_id: app_id:
# gitter
# https://gitter.im/
gitter:
enable: false
room:
# crisp # crisp
# https://crisp.chat/en/ # https://crisp.chat/en/
crisp: crisp:
@@ -426,15 +555,6 @@ messenger:
pageID: pageID:
lang: zh_TW # Language en_US/zh_CN/zh_TW and so on lang: zh_TW # Language en_US/zh_CN/zh_TW and so on
# Footer Settings
# --------------------------------------
footer:
owner:
enable: true
since: 2020
custom_text:
copyright: true # Copyright of theme and framework
# Analysis # Analysis
# -------------------------------------- # --------------------------------------
@@ -525,12 +645,25 @@ background:
# Footer Background # Footer Background
footer_bg: false footer_bg: false
# Add mask to header or footer (为 header 或 footer 添加黑色半透遮罩)
mask:
header: true
footer: true
# the position of bottom right button/default unit: px (右下角按鈕距離底部的距離/默認單位為px) # the position of bottom right button/default unit: px (右下角按鈕距離底部的距離/默認單位為px)
rightside-bottom: rightside-bottom:
# Enter transitions (開啓網頁進入效果) # Enter transitions (開啓網頁進入效果)
enter_transitions: true enter_transitions: true
# Typewriter Effect (打字效果)
# https://github.com/disjukr/activate-power-mode
activate_power_mode:
enable: false
colorful: true # open particle animation (冒光特效)
shake: true # open shake (抖動特效)
mobile: false
# Background effects (背景特效) # Background effects (背景特效)
# -------------------------------------- # --------------------------------------
@@ -559,14 +692,6 @@ canvas_nest:
count: 99 # the number of lines, default: 99. count: 99 # the number of lines, default: 99.
mobile: false mobile: false
# Typewriter Effect (打字效果)
# https://github.com/disjukr/activate-power-mode
activate_power_mode:
enable: false
colorful: true # open particle animation (冒光特效)
shake: true # open shake (抖動特效)
mobile: false
# Mouse click effects: fireworks (鼠標點擊效果: 煙火特效) # Mouse click effects: fireworks (鼠標點擊效果: 煙火特效)
fireworks: fireworks:
enable: false enable: false
@@ -648,120 +773,13 @@ preloader:
# pace theme (see https://codebyzach.github.io/pace/) # pace theme (see https://codebyzach.github.io/pace/)
pace_css_url: pace_css_url:
# aside (側邊欄) # wordcount (字數統計)
# -------------------------------------- # see https://butterfly.js.org/posts/ceeb73f/#字數統計
wordcount:
aside:
enable: true
hide: false
button: true
mobile: true # display on mobile
position: right # left or right
display:
archive: true
tag: true
category: true
card_author:
enable: true
description:
button:
enable: true
icon: fab fa-github
text: Follow Me
link: https://github.com/xxxxxx
card_announcement:
enable: true
content: This is my Blog
card_recent_post:
enable: true
limit: 5 # if set 0 will show all
sort: date # date or updated
sort_order: # Don't modify the setting unless you know how it works
card_categories:
enable: true
limit: 8 # if set 0 will show all
expand: none # none/true/false
sort_order: # Don't modify the setting unless you know how it works
card_tags:
enable: true
limit: 40 # if set 0 will show all
color: false
sort_order: # Don't modify the setting unless you know how it works
card_archives:
enable: true
type: monthly # yearly or monthly
format: MMMM YYYY # eg: YYYY年MM月
order: -1 # Sort of order. 1, asc for ascending; -1, desc for descending
limit: 8 # if set 0 will show all
sort_order: # Don't modify the setting unless you know how it works
card_webinfo:
enable: true
post_count: true
last_push_date: true
sort_order: # Don't modify the setting unless you know how it works
# busuanzi count for PV / UV in site
# 訪問人數
busuanzi:
site_uv: true
site_pv: true
page_pv: true
# Time difference between publish date and now (網頁運行時間)
# Formal: Month/Day/Year Time or Year/Month/Day Time
runtimeshow:
enable: false enable: false
publish_date: post_wordcount: true
min2read: true
# Aside widget - Newest Comments total_wordcount: true
newest_comments:
enable: false
sort_order: # Don't modify the setting unless you know how it works
limit: 6
storage: 10 # unit: mins, save data to localStorage
avatar: true
# Bottom right button (右下角按鈕)
# --------------------------------------
# Conversion between Traditional and Simplified Chinese (簡繁轉換)
translate:
enable: false
# The text of a button
default:
# the language of website (1 - Traditional Chinese/ 2 - Simplified Chinese
defaultEncoding: 2
# Time delay
translateDelay: 0
# The text of the button when the language is Simplified Chinese
msgToTraditionalChinese: '繁'
# The text of the button when the language is Traditional Chinese
msgToSimplifiedChinese: '簡'
# Read Mode (閲讀模式)
readmode: true
# dark mode
darkmode:
enable: true
# Toggle Button to switch dark/light mode
button: true
# Switch dark/light mode automatically (自動切換 dark mode和 light mode)
# autoChangeMode: 1 Following System Settings, if the system doesn't support dark mode, it will switch dark mode between 6 pm to 6 am
# autoChangeMode: 2 Switch dark mode between 6 pm to 6 am
# autoChangeMode: false
autoChangeMode: false
# show scroll percent in scroll-to-top button
rightside_scroll_percent: false
# Don't modify the following settings unless you know how they work (非必要請不要修改 )
# Choose: readmode,translate,darkmode,hideAside,toc,chat,comment
# Don't repeat 不要重複
rightside_item_order:
enable: false
hide: # readmode,translate,darkmode,hideAside
show: # toc,chat,comment
# Lightbox (圖片大圖查看模式) # Lightbox (圖片大圖查看模式)
# -------------------------------------- # --------------------------------------
@@ -772,12 +790,18 @@ rightside_item_order:
medium_zoom: false medium_zoom: false
# fancybox # fancybox
# http://fancyapps.com/fancybox/3/ # https://fancyapps.com/fancybox/
fancybox: true fancybox: true
# Tag Plugins settings (標籤外掛) # Tag Plugins settings (標籤外掛)
# -------------------------------------- # --------------------------------------
# abcjs (樂譜渲染)
# See https://github.com/paulrosen/abcjs
abcjs:
enable: false
per_page: true
# mermaid # mermaid
# see https://github.com/mermaid-js/mermaid # see https://github.com/mermaid-js/mermaid
mermaid: mermaid:
@@ -896,7 +920,7 @@ CDN:
# when set it to local, you need to install hexo-butterfly-extjs # when set it to local, you need to install hexo-butterfly-extjs
third_party_provider: jsdelivr third_party_provider: jsdelivr
# Add version number to CDN, true or false # Add version number to url, true or false
version: false version: false
# Custom format # Custom format
@@ -910,8 +934,10 @@ CDN:
# translate: # translate:
# local_search: # local_search:
# algolia_js: # algolia_js:
# algolia_search_v4: # algolia_search:
# instantsearch_v4: # instantsearch:
# docsearch_js:
# docsearch_css:
# pjax: # pjax:
# gitalk: # gitalk:
# gitalk_css: # gitalk_css:
@@ -922,6 +948,7 @@ CDN:
# twikoo: # twikoo:
# waline_js: # waline_js:
# waline_css: # waline_css:
# giscus:
# sharejs: # sharejs:
# sharejs_css: # sharejs_css:
# mathjax: # mathjax:
@@ -935,8 +962,8 @@ CDN:
# instantpage: # instantpage:
# typed: # typed:
# pangu: # pangu:
# fancybox_css_v4: # fancybox_css:
# fancybox_v4: # fancybox:
# medium_zoom: # medium_zoom:
# snackbar_css: # snackbar_css:
# snackbar: # snackbar:
@@ -944,7 +971,7 @@ CDN:
# fireworks: # fireworks:
# click_heart: # click_heart:
# ClickShowText: # ClickShowText:
# fontawesomeV6: # fontawesome:
# flickr_justified_gallery_js: # flickr_justified_gallery_js:
# flickr_justified_gallery_css: # flickr_justified_gallery_css:
# aplayer_css: # aplayer_css:
@@ -956,3 +983,4 @@ CDN:
# artalk_js: # artalk_js:
# artalk_css: # artalk_css:
# busuanzi: # busuanzi:
# abcjs_basic_js:

View File

@@ -45,6 +45,7 @@ search:
local_search: local_search:
input_placeholder: Search for Posts input_placeholder: Search for Posts
hits_empty: "We didn't find any results for the search: ${query}" hits_empty: "We didn't find any results for the search: ${query}"
hits_stats: '${hits} results found'
pagination: pagination:
prev: Previous Post prev: Previous Post

View File

@@ -45,6 +45,7 @@ search:
local_search: local_search:
input_placeholder: Search for Posts input_placeholder: Search for Posts
hits_empty: "We didn't find any results for the search: ${query}" hits_empty: "We didn't find any results for the search: ${query}"
hits_stats: '${hits} results found'
pagination: pagination:
prev: Previous Post prev: Previous Post

View File

@@ -46,6 +46,7 @@ search:
local_search: local_search:
input_placeholder: 搜索文章 input_placeholder: 搜索文章
hits_empty: '找不到您查询的内容:${query}' hits_empty: '找不到您查询的内容:${query}'
hits_stats: '共找到 ${hits} 篇文章'
pagination: pagination:
prev: 上一篇 prev: 上一篇

View File

@@ -46,7 +46,8 @@ search:
local_search: local_search:
input_placeholder: 搜尋文章 input_placeholder: 搜尋文章
hits_empty: '找不到您查詢的內容:${query}' hits_empty: '找不到您查詢的內容:${query}'
hits_stats: '共找到 ${hits} 篇文章'
pagination: pagination:
prev: 上一篇 prev: 上一篇
next: 下一篇 next: 下一篇

View File

@@ -8,7 +8,7 @@ div
if theme.medium_zoom if theme.medium_zoom
script(src=url_for(theme.asset.medium_zoom)) script(src=url_for(theme.asset.medium_zoom))
else if theme.fancybox else if theme.fancybox
script(src=url_for(theme.asset.fancybox_v4)) 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')
@@ -22,14 +22,6 @@ div
if theme.pangu.enable if theme.pangu.enable
!= partial("includes/third-party/pangu.pug", {}, { cache: true }) != partial("includes/third-party/pangu.pug", {}, { cache: true })
//- search
if theme.algolia_search.enable
script(src=url_for(theme.asset.algolia_search_v4))
script(src=url_for(theme.asset.instantsearch_v4))
script(src=url_for(theme.asset.algolia_js))
else if theme.local_search.enable
script(src=url_for(theme.asset.local_search))
.js-pjax .js-pjax
if needLoadCountJs if needLoadCountJs
!= partial("includes/third-party/card-post-count/index", {}, { cache: true }) != partial("includes/third-party/card-post-count/index", {}, { cache: true })
@@ -39,6 +31,8 @@ div
include ./third-party/math/index.pug include ./third-party/math/index.pug
include ./third-party/abcjs/index.pug
if commentsJsLoad if commentsJsLoad
include ./third-party/comments/js.pug include ./third-party/comments/js.pug
@@ -67,3 +61,5 @@ div
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')
!=partial('includes/third-party/search/index', {}, {cache: true})

View File

@@ -15,7 +15,7 @@
meta(charset='UTF-8') meta(charset='UTF-8')
meta(http-equiv="X-UA-Compatible" content="IE=edge") meta(http-equiv="X-UA-Compatible" content="IE=edge")
meta(name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0") meta(name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover")
title= tabTitle title= tabTitle
meta(name="author" content=pageAuthor) meta(name="author" content=pageAuthor)
meta(name="copyright" content=pageCopyright) meta(name="copyright" content=pageCopyright)
@@ -40,13 +40,13 @@ if (theme.pwa && theme.pwa.enable)
//- main css //- main css
link(rel='stylesheet', href=url_for(theme.asset.main_css)) link(rel='stylesheet', href=url_for(theme.asset.main_css))
link(rel='stylesheet', href=url_for(theme.asset.fontawesomeV6) media="print" onload="this.media='all'") link(rel='stylesheet', href=url_for(theme.asset.fontawesome) media="print" onload="this.media='all'")
if (theme.snackbar && theme.snackbar.enable) if (theme.snackbar && theme.snackbar.enable)
link(rel='stylesheet', href=url_for(theme.asset.snackbar_css) media="print" onload="this.media='all'") link(rel='stylesheet', href=url_for(theme.asset.snackbar_css) media="print" onload="this.media='all'")
if theme.fancybox if theme.fancybox
link(rel='stylesheet' href=url_for(theme.asset.fancybox_css_v4) media="print" onload="this.media='all'") link(rel='stylesheet' href=url_for(theme.asset.fancybox_css) media="print" onload="this.media='all'")
//- google_adsense //- google_adsense
!=partial('includes/head/google_adsense', {}, {cache: true}) !=partial('includes/head/google_adsense', {}, {cache: true})
@@ -66,4 +66,4 @@ include ./head/noscript.pug
!=fragment_cache('injectHeadJs', function(){return inject_head_js()}) !=fragment_cache('injectHeadJs', function(){return inject_head_js()})
!=fragment_cache('injectHead', function(){return injectHtml(theme.inject.head)}) !=fragment_cache('injectHead', function(){return injectHtml(theme.inject.head)})

View File

@@ -21,9 +21,12 @@
localSearch = JSON.stringify({ localSearch = JSON.stringify({
path: theme.local_search.CDN ? theme.local_search.CDN : config.root + config.search.path, path: theme.local_search.CDN ? theme.local_search.CDN : config.root + config.search.path,
preload: theme.local_search.preload, preload: theme.local_search.preload,
top_n_per_article: theme.local_search.top_n_per_article,
unescape: theme.local_search.unescape,
languages: { languages: {
// search languages // search languages
hits_empty: _p("search.local_search.hits_empty"), hits_empty: _p("search.local_search.hits_empty"),
hits_stats: _p("search.local_search.hits_stats"),
} }
}) })
} }
@@ -85,7 +88,7 @@
} }
script. script.
const GLOBAL_CONFIG = { const GLOBAL_CONFIG = {
root: '!{config.root}', root: '!{config.root}',
algolia: !{algolia}, algolia: !{algolia},
localSearch: !{localSearch}, localSearch: !{localSearch},
@@ -102,7 +105,7 @@ script.
post: !{theme.post_meta.post.date_format === 'relative'} post: !{theme.post_meta.post.date_format === 'relative'}
}, },
runtime: '!{theme.runtimeshow.enable ? _p("aside.card_webinfo.runtime.unit") : ""}', runtime: '!{theme.runtimeshow.enable ? _p("aside.card_webinfo.runtime.unit") : ""}',
date_suffix: { dateSuffix: {
just: '!{_p("date_suffix.just")}', just: '!{_p("date_suffix.just")}',
min: '!{_p("date_suffix.min")}', min: '!{_p("date_suffix.min")}',
hour: '!{_p("date_suffix.hour")}', hour: '!{_p("date_suffix.hour")}',
@@ -124,5 +127,6 @@ script.
percent: { percent: {
toc: !{theme.toc.scroll_percent}, toc: !{theme.toc.scroll_percent},
rightside: !{theme.rightside_scroll_percent}, rightside: !{theme.rightside_scroll_percent},
} },
autoDarkmode: !{theme.darkmode.enable && theme.darkmode.autoChangeMode === 1}
} }

View File

@@ -44,7 +44,7 @@ header#page-header(class=`${isHomeClass+isFixedClass}` style=bg_img)
span#subtitle span#subtitle
if(theme.social) if(theme.social)
#site_social_icons #site_social_icons
!=fragment_cache('social', function(){return partial('includes/header/social')}) !=partial('includes/header/social', {}, {cache: true})
#scroll-down #scroll-down
i.fas.fa-angle-down.scroll-down-effects i.fas.fa-angle-down.scroll-down-effects
else else

View File

@@ -7,7 +7,7 @@ nav#nav
span.site-name=config.title span.site-name=config.title
#menus #menus
if (theme.algolia_search.enable || theme.local_search.enable) if (theme.algolia_search.enable || theme.local_search.enable || theme.docsearch.enable)
#search-button #search-button
a.site-page.social-icon.search(href="javascript:void(0);") a.site-page.social-icon.search(href="javascript:void(0);")
i.fas.fa-search.fa-fw i.fas.fa-search.fa-fw

View File

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

View File

@@ -44,5 +44,4 @@ html(lang=config.language data-theme=theme.display_mode class=htmlClassHideAside
include ./404.pug include ./404.pug
include ./rightside.pug include ./rightside.pug
!=partial('includes/third-party/search/index', {}, {cache: true})
include ./additional-js.pug include ./additional-js.pug

View File

@@ -9,20 +9,25 @@
.loading-word= _p('loading') .loading-word= _p('loading')
script. script.
const preloader = { (()=>{
endLoading: () => { const $loadingBox = document.getElementById('loading-box')
document.body.style.overflow = 'auto'; const $body = document.body
document.getElementById('loading-box').classList.add("loaded") const preloader = {
}, endLoading: () => {
initLoading: () => { $body.style.overflow = ''
document.body.style.overflow = ''; $loadingBox.classList.add('loaded')
document.getElementById('loading-box').classList.remove("loaded") },
initLoading: () => {
$body.style.overflow = 'hidden'
$loadingBox.classList.remove('loaded')
}
} }
}
window.addEventListener('load',()=> { preloader.endLoading() })
if (!{theme.pjax && theme.pjax.enable}) { preloader.initLoading()
document.addEventListener('pjax:send', () => { preloader.initLoading() }) window.addEventListener('load',() => { preloader.endLoading() })
document.addEventListener('pjax:complete', () => { preloader.endLoading() })
} if (!{theme.pjax && theme.pjax.enable}) {
document.addEventListener('pjax:send', () => { preloader.initLoading() })
document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}
})()

View File

@@ -1,2 +1,11 @@
script.
window.paceOptions = {
restartOnPushState: false
}
document.addEventListener('pjax:send', () => {
Pace.restart()
})
link(rel="stylesheet", href=url_for(theme.preloader.pace_css_url || theme.asset.pace_default_css)) link(rel="stylesheet", href=url_for(theme.preloader.pace_css_url || theme.asset.pace_default_css))
script(src=url_for(theme.asset.pace_js)) script(src=url_for(theme.asset.pace_js))

View File

@@ -70,7 +70,7 @@ mixin postUI(posts)
block block
span.article-meta-label= ' ' + _p('card_post_count') span.article-meta-label= ' ' + _p('card_post_count')
if theme.comments.card_post_count if theme.comments.card_post_count && theme.comments.use
case theme.comments.use[0] case theme.comments.use[0]
when 'Disqus' when 'Disqus'
+countBlockInIndex +countBlockInIndex
@@ -89,7 +89,7 @@ mixin postUI(posts)
when 'Waline' when 'Waline'
+countBlockInIndex +countBlockInIndex
a(href=url_for(link) + '#post-comment') a(href=url_for(link) + '#post-comment')
span.waline-comment-count(id=url_for(link)) span.waline-comment-count(data-path=url_for(link))
i.fa-solid.fa-spinner.fa-spin i.fa-solid.fa-spinner.fa-spin
when 'Twikoo' when 'Twikoo'
+countBlockInIndex +countBlockInIndex

View File

@@ -1,7 +1,10 @@
#article-container #article-container
.flink .flink
- let pageContent = page.content - let { content, random, flink_url } = page
if page.flink_url - let pageContent = content
if flink_url || random
- const linkData = flink_url ? false : site.data.link || false
script. script.
(()=>{ (()=>{
const replaceSymbol = (str) => { const replaceSymbol = (str) => {
@@ -9,35 +12,45 @@
} }
let result = "" let result = ""
fetch("!{url_for(page.flink_url)}") const add = (str) => {
.then(response => response.json()) for(let i = 0; i < str.length; i++){
.then(str => { const replaceClassName = replaceSymbol(str[i].class_name)
for(let i = 0; i < str.length; i++){ const className = str[i].class_name ? `<h2 id="${replaceClassName}"><a href="#${replaceClassName}" class="headerlink" title="${str[i].class_name}"></a>${str[i].class_name}</h2>` : ""
const replaceClassName = replaceSymbol(str[i].class_name) const classDesc = str[i].class_desc ? `<div class="flink-desc">${str[i].class_desc}</div>` : ""
const className = str[i].class_name ? `<h2 id="${replaceClassName}"><a href="#${replaceClassName}" class="headerlink" title="${str[i].class_name}"></a>${str[i].class_name}</h2>` : ""
const classDesc = str[i].class_desc ? `<div class="flink-desc">${str[i].class_desc}</div>` : ""
let listResult = ""
const lists = str[i].link_list
for(let j = 0; j < lists.length; j++){
listResult += `
<div class="flink-list-item">
<a href="${lists[j].link}" title="${lists[j].name}" target="_blank">
<div class="flink-item-icon">
<img class="no-lightbox" src="${lists[j].avatar}" onerror='this.onerror=null;this.src="!{url_for(theme.error_img.flink)}"' alt="${lists[j].name}" />
</div>
<div class="flink-item-name">${lists[j].name}</div>
<div class="flink-item-desc" title="${lists[j].descr}">${lists[j].descr}</div>
</a>
</div>`
}
result += `${className}${classDesc} <div class="flink-list">${listResult}</div>` let listResult = ""
const lists = str[i].link_list
if (!{random === true}) {
lists.sort(() => Math.random() - 0.5)
}
for(let j = 0; j < lists.length; j++){
listResult += `
<div class="flink-list-item">
<a href="${lists[j].link}" title="${lists[j].name}" target="_blank">
<div class="flink-item-icon">
<img class="no-lightbox" src="${lists[j].avatar}" onerror='this.onerror=null;this.src="!{url_for(theme.error_img.flink)}"' alt="${lists[j].name}" />
</div>
<div class="flink-item-name">${lists[j].name}</div>
<div class="flink-item-desc" title="${lists[j].descr}">${lists[j].descr}</div>
</a>
</div>`
} }
document.querySelector(".flink").insertAdjacentHTML("afterbegin", result) result += `${className}${classDesc} <div class="flink-list">${listResult}</div>`
window.lazyLoadInstance && window.lazyLoadInstance.update() }
})
document.querySelector(".flink").insertAdjacentHTML("afterbegin", result)
window.lazyLoadInstance && window.lazyLoadInstance.update()
}
const linkData = !{JSON.stringify(linkData)}
if (!{Boolean(flink_url)}) {
fetch("!{url_for(flink_url)}")
.then(response => response.json())
.then(add)
} else if (linkData) {
add(linkData)
}
})() })()
else else
@@ -67,4 +80,3 @@
- pageContent = result + pageContent - pageContent = result + pageContent
!= pageContent != pageContent

View File

@@ -1,2 +1,2 @@
.tag-cloud-list.is-center .tag-cloud-list.is-center
!=cloudTags({source: site.tags, minfontsize: 1.2, maxfontsize: 2.1, limit: 0, unit: 'em'}) !=cloudTags({source: site.tags, orderby: page.orderby || 'random', order: page.order || 1, minfontsize: 1.2, maxfontsize: 2.1, limit: 0, unit: 'em'})

View File

@@ -23,7 +23,7 @@ mixin rightsideItem(array)
i.fas.fa-list-ul i.fas.fa-list-ul
when 'chat' when 'chat'
if chat_btn if chat_btn
button#chat_btn(type="button" title=_p("rightside.chat")) button#chat-btn(type="button" title=_p("rightside.chat"))
i.fas.fa-sms i.fas.fa-sms
when 'comment' when 'comment'
if commentsJsLoad if commentsJsLoad

View File

@@ -14,5 +14,5 @@
.headline= _p('aside.categories') .headline= _p('aside.categories')
.length-num= site.categories.length .length-num= site.categories.length
hr hr.custom-hr
!=partial('includes/header/menu_item', {}, {cache: true}) !=partial('includes/header/menu_item', {}, {cache: true})

View File

@@ -0,0 +1,15 @@
script.
(() => {
function abcjsInit() {
function abcjsFn() {
for (let abcContainer of document.getElementsByClassName("abc-music-sheet")) {
ABCJS.renderAbc(abcContainer, abcContainer.innerHTML, {responsive: 'resize'})
}
}
typeof ABCJS === 'object' ? abcjsFn()
: getScript('!{url_for(theme.asset.abcjs_basic_js)}').then(abcjsFn)
}
window.pjax ? abcjsInit() : document.addEventListener('DOMContentLoaded', abcjsInit)
})()

View File

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

View File

@@ -2,19 +2,34 @@
script. script.
(() => { (() => {
const getArtalkCount = () => { const getArtalkCount = async() => {
const runWidget = () => { try {
Artalk.LoadCountWidget({ const eleGroup = document.querySelectorAll('#recent-posts .artalk-count')
server: '!{server}', const keyArray = Array.from(eleGroup).map(i => i.getAttribute('data-page-key'))
site: '!{site}',
countEl: '.artalk-count' const headerList = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Origin': window.location.origin
},
body: new URLSearchParams({
'site_name': '!{site}',
'type':'page_comment',
'page_keys': keyArray
})
}
const res = await fetch('!{server}/api/stat', headerList)
const result = await res.json()
keyArray.forEach((key, index) => {
eleGroup[index].textContent = result.data[key] || 0
}) })
} catch (err) {
console.error(err)
} }
if (typeof Artalk === 'function') runWidget()
else getScript('!{theme.asset.artalk_js}').then(runWidget)
} }
window.pjax ? getArtalkCount() : window.addEventListener('load', getArtalkCount) window.pjax ? getArtalkCount() : window.addEventListener('load', getArtalkCount)
})() })()

View File

@@ -1,4 +1,4 @@
- const fbSDKVer = 'v15.0' - const fbSDKVer = 'v16.0'
- const fbSDK = theme.messenger.enable ? `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 = theme.messenger.enable ? `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}`
script. script.

View File

@@ -18,7 +18,7 @@ script.
includeReply: false includeReply: false
}).then(function (res) { }).then(function (res) {
document.querySelectorAll('#recent-posts .twikoo-count').forEach((item,index) => { document.querySelectorAll('#recent-posts .twikoo-count').forEach((item,index) => {
item.innerText = res[index].count item.textContent = res[index].count
}) })
}).catch(function (err) { }).catch(function (err) {
console.log(err) console.log(err)

View File

@@ -1,17 +1,19 @@
script. script.
(() => { (() => {
function loadWaline () { async function loadWaline () {
function initWaline () { try {
let initData = { const eleGroup = document.querySelectorAll('#recent-posts .waline-comment-count')
el: null, const keyArray = Array.from(eleGroup).map(i => i.getAttribute('data-path'))
serverURL: '!{theme.waline.serverURL}',
comment: true
}
const waline = Waline.init(initData)
}
if (typeof Waline === 'object') initWaline() const res = await fetch(`!{theme.waline.serverURL}/api/comment?type=count&url=${keyArray}`, { method: 'GET' })
else getScript('!{url_for(theme.asset.waline_js)}').then(initWaline) const result = await res.json()
result.data.forEach((count, index) => {
eleGroup[index].textContent = count
})
} catch (err) {
console.error(err)
}
} }
window.pjax ? loadWaline() : window.addEventListener('load', loadWaline) window.pjax ? loadWaline() : window.addEventListener('load', loadWaline)

View File

@@ -1,33 +1,50 @@
//- https://chatra.io/help/api/ //- https://chatra.io/help/api/
script. script.
(function(d, w, c) { (() => {
w.ChatraID = '#{theme.chatra.id}'; const isChatBtn = !{theme.chat_btn}
var s = d.createElement('script'); const isChatHideShow = !{theme.chat_hide_show}
w[c] = w[c] || function() {
(w[c].q = w[c].q || []).push(arguments);
};
s.async = true;
s.src = 'https://call.chatra.io/chatra.js';
if (d.head) d.head.appendChild(s);
})(document, window, 'Chatra');
if (!{theme.chat_btn}) { if (isChatBtn) {
var chatBtnFn = () => { const close = () => {
var chatBtn = document.getElementById("chat_btn") Chatra('minimizeWidget')
chatBtn.addEventListener("click", function(){
Chatra('openChat')
});
}
chatBtnFn()
} else {
if (!{theme.chat_hide_show}) {
function chatBtnHide () {
Chatra('hide') Chatra('hide')
} }
function chatBtnShow () {
const open = () => {
Chatra('openChat', true)
Chatra('show') Chatra('show')
} }
window.ChatraSetup = {
startHidden: true
}
window.chatBtnFn = () => {
const isShow = document.getElementById('chatra').classList.contains('chatra--expanded')
isShow ? close() : open()
}
} else if (isChatHideShow) {
window.chatBtn = {
hide: () => {
Chatra('hide')
},
show: () => {
Chatra('show')
}
}
} }
}
(function(d, w, c) {
w.ChatraID = '#{theme.chatra.id}'
var s = d.createElement('script')
w[c] = w[c] || function() {
(w[c].q = w[c].q || []).push(arguments)
}
s.async = true
s.src = 'https://call.chatra.io/chatra.js'
if (d.head) d.head.appendChild(s)
})(document, window, 'Chatra')
})()

View File

@@ -1,36 +1,45 @@
script. script.
window.$crisp = []; (() => {
window.CRISP_WEBSITE_ID = "!{theme.crisp.website_id}"; window.$crisp = [];
(function () { window.CRISP_WEBSITE_ID = "!{theme.crisp.website_id}";
d = document; (function () {
s = d.createElement("script"); d = document;
s.src = "https://client.crisp.chat/l.js"; s = d.createElement("script");
s.async = 1; s.src = "https://client.crisp.chat/l.js";
d.getElementsByTagName("head")[0].appendChild(s); s.async = 1;
})(); d.getElementsByTagName("head")[0].appendChild(s);
$crisp.push(["safe", true]) })();
$crisp.push(["safe", true])
if (!{theme.chat_btn}) { const isChatBtn = !{theme.chat_btn}
$crisp.push(["do", "chat:hide"]) const isChatHideShow = !{theme.chat_hide_show}
$crisp.push(["on", "chat:closed", function() {
$crisp.push(["do", "chat:hide"]) if (isChatBtn) {
}]) const open = () => {
var chatBtnFn = () => {
var chatBtn = document.getElementById("chat_btn")
chatBtn.addEventListener("click", function(){
$crisp.push(["do", "chat:show"]) $crisp.push(["do", "chat:show"])
$crisp.push(["do", "chat:open"]) $crisp.push(["do", "chat:open"])
}
}); const close = () => {
}
chatBtnFn()
} else {
if (!{theme.chat_hide_show}) {
function chatBtnHide () {
$crisp.push(["do", "chat:hide"]) $crisp.push(["do", "chat:hide"])
} }
function chatBtnShow () {
$crisp.push(["do", "chat:show"]) close()
$crisp.push(["on", "chat:closed", function() {
close()
}])
window.chatBtnFn = () => {
$crisp.is("chat:visible") ? close() : open()
}
} else if (isChatHideShow) {
window.chatBtn = {
hide: () => {
$crisp.push(["do", "chat:hide"])
},
show: () => {
$crisp.push(["do", "chat:show"])
}
} }
} }
} })()

View File

@@ -1,40 +1,40 @@
//- https://guide.daocloud.io/daovoice/javascript-api-5869833.html //- https://guide.daocloud.io/daovoice/javascript-api-5869833.html
script. script.
(function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/!{theme.daovoice.app_id}.js","daovoice") (() => {
(function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/!{theme.daovoice.app_id}.js","daovoice")
script. const isChatBtn = !{theme.chat_btn}
var isChatBtn = !{theme.chat_btn} const isChatHideShow = !{theme.chat_hide_show}
daovoice('init', {
app_id: '!{theme.daovoice.app_id}',},{
launcher: {
disableLauncherIcon: isChatBtn // 悬浮 ICON 是否显示
},
});
daovoice('update');
if (isChatBtn) { daovoice('init', {
var chatBtnFn = () => { app_id: '!{theme.daovoice.app_id}',},{
var chatBtn = document.getElementById("chat_btn") launcher: {
chatBtn.addEventListener("click", function(){ disableLauncherIcon: isChatBtn
daovoice('show') },
}); });
} daovoice('update');
chatBtnFn()
} else { if (isChatBtn) {
if (!{theme.chat_hide_show}) { window.chatBtnFn = () => {
function chatBtnHide () { const isShow = document.getElementById('daodream-messenger').classList.contains('daodream-messenger-active')
daovoice('update', {},{ isShow ? daovoice('hide') : daovoice('show')
launcher: {
disableLauncherIcon: true // 悬浮 ICON 是否显示
},
});
} }
function chatBtnShow () { } else if (isChatHideShow) {
daovoice('update', {},{ window.chatBtn = {
launcher: { hide: () => {
disableLauncherIcon: false // 悬浮 ICON 是否显示 daovoice('update', {},{
}, launcher: {
}); disableLauncherIcon: true
}
})
},
show: () => {
daovoice('update', {}, {
launcher: {
disableLauncherIcon: false
}
})
}
} }
} }
} })()

View File

@@ -1,43 +0,0 @@
if theme.chat_btn
script.
((window.gitter = {}).chat = {}).options = {
disableDefaultChat: true,
};
document.addEventListener('gitter-sidecar-ready', (e) => {
const GitterChat = e.detail.Chat
let chat
function initGitter () {
chat = new GitterChat({
room: '#{theme.gitter.room}',
activationElement: '#chat_btn'
});
}
initGitter()
if (!{theme.pjax.enable}) {
document.addEventListener('pjax:complete', () => {
chat.destroy()
initGitter()
})
}
})
else
script.
((window.gitter = {}).chat = {}).options = {
room: '#{theme.gitter.room}',
};
if (!{theme.chat_hide_show}) {
function chatBtnHide () {
document.getElementsByClassName('gitter-open-chat-button')[0].style.display= 'none'
}
function chatBtnShow () {
document.getElementsByClassName('gitter-open-chat-button')[0].style.display= 'block'
}
}
script(src="https://sidecar.gitter.im/dist/sidecar.v1.js" async defer)

View File

@@ -4,8 +4,6 @@ else if theme.tidio && theme.tidio.enable
include ./tidio.pug include ./tidio.pug
else if theme.daovoice && theme.daovoice.enable else if theme.daovoice && theme.daovoice.enable
include ./daovoice.pug include ./daovoice.pug
else if theme.gitter && theme.gitter.enable
include ./gitter.pug
else if theme.crisp && theme.crisp.enable else if theme.crisp && theme.crisp.enable
include ./crisp.pug include ./crisp.pug
else if theme.messenger && theme.messenger.enable else if theme.messenger && theme.messenger.enable

View File

@@ -4,39 +4,41 @@
#fb-customer-chat.fb-customerchat(page_id=pageID attribution='biz_inbox') #fb-customer-chat.fb-customerchat(page_id=pageID attribution='biz_inbox')
script. script.
document.getElementById('fb-root') ? '' : document.body.insertAdjacentHTML('afterend', '<div id="fb-root"></div>') (() => {
document.getElementById('fb-root') ? '' : document.body.insertAdjacentHTML('afterend', '<div id="fb-root"></div>')
window.fbAsyncInit = function() { window.fbAsyncInit = function() {
FB.init({ FB.init({
xfbml: true, xfbml: true,
version: 'v15.0' 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'));
if (!{theme.chat_btn}) {
var chatBtnFn = () => {
var chatBtn = document.getElementById("chat_btn")
chatBtn.addEventListener("click", function(){
FB.CustomerChat.show();
}); });
} };
chatBtnFn()
} else { (function(d, s, id) {
if (!{theme.chat_hide_show}) { var js, fjs = d.getElementsByTagName(s)[0];
function chatBtnHide () { if (d.getElementById(id)) return;
FB.CustomerChat.hide() js = d.createElement(s); js.id = id;
} js.src = 'https://connect.facebook.net/!{lang}/sdk/xfbml.customerchat.js';
function chatBtnShow () { fjs.parentNode.insertBefore(js, fjs);
FB.CustomerChat.show(false) }(document, 'script', 'facebook-jssdk'));
}
} const isChatBtn = !{theme.chat_btn}
} const isChatHideShow = !{theme.chat_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)
}
}
}
})()

View File

@@ -1,41 +1,45 @@
script(src=`//code.tidio.co/${theme.tidio.public_key}.js` async) script(src=`//code.tidio.co/${theme.tidio.public_key}.js` async)
script.
(() => {
const isChatBtn = !{theme.chat_btn}
const isChatHideShow = !{theme.chat_hide_show}
if theme.chat_btn if (isChatBtn) {
script. let isShow = false
function onTidioChatApiReady() { const close = () => {
window.tidioChatApi.hide(); window.tidioChatApi.hide()
window.tidioChatApi.on("close", function() { isShow = false
window.tidioChatApi.hide(); }
});
} const open = () => {
if (window.tidioChatApi) { window.tidioChatApi.open()
window.tidioChatApi.on("ready", onTidioChatApiReady); window.tidioChatApi.show()
} else { isShow = true
document.addEventListener("tidioChat-ready", onTidioChatApiReady); }
}
var chatBtnFn = () => { const onTidioChatApiReady = () => {
document.getElementById("chat_btn").addEventListener("click", function(){ window.tidioChatApi.hide()
window.tidioChatApi.show(); window.tidioChatApi.on("close", close)
window.tidioChatApi.open(); }
});
}
chatBtnFn()
else if theme.chat_hide_show
script.
function chatBtnHide () {
if (window.tidioChatApi) { if (window.tidioChatApi) {
//- window.tidioChatApi.hide(); window.tidioChatApi.on("ready", onTidioChatApiReady)
document.getElementById('tidio-chat').style.display= 'none' } else {
document.addEventListener("tidioChat-ready", onTidioChatApiReady)
}
window.chatBtnFn = () => {
if (!window.tidioChatApi) return
isShow ? close() : open()
}
} else if (isChatHideShow) {
window.chatBtn = {
hide: () => {
window.tidioChatApi && window.tidioChatApi.hide()
},
show: () => {
window.tidioChatApi && window.tidioChatApi.show()
}
} }
} }
})()
function chatBtnShow () {
if (window.tidioChatApi) {
//- window.tidioChatApi.show();
document.getElementById('tidio-chat').style.display= 'block'
}
}

View File

@@ -11,22 +11,34 @@ script.
darkMode: document.documentElement.getAttribute('data-theme') === 'dark', darkMode: document.documentElement.getAttribute('data-theme') === 'dark',
countEl: '.artalk-count' countEl: '.artalk-count'
},!{JSON.stringify(option)})) },!{JSON.stringify(option)}))
if (GLOBAL_CONFIG.lightbox === 'null') return
window.artalkItem.use(ctx => {
ctx.on('list-loaded', () => {
ctx.getCommentList().forEach(comment => {
const $content = comment.getRender().$content
btf.loadLightbox($content.querySelectorAll('img:not([atk-emoticon])'))
})
})
})
} }
if (typeof window.artalkItem === 'object') setTimeout(()=>{initArtalk()},200) if (typeof window.artalkItem === 'object') initArtalk()
else { else {
getCSS('!{theme.asset.artalk_css}') getCSS('!{theme.asset.artalk_css}').then(()=>{
typeof Artalk !== 'function' ? getScript('!{theme.asset.artalk_js}').then(initArtalk) getScript('!{theme.asset.artalk_js}').then(initArtalk)
: setTimeout(()=>{initArtalk()},200) })
} }
} }
document.getElementById('darkmode').addEventListener('click',()=> { function artalkChangeMode (theme) {
if (typeof window.artalkItem !== 'object') return const artalkWrap = document.getElementById('artalk-wrap')
let isDark = document.documentElement.getAttribute('data-theme') === 'dark' if (!(artalkWrap && artalkWrap.children.length)) return
window.artalkItem.setDarkMode(!isDark) const isDark = theme === 'dark'
}) window.artalkItem.setDarkMode(isDark)
}
btf.addModeChange('artalk', artalkChangeMode)
if ('!{theme.comments.use[0]}' === 'Artalk' || !!{theme.comments.lazyload}) { if ('!{theme.comments.use[0]}' === 'Artalk' || !!{theme.comments.lazyload}) {
if (!{theme.comments.lazyload}) btf.loadComment(document.getElementById('artalk-wrap'), loadArtalk) if (!{theme.comments.lazyload}) btf.loadComment(document.getElementById('artalk-wrap'), loadArtalk)

View File

@@ -2,19 +2,21 @@
script. script.
function loadDisqus () { function loadDisqus () {
var disqus_config = function () { const disqus_config = function () {
this.page.url = '!{ page.permalink }' this.page.url = '!{ page.permalink }'
this.page.identifier = '!{ url_for(page.path) }' this.page.identifier = '!{ url_for(page.path) }'
this.page.title = '!{ disqusPageTitle }' this.page.title = '!{ disqusPageTitle }'
}; }
window.disqusReset = () => { const disqusReset = () => {
DISQUS.reset({ DISQUS.reset({
reload: true, reload: true,
config: disqus_config config: disqus_config
}) })
} }
btf.addModeChange('disqus', disqusReset)
if (window.DISQUS) disqusReset() if (window.DISQUS) disqusReset()
else { else {
(function() { (function() {
@@ -24,10 +26,6 @@ script.
(d.head || d.body).appendChild(s); (d.head || d.body).appendChild(s);
})(); })();
} }
document.getElementById('darkmode').addEventListener('click', () => {
setTimeout(() => window.disqusReset(), 200)
})
} }
if ('!{theme.comments.use[0]}' === 'Disqus' || !!{theme.comments.lazyload}) { if ('!{theme.comments.use[0]}' === 'Disqus' || !!{theme.comments.lazyload}) {

View File

@@ -23,7 +23,7 @@ script.
} }
document.getElementById('darkmode').addEventListener('click', themeChange) btf.addModeChange('disqusjs', themeChange)
if (window.disqusJsLoad) initDisqusjs() if (window.disqusJsLoad) initDisqusjs()
else { else {

View File

@@ -1,4 +1,4 @@
- const fbSDKVer = 'v15.0' - const fbSDKVer = 'v16.0'
- const fbSDK = theme.messenger.enable ? `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 = theme.messenger.enable ? `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}`
script. script.
@@ -22,9 +22,19 @@ script.
ele.setAttribute('crossorigin', 'anonymous') ele.setAttribute('crossorigin', 'anonymous')
ele.setAttribute('id', 'facebook-jssdk') ele.setAttribute('id', 'facebook-jssdk')
document.getElementById('fb-root').insertAdjacentElement('afterbegin',ele) document.getElementById('fb-root').insertAdjacentElement('afterbegin',ele)
} }
} }
function fbModeChange (theme) {
const $fbComment = document.getElementsByClassName('fb-comments')[0]
if ($fbComment && typeof FB === 'object') {
$fbComment.setAttribute('data-colorscheme',theme)
FB.XFBML.parse(document.getElementById('post-comment'))
}
}
btf.addModeChange('facebook_comments', fbModeChange)
if ('!{theme.comments.use[0]}' === 'Facebook Comments' || !!{theme.comments.lazyload}) { if ('!{theme.comments.use[0]}' === 'Facebook Comments' || !!{theme.comments.lazyload}) {
if (!{theme.comments.lazyload}) btf.loadComment(document.querySelector('#post-comment .fb-comments'), loadFBComment) if (!{theme.comments.lazyload}) btf.loadComment(document.querySelector('#post-comment .fb-comments'), loadFBComment)
else loadFBComment() else loadFBComment()

View File

@@ -1,16 +1,20 @@
- const { repo, repo_id, category_id, option } = theme.giscus - const { repo, repo_id, category_id, theme:themes, option } = theme.giscus
- const themes = theme.giscus.theme - const giscusUrl = theme.asset.giscus || 'https://giscus.app/client.js'
script. - const giscusOriginUrl = new URL(giscusUrl).origin
function loadGiscus () {
let nowTheme = document.documentElement.getAttribute('data-theme') === 'dark' ? '!{themes.dark}' : '!{themes.light}'
script.
function getGiscusTheme (theme) {
return theme === 'dark' ? '!{themes.dark}' : '!{themes.light}'
}
function loadGiscus () {
const config = Object.assign({ const config = Object.assign({
src: 'https://giscus.app/client.js', src: '!{giscusUrl}',
'data-repo': '!{repo}', 'data-repo': '!{repo}',
'data-repo-id': '!{repo_id}', 'data-repo-id': '!{repo_id}',
'data-category-id': '!{category_id}', 'data-category-id': '!{category_id}',
'data-mapping': 'pathname', 'data-mapping': 'pathname',
'data-theme': nowTheme, 'data-theme': getGiscusTheme(document.documentElement.getAttribute('data-theme')),
'data-reactions-enabled': '1', 'data-reactions-enabled': '1',
crossorigin: 'anonymous', crossorigin: 'anonymous',
async: true async: true
@@ -23,22 +27,22 @@ script.
document.getElementById('giscus-wrap').insertAdjacentElement('afterbegin',ele) document.getElementById('giscus-wrap').insertAdjacentElement('afterbegin',ele)
} }
function changeGiscusTheme () { function changeGiscusTheme (theme) {
const theme = document.documentElement.getAttribute('data-theme') === 'dark' ? '!{themes.dark}' : '!{themes.light}'
function sendMessage(message) { function sendMessage(message) {
const iframe = document.querySelector('iframe.giscus-frame'); const iframe = document.querySelector('iframe.giscus-frame')
if (!iframe) return; if (!iframe) return
iframe.contentWindow.postMessage({ giscus: message }, 'https://giscus.app'); iframe.contentWindow.postMessage({ giscus: message }, '!{giscusOriginUrl}')
} }
sendMessage({ sendMessage({
setConfig: { setConfig: {
theme: theme theme: getGiscusTheme(theme)
} }
}); });
} }
btf.addModeChange('giscus', changeGiscusTheme)
if ('!{theme.comments.use[0]}' === 'Giscus' || !!{theme.comments.lazyload}) { if ('!{theme.comments.use[0]}' === 'Giscus' || !!{theme.comments.lazyload}) {
if (!{theme.comments.lazyload}) btf.loadComment(document.getElementById('giscus-wrap'), loadGiscus) if (!{theme.comments.lazyload}) btf.loadComment(document.getElementById('giscus-wrap'), loadGiscus)
else loadGiscus() else loadGiscus()

View File

@@ -24,7 +24,7 @@ script.
function commentCount(n){ function commentCount(n){
let isCommentCount = document.querySelector('#post-meta .gitalk-comment-count') let isCommentCount = document.querySelector('#post-meta .gitalk-comment-count')
if (isCommentCount) { if (isCommentCount) {
isCommentCount.innerHTML= n isCommentCount.textContent= n
} }
} }

View File

@@ -1,5 +1,5 @@
- let defaultComment = theme.comments.use[0] - let defaultComment = theme.comments.use[0]
hr hr.custom-hr
#post-comment #post-comment
.comment-head .comment-head
.comment-headline .comment-headline

View File

@@ -51,11 +51,12 @@ script.
} }
} }
document.getElementById('darkmode').addEventListener('click',()=>{ function remarkChangeMode (theme) {
if (!window.REMARK42) return if (!window.REMARK42) return
let theme = document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark'
window.REMARK42.changeTheme(theme) window.REMARK42.changeTheme(theme)
}) }
btf.addModeChange('remark42', remarkChangeMode)
if ('!{theme.comments.use[0]}' === 'Remark42' || !!{theme.comments.lazyload}) { if ('!{theme.comments.use[0]}' === 'Remark42' || !!{theme.comments.lazyload}) {
if (!{theme.comments.lazyload}) btf.loadComment(document.getElementById('remark42'), loadRemark42) if (!{theme.comments.lazyload}) btf.loadComment(document.getElementById('remark42'), loadRemark42)

View File

@@ -23,7 +23,7 @@ script.
urls: [window.location.pathname], urls: [window.location.pathname],
includeReply: false includeReply: false
}).then(function (res) { }).then(function (res) {
countELement.innerText = res[0].count countELement.textContent = res[0].count
}).catch(function (err) { }).catch(function (err) {
console.error(err); console.error(err);
}); });

View File

@@ -12,10 +12,10 @@ script.
document.getElementById('utterances-wrap').insertAdjacentElement('afterbegin',ele) document.getElementById('utterances-wrap').insertAdjacentElement('afterbegin',ele)
} }
function utterancesTheme () { function utterancesTheme (theme) {
const iframe = document.querySelector('.utterances-frame') const iframe = document.querySelector('.utterances-frame')
if (iframe) { if (iframe) {
const theme = document.documentElement.getAttribute('data-theme') === 'dark' ? '#{theme.utterances.dark_theme}' : '#{theme.utterances.light_theme}' const theme = theme === 'dark' ? '#{theme.utterances.dark_theme}' : '#{theme.utterances.light_theme}'
const message = { const message = {
type: 'set-theme', type: 'set-theme',
theme: theme theme: theme
@@ -24,6 +24,8 @@ script.
} }
} }
btf.addModeChange('utterances', utterancesTheme)
if ('!{theme.comments.use[0]}' === 'Utterances' || !!{theme.comments.lazyload}) { if ('!{theme.comments.use[0]}' === 'Utterances' || !!{theme.comments.lazyload}) {
if (!{theme.comments.lazyload}) btf.loadComment(document.getElementById('utterances-wrap'), loadUtterances) if (!{theme.comments.lazyload}) btf.loadComment(document.getElementById('utterances-wrap'), loadUtterances)
else loadUtterances() else loadUtterances()

View File

@@ -3,7 +3,7 @@ script.
if (!window.MathJax) { if (!window.MathJax) {
window.MathJax = { window.MathJax = {
tex: { tex: {
inlineMath: [ ['$','$'], ["\\(","\\)"]], inlineMath: [['$', '$'], ['\\(', '\\)']],
tags: 'ams' tags: 'ams'
}, },
chtml: { chtml: {
@@ -21,16 +21,7 @@ script.
math.end = {node: text, delim: '', n: 0} math.end = {node: text, delim: '', n: 0}
doc.math.push(math) doc.math.push(math)
} }
}, ''], }, '']
insertScript: [200, () => {
document.querySelectorAll('mjx-container').forEach(node => {
if (node.hasAttribute('display')) {
btf.wrap(node, 'div', { class: 'mathjax-overflow' })
} else {
btf.wrap(node, 'span', { class: 'mathjax-overflow' })
}
});
}, '', false]
} }
} }
} }
@@ -43,5 +34,5 @@ script.
} else { } else {
MathJax.startup.document.state(0) MathJax.startup.document.state(0)
MathJax.texReset() MathJax.texReset()
MathJax.typeset() MathJax.typesetPromise()
} }

View File

@@ -1,26 +1,38 @@
script. script.
(() => { (() => {
const $mermaidWrap = document.querySelectorAll('#article-container .mermaid-wrap') const $mermaid = document.querySelectorAll('#article-container .mermaid-wrap')
if ($mermaidWrap.length) { if ($mermaid.length === 0) return
window.runMermaid = () => { const runMermaid = () => {
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($mermaidWrap).forEach((item, index) => { Array.from($mermaid).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
mermaid.mermaidAPI.render(mermaidID, mermaidDefinition, (svgCode) => {
mermaidSrc.insertAdjacentHTML('afterend', svgCode) const renderFn = mermaid.render(mermaidID, mermaidDefinition)
const renderV10 = () => {
renderFn.then(({svg}) => {
mermaidSrc.insertAdjacentHTML('afterend', svg)
}) })
}) }
}
const loadMermaid = () => { const renderV9 = svg => {
window.loadMermaid ? runMermaid() : getScript('!{url_for(theme.asset.mermaid)}').then(runMermaid) mermaidSrc.insertAdjacentHTML('afterend', svg)
} }
window.pjax ? loadMermaid() : document.addEventListener('DOMContentLoaded', loadMermaid) typeof renderFn === 'string' ? renderV9(renderFn) : renderV10()
})
} }
const loadMermaid = () => {
window.loadMermaid ? runMermaid() : getScript('!{url_for(theme.asset.mermaid)}').then(runMermaid)
}
btf.addModeChange('mermaid', runMermaid)
window.pjax ? loadMermaid() : document.addEventListener('DOMContentLoaded', loadMermaid)
})() })()

View File

@@ -1,6 +1,6 @@
- const { server, option } = theme.artalk - const { server, site, option } = theme.artalk
- const avatarCdn = option !== null && option.gravatar ? option.gravatar.mirror : 'https://sdn.geekzu.org/avatar/' - const avatarCdn = option !== null && option.gravatar && option.gravatar.mirror
- const avatarDefault = option !== null && option.gravatar ? option.gravatar.default : 'mp' - const avatarDefault = option !== null && option.gravatar && (option.gravatar.params || option.gravatar.default)
script. script.
window.addEventListener('load', () => { window.addEventListener('load', () => {
@@ -45,25 +45,53 @@ script.
window.pjax && window.pjax.refresh($dom) window.pjax && window.pjax.refresh($dom)
} }
const getComment = () => { const getSetting = async () => {
fetch('!{server}/api/stat?type=latest_comments&limit=!{theme.newest_comments.limit}',{method: "POST"}) try {
.then(response => response.json()) const res = await fetch('!{server}/api/conf', { method: 'GET' })
.then(d => { return await res.json()
const artalk = d.data.map(function (e) { } catch (e) {
return { console.log(e)
'avatar': '!{avatarCdn}' + e.email_encrypted + '?d=!{avatarDefault}', }
'content': changeContent(e.content_marked), }
'nick': e.nick,
'url': e.page_url, const headerList = {
'date': e.date, method: 'POST',
} headers: {
}) 'Content-Type': 'application/x-www-form-urlencoded',
saveToLocal.set('artalk-newest-comments', JSON.stringify(artalk), !{theme.newest_comments.storage}/(60*24)) 'Origin': window.location.origin
generateHtml(artalk) },
}).catch(e => { body: new URLSearchParams({
const $dom = document.querySelector('#card-newest-comments .aside-list') 'site_name': '!{site}',
$dom.innerHTML= "!{_p('aside.card_newest_comments.error')}" 'limit': '!{theme.newest_comments.limit}',
'type':'latest_comments'
})
}
const getComment = async () => {
try {
const res = await fetch('!{server}/api/stat', headerList)
const result = await res.json()
const avatarStr = await getSetting()
const { mirror, params, default:defaults } = avatarStr.data.frontend_conf.gravatar
const avatarCdn = !{avatarCdn} || mirror
let avatarDefault = !{avatarDefault} || params || defaults
avatarDefault = avatarDefault.startsWith('d=') ? avatarDefault : `d=${avatarDefault}`
const artalk = result.data.map(function (e) {
return {
'avatar': `${avatarCdn}${e.email_encrypted}?${avatarDefault}`,
'content': changeContent(e.content_marked),
'nick': e.nick,
'url': e.page_url,
'date': e.date,
}
}) })
saveToLocal.set('artalk-newest-comments', JSON.stringify(artalk), !{theme.newest_comments.storage}/(60*24))
generateHtml(artalk)
} catch (e) {
console.log(e)
const $dom = document.querySelector('#card-newest-comments .aside-list')
$dom.innerHTML= "!{_p('aside.card_newest_comments.error')}"
}
} }
const newestCommentInit = () => { const newestCommentInit = () => {

View File

@@ -32,7 +32,7 @@ script.
generateHtml(disqusArray) generateHtml(disqusArray)
}).catch(e => { }).catch(e => {
const $dom = document.querySelector('#card-newest-comments .aside-list') const $dom = document.querySelector('#card-newest-comments .aside-list')
$dom.innerHTML= "!{_p('aside.card_newest_comments.error')}" $dom.textContent= "!{_p('aside.card_newest_comments.error')}"
}) })
} }

View File

@@ -58,7 +58,7 @@ script.
findTrueUrl(githubArray) findTrueUrl(githubArray)
}).catch(e => { }).catch(e => {
const $dom = document.querySelector('#card-newest-comments .aside-list') const $dom = document.querySelector('#card-newest-comments .aside-list')
$dom.innerHTML= "!{_p('aside.card_newest_comments.error')}" $dom.textContent= "!{_p('aside.card_newest_comments.error')}"
}) })
} }

View File

@@ -60,7 +60,7 @@ script.
generateHtml(remark42) generateHtml(remark42)
}).catch(e => { }).catch(e => {
const $dom = document.querySelector('#card-newest-comments .aside-list') const $dom = document.querySelector('#card-newest-comments .aside-list')
$dom.innerHTML= "!{_p('aside.card_newest_comments.error')}" $dom.textContent= "!{_p('aside.card_newest_comments.error')}"
}) })
} }

View File

@@ -36,7 +36,7 @@ script.
generateHtml(twikooArray) generateHtml(twikooArray)
}).catch(function (err) { }).catch(function (err) {
const $dom = document.querySelector('#card-newest-comments .aside-list') const $dom = document.querySelector('#card-newest-comments .aside-list')
$dom.innerHTML= "!{_p('aside.card_newest_comments.error')}" $dom.textContent= "!{_p('aside.card_newest_comments.error')}"
}) })
} }

View File

@@ -79,7 +79,7 @@ script.
generateHtml(valineArray) generateHtml(valineArray)
}).catch(e => { }).catch(e => {
const $dom = document.querySelector('#card-newest-comments .aside-list') const $dom = document.querySelector('#card-newest-comments .aside-list')
$dom.innerHTML= "!{_p('aside.card_newest_comments.error')}" $dom.textContent= "!{_p('aside.card_newest_comments.error')}"
}) })
} }

View File

@@ -1,6 +1,6 @@
script. script.
window.addEventListener('load', () => { window.addEventListener('load', () => {
const changeContent = (content) => { const changeContent = content => {
if (content === '') return content if (content === '') return content
content = content.replace(/<img.*?src="(.*?)"?[^\>]+>/ig, '[!{_p("aside.card_newest_comments.image")}]') // replace image link content = content.replace(/<img.*?src="(.*?)"?[^\>]+>/ig, '[!{_p("aside.card_newest_comments.image")}]') // replace image link
@@ -41,31 +41,26 @@ script.
window.pjax && window.pjax.refresh($dom) window.pjax && window.pjax.refresh($dom)
} }
const getComment = () => { const getComment = async () => {
const loadWaline = () => { try {
Waline.RecentComments({ const res = await fetch('!{theme.waline.serverURL}/api/comment?type=recent&count=!{theme.newest_comments.limit}', { method: 'GET' })
serverURL: '!{theme.waline.serverURL}', const result = await res.json()
count: !{theme.newest_comments.limit} const walineArray = result.data.map(e => {
}).then(({comments}) => { return {
const walineArray = comments.map(e => { 'content': changeContent(e.comment),
return { 'avatar': e.avatar,
'content': changeContent(e.comment), 'nick': e.nick,
'avatar': e.avatar, 'url': e.url + '#' + e.objectId,
'nick': e.nick, 'date': e.time || e.insertedAt
'url': e.url + '#' + e.objectId, }
'date': e.insertedAt, })
} saveToLocal.set('waline-newest-comments', JSON.stringify(walineArray), !{theme.newest_comments.storage}/(60*24))
}) generateHtml(walineArray)
saveToLocal.set('waline-newest-comments', JSON.stringify(walineArray), !{theme.newest_comments.storage}/(60*24)) } catch (err) {
generateHtml(walineArray) console.error(err)
}).catch(e => { const $dom = document.querySelector('#card-newest-comments .aside-list')
const $dom = document.querySelector('#card-newest-comments .aside-list') $dom.textContent= "!{_p('aside.card_newest_comments.error')}"
$dom.innerHTML= "!{_p('aside.card_newest_comments.error')}"
})
} }
if (typeof Waline === 'object') loadWaline()
else getScript('!{url_for(theme.asset.waline_js)}').then(loadWaline)
} }
const newestCommentInit = () => { const newestCommentInit = () => {

View File

@@ -62,7 +62,6 @@ script.
GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update() GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()
typeof chatBtnFn === 'function' && chatBtnFn()
typeof panguInit === 'function' && panguInit() typeof panguInit === 'function' && panguInit()
// google analytics // google analytics

View File

@@ -16,3 +16,7 @@
.algolia-poweredBy .algolia-poweredBy
#search-mask #search-mask
script(src=url_for(theme.asset.algolia_search))
script(src=url_for(theme.asset.instantsearch))
script(src=url_for(theme.asset.algolia_js))

View File

@@ -0,0 +1,27 @@
- const { appId, apiKey, indexName, option } = theme.docsearch
.docsearch-wrap
#docsearch(style="display:none")
link(rel="stylesheet" href=url_for(theme.asset.docsearch_css))
script(src=url_for(theme.asset.docsearch_js))
script.
(() => {
docsearch(Object.assign({
appId: '!{appId}',
apiKey: '!{apiKey}',
indexName: '!{indexName}',
container: '#docsearch',
}, !{JSON.stringify(option)}))
const searchClickFn = () => {
document.querySelector('#search-button > .search').addEventListener('click', () => {
document.querySelector('.DocSearch-Button').click()
})
}
searchClickFn()
window.addEventListener('pjax:complete', searchClickFn)
})()

View File

@@ -1,4 +1,6 @@
if theme.algolia_search.enable if theme.algolia_search.enable
include ./algolia.pug include ./algolia.pug
else if theme.local_search.enable else if theme.local_search.enable
include ./local-search.pug include ./local-search.pug
else if theme.docsearch.enable
include ./docsearch.pug

View File

@@ -15,6 +15,8 @@
.local-search-box .local-search-box
input(placeholder=_p("search.local_search.input_placeholder") type="text").local-search-box--input input(placeholder=_p("search.local_search.input_placeholder") type="text").local-search-box--input
hr hr
#local-search-results #local-search-results.no-result
#local-search-stats-wrap
#search-mask
#search-mask script(src=url_for(theme.asset.local_search))

View File

@@ -38,7 +38,7 @@ case source
sub.unshift(data.hitokoto, from) sub.unshift(data.hitokoto, from)
typedJSFn.init(sub) typedJSFn.init(sub)
} else { } else {
document.getElementById('subtitle').innerHTML = data.hitokoto document.getElementById('subtitle').textContent = data.hitokoto
} }
}) })
} }
@@ -55,7 +55,7 @@ case source
sub.unshift(con, from) sub.unshift(con, from)
typedJSFn.init(sub) typedJSFn.init(sub)
} else { } else {
document.getElementById('subtitle').innerHTML = con document.getElementById('subtitle').textContent = con
} }
}) })
} }
@@ -72,7 +72,7 @@ case source
sub.unshift(content) sub.unshift(content)
typedJSFn.init(sub) typedJSFn.init(sub)
} else { } else {
document.getElementById('subtitle').innerHTML = result.data.content document.getElementById('subtitle').textContent = result.data.content
} }
}) })
}) })
@@ -86,7 +86,7 @@ case source
if (!{effect}) { if (!{effect}) {
typedJSFn.init(!{JSON.stringify(subContent)}) typedJSFn.init(!{JSON.stringify(subContent)})
} else { } else {
document.getElementById("subtitle").innerHTML = '!{subContent[0]}' document.getElementById("subtitle").textContent = !{JSON.stringify(subContent[0])}
} }
} }
typedJSFn.run(subtitleType) typedJSFn.run(subtitleType)

View File

@@ -24,4 +24,4 @@ if theme.aside.card_author.enable
if(theme.social) if(theme.social)
.card-info-social-icons.is-center .card-info-social-icons.is-center
!=fragment_cache('social', function(){return partial('includes/header/social')}) !=partial('includes/header/social', {}, {cache: true})

View File

@@ -1,4 +1,4 @@
if theme.newest_comments.enable && !['Livere','Facebook Comments','Giscus'].includes(theme.comments.use[0]) if theme.newest_comments.enable && theme.comments.use && !['Livere','Facebook Comments','Giscus'].includes(theme.comments.use[0])
.card-widget#card-newest-comments .card-widget#card-newest-comments
.item-headline .item-headline
i.fas.fa-comment-dots i.fas.fa-comment-dots

View File

@@ -5,8 +5,10 @@ if theme.aside.card_tags.enable
i.fas.fa-tags i.fas.fa-tags
span= _p('aside.card_tags') span= _p('aside.card_tags')
- let tagLimit = theme.aside.card_tags.limit === 0 ? 0 : theme.aside.card_tags.limit || 40 - let { limit, orderby, order } = theme.aside.card_tags
- limit = limit === 0 ? 0 : limit || 40
if theme.aside.card_tags.color if theme.aside.card_tags.color
.card-tag-cloud!= cloudTags({source: site.tags, minfontsize: 1.15, maxfontsize: 1.45, limit: tagLimit, unit: 'em'}) .card-tag-cloud!= cloudTags({source: site.tags, orderby: orderby, order: order, minfontsize: 1.15, maxfontsize: 1.45, limit: limit, unit: 'em'})
else else
.card-tag-cloud!= tagcloud({min_font: 1.1, max_font: 1.5, amount: tagLimit , color: true, start_color: '#999', end_color: '#99a9bf', unit: 'em'}) .card-tag-cloud!= tagcloud({orderby: orderby, order: order, min_font: 1.1, max_font: 1.5, amount: limit , color: true, start_color: '#999', end_color: '#99a9bf', unit: 'em'})

View File

@@ -19,7 +19,7 @@
//- page //- page
!=partial('includes/widget/card_author', {}, {cache: true}) !=partial('includes/widget/card_author', {}, {cache: true})
!=partial('includes/widget/card_announcement', {}, {cache: true}) !=partial('includes/widget/card_announcement', {}, {cache: true})
!=partial('includes/widget/card_top_self', {}, {cache: true}) !=partial('includes/widget/card_top_self', {}, {cache: true})
.sticky_layout .sticky_layout
if showToc if showToc

View File

@@ -1,6 +1,6 @@
{ {
"name": "hexo-theme-butterfly", "name": "hexo-theme-butterfly",
"version": "4.6.1", "version": "4.9.0",
"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": {
@@ -23,7 +23,7 @@
"email": "my@crazywong.com" "email": "my@crazywong.com"
}, },
"dependencies": { "dependencies": {
"hexo-renderer-stylus": "^2.1.0", "hexo-renderer-stylus": "^3.0.0",
"hexo-renderer-pug": "^3.0.0" "hexo-renderer-pug": "^3.0.0"
}, },
"homepage": "https://butterfly.js.org/", "homepage": "https://butterfly.js.org/",

View File

@@ -1,11 +1,11 @@
algolia_search_v4: algolia_search:
name: algoliasearch name: algoliasearch
file: dist/algoliasearch-lite.umd.js file: dist/algoliasearch-lite.umd.js
version: 4.14.3 version: 4.17.1
instantsearch_v4: instantsearch:
name: instantsearch.js name: instantsearch.js
file: dist/instantsearch.production.min.js file: dist/instantsearch.production.min.js
version: 4.49.4 version: 4.56.1
pjax: pjax:
name: pjax name: pjax
file: pjax.min.js file: pjax.min.js
@@ -37,17 +37,17 @@ disqusjs_css:
twikoo: twikoo:
name: twikoo name: twikoo
file: dist/twikoo.all.min.js file: dist/twikoo.all.min.js
version: 1.6.8 version: 1.6.16
waline_js: waline_js:
name: '@waline/client' name: '@waline/client'
file: dist/waline.js file: dist/waline.js
other_name: waline other_name: waline
version: 2.14.7 version: 2.15.5
waline_css: waline_css:
name: '@waline/client' name: '@waline/client'
file: dist/waline.css file: dist/waline.css
other_name: waline other_name: waline
version: 2.14.7 version: 2.15.5
sharejs: sharejs:
name: butterfly-extsrc name: butterfly-extsrc
file: sharejs/dist/js/social-share.min.js file: sharejs/dist/js/social-share.min.js
@@ -64,16 +64,16 @@ katex:
name: katex name: katex
file: dist/katex.min.css file: dist/katex.min.css
other_name: KaTeX other_name: KaTeX
version: 0.16.4 version: 0.16.7
katex_copytex: katex_copytex:
name: katex name: katex
file: dist/contrib/copy-tex.min.js file: dist/contrib/copy-tex.min.js
other_name: KaTeX other_name: KaTeX
version: 0.16.4 version: 0.16.7
mermaid: mermaid:
name: mermaid name: mermaid
file: dist/mermaid.min.js file: dist/mermaid.min.js
version: 9.3.0 version: 10.2.2
canvas_ribbon: canvas_ribbon:
name: butterfly-extsrc name: butterfly-extsrc
file: dist/canvas-ribbon.min.js file: dist/canvas-ribbon.min.js
@@ -109,24 +109,24 @@ lazyload:
instantpage: instantpage:
name: instant.page name: instant.page
file: instantpage.js file: instantpage.js
version: 5.1.1 version: 5.2.0
typed: typed:
name: typed.js name: typed.js
file: lib/typed.min.js file: dist/typed.umd.js
version: 2.0.12 version: 2.0.16
pangu: pangu:
name: pangu name: pangu
file: dist/browser/pangu.min.js file: dist/browser/pangu.min.js
version: 4.0.7 version: 4.0.7
fancybox_css_v4: fancybox_css:
name: '@fancyapps/ui' name: '@fancyapps/ui'
file: dist/fancybox.css file: dist/fancybox/fancybox.css
version: 4.0.31 version: 5.0.19
other_name: fancyapps-ui other_name: fancyapps-ui
fancybox_v4: fancybox:
name: '@fancyapps/ui' name: '@fancyapps/ui'
file: dist/fancybox.umd.js file: dist/fancybox/fancybox.umd.js
version: 4.0.31 version: 5.0.19
other_name: fancyapps-ui other_name: fancyapps-ui
medium_zoom: medium_zoom:
name: medium-zoom name: medium-zoom
@@ -140,11 +140,11 @@ snackbar:
name: node-snackbar name: node-snackbar
file: dist/snackbar.min.js file: dist/snackbar.min.js
version: 0.1.16 version: 0.1.16
fontawesomeV6: fontawesome:
name: '@fortawesome/fontawesome-free' name: '@fortawesome/fontawesome-free'
file: css/all.min.css file: css/all.min.css
other_name: font-awesome other_name: font-awesome
version: 6.2.1 version: 6.4.0
flickr_justified_gallery_js: flickr_justified_gallery_js:
name: flickr-justified-gallery name: flickr-justified-gallery
file: dist/fjGallery.min.js file: dist/fjGallery.min.js
@@ -183,11 +183,11 @@ prismjs_autoloader:
artalk_js: artalk_js:
name: artalk name: artalk
file: dist/Artalk.js file: dist/Artalk.js
version: 2.4.4 version: 2.5.5
artalk_css: artalk_css:
name: artalk name: artalk
file: dist/Artalk.css file: dist/Artalk.css
version: 2.4.4 version: 2.5.5
pace_js: pace_js:
name: pace-js name: pace-js
other_name: pace other_name: pace
@@ -198,3 +198,17 @@ pace_default_css:
other_name: pace other_name: pace
file: themes/blue/pace-theme-minimal.css file: themes/blue/pace-theme-minimal.css
version: 1.2.4 version: 1.2.4
docsearch_js:
name: '@docsearch/js'
other_name: docsearch-js
file: dist/umd/index.js
version: 3.4.0
docsearch_css:
name: '@docsearch/css'
other_name: docsearch-css
file: dist/style.css
version: 3.4.0
abcjs_basic_js:
name: abcjs
file: dist/abcjs-basic-min.js
version: 6.2.2

View File

@@ -41,20 +41,19 @@ hexo.extend.filter.register('before_generate', () => {
} }
} }
const minFile = (file) => { const minFile = file => {
return file.replace(/(?<!\.min)\.(js|css)$/g, ext => '.min' + ext) return file.replace(/(?<!\.min)\.(js|css)$/g, ext => '.min' + ext)
} }
const createCDNLink = (data, type, cond = '') => { const createCDNLink = (data, type, cond = '') => {
Object.keys(data).forEach(key => { Object.keys(data).forEach(key => {
let { name, version, file, other_name } = data[key] let { name, version, file, other_name } = data[key]
const min_file = minFile(file)
const cdnjs_name = other_name || name const cdnjs_name = other_name || name
const cdnjs_file = file.replace(/^[lib|dist]*\/|browser\//g, '') const cdnjs_file = file.replace(/^[lib|dist]*\/|browser\//g, '')
const min_cdnjs_file = minFile(cdnjs_file) const min_cdnjs_file = minFile(cdnjs_file)
if (cond === 'internal') file = `source/${file}` if (cond === 'internal') file = `source/${file}`
const verType = CDN.version ? `@${version}` : '' const min_file = minFile(file)
const verType = CDN.version ? (type === 'local' ? `?v=${version}` : `@${version}`) : ''
const value = { const value = {
version, version,
@@ -67,7 +66,7 @@ hexo.extend.filter.register('before_generate', () => {
} }
const cdnSource = { const cdnSource = {
local: cond === 'internal' ? cdnjs_file : `/pluginsSrc/${name}/${file}`, local: cond === 'internal' ? `${cdnjs_file + verType}` : `/pluginsSrc/${name}/${file + verType}`,
jsdelivr: `https://cdn.jsdelivr.net/npm/${name}${verType}/${min_file}`, jsdelivr: `https://cdn.jsdelivr.net/npm/${name}${verType}/${min_file}`,
unpkg: `https://unpkg.com/${name}${verType}/${file}`, unpkg: `https://unpkg.com/${name}${verType}/${file}`,
cdnjs: `https://cdnjs.cloudflare.com/ajax/libs/${cdnjs_name}/${version}/${min_cdnjs_file}`, cdnjs: `https://cdnjs.cloudflare.com/ajax/libs/${cdnjs_name}/${version}/${min_cdnjs_file}`,
@@ -77,7 +76,7 @@ hexo.extend.filter.register('before_generate', () => {
data[key] = cdnSource[type] data[key] = cdnSource[type]
}) })
if (cond === 'internal') data.main_css = 'css/index.css' if (cond === 'internal') data.main_css = 'css/index.css' + (CDN.version ? `?v=${version}` : '')
return data return data
} }
@@ -90,6 +89,9 @@ hexo.extend.filter.register('before_generate', () => {
return obj return obj
} }
themeConfig.asset = Object.assign(createCDNLink(internalSrc, CDN.internal_provider, 'internal'), themeConfig.asset = Object.assign(
createCDNLink(thirdPartySrc, CDN.third_party_provider), deleteNullValue(CDN.option)) createCDNLink(internalSrc, CDN.internal_provider, 'internal'),
createCDNLink(thirdPartySrc, CDN.third_party_provider),
deleteNullValue(CDN.option)
)
}) })

View File

@@ -1,21 +1,19 @@
hexo.extend.filter.register('before_generate', () => { hexo.extend.filter.register('before_generate', () => {
// Get first two digits of the Hexo version number // Get first two digits of the Hexo version number
const hexoVer = hexo.version.replace(/(^.*\..*)\..*/, '$1') const { version, log, locals } = hexo
const logger = hexo.log const hexoVer = version.replace(/(^.*\..*)\..*/, '$1')
if (hexoVer < 5.3) { if (hexoVer < 5.3) {
logger.error('Please update Hexo to V5.3.0 or higher!') log.error('Please update Hexo to V5.3.0 or higher!')
logger.error('請把 Hexo 升級到 V5.3.0 或更高的版本!') log.error('請把 Hexo 升級到 V5.3.0 或更高的版本!')
process.exit(-1) process.exit(-1)
} }
if (hexo.locals.get) { if (locals.get) {
const data = hexo.locals.get('data') const data = locals.get('data')
if (data && data.butterfly) { if (data && data.butterfly) {
logger.error( log.error("'butterfly.yml' is deprecated. Please use '_config.butterfly.yml'")
" 'butterfly.yml' is deprecated. Please use '_config.butterfly.yml' " log.error("'butterfly.yml' 已經棄用,請使用 '_config.butterfly.yml'")
)
logger.error(" 'butterfly.yml' 已經棄用,請使用 '_config.butterfly.yml' ")
process.exit(-1) process.exit(-1)
} }
} }

View File

@@ -6,7 +6,7 @@
'use strict' 'use strict'
hexo.extend.filter.register('before_post_render', function (data) { hexo.extend.filter.register('before_post_render', function (data) {
const imgTestReg = /\.(png|jpe?g|gif|svg|webp)(\?.*)?$/ const imgTestReg = /\.(png|jpe?g|gif|svg|webp)(\?.*)?$/i
let randomCover let randomCover
let coverVal = data.cover let coverVal = data.cover

View File

@@ -7,7 +7,8 @@
hexo.extend.helper.register('inject_head_js', function () { hexo.extend.helper.register('inject_head_js', function () {
const { darkmode, aside } = this.theme const { darkmode, aside } = this.theme
const start = darkmode.start ? darkmode.start : 6
const end = darkmode.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'
@@ -61,12 +62,18 @@ hexo.extend.helper.register('inject_head_js', function () {
` `
const getCSS = ` const getCSS = `
win.getCSS = url => new Promise((resolve, reject) => { win.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
link.onload = () => resolve() if (id) link.id = id
link.onerror = () => reject() link.onerror = reject
link.onload = link.onreadystatechange = function() {
const loadState = this.readyState
if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
link.onload = link.onreadystatechange = null
resolve()
}
document.head.appendChild(link) document.head.appendChild(link)
}) })
` `
@@ -104,7 +111,7 @@ hexo.extend.helper.register('inject_head_js', function () {
else if (isNotSpecified || hasNoSupport) { else if (isNotSpecified || hasNoSupport) {
const now = new Date() const now = new Date()
const hour = now.getHours() const hour = now.getHours()
const isNight = hour <= 6 || hour >= 18 const isNight = hour <= ${start} || hour >= ${end}
isNight ? activateDarkMode() : activateLightMode() isNight ? activateDarkMode() : activateLightMode()
} }
window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) { window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
@@ -119,7 +126,7 @@ hexo.extend.helper.register('inject_head_js', function () {
darkmodeJs += ` darkmodeJs += `
const now = new Date() const now = new Date()
const hour = now.getHours() const hour = now.getHours()
const isNight = hour <= 6 || hour >= 18 const isNight = hour <= ${start} || hour >= ${end}
if (t === undefined) isNight ? activateDarkMode() : activateLightMode() if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
else if (t === 'light') activateLightMode() else if (t === 'light') activateLightMode()
else activateDarkMode() else activateDarkMode()

View File

@@ -24,11 +24,8 @@ hexo.extend.helper.register('page_description', function () {
hexo.extend.helper.register('cloudTags', function (options = {}) { hexo.extend.helper.register('cloudTags', function (options = {}) {
const env = this const env = this
let source = options.source let { source, minfontsize, maxfontsize, limit, unit, orderby, order } = options
const minfontsize = options.minfontsize unit = unit || 'px'
const maxfontsize = options.maxfontsize
const limit = options.limit
const unit = options.unit || 'px'
let result = '' let result = ''
if (limit > 0) { if (limit > 0) {
@@ -43,7 +40,7 @@ hexo.extend.helper.register('cloudTags', function (options = {}) {
}) })
const length = sizes.length - 1 const length = sizes.length - 1
source.forEach(tag => { source.sort(orderby, order).forEach(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)
let style = `font-size: ${parseFloat(size.toFixed(2))}${unit};` let style = `font-size: ${parseFloat(size.toFixed(2))}${unit};`
@@ -97,7 +94,7 @@ hexo.extend.helper.register('findArchivesTitle', function (page, menu, date) {
}) })
hexo.extend.helper.register('isImgOrUrl', function (path) { hexo.extend.helper.register('isImgOrUrl', function (path) {
const imgTestReg = /\.(png|jpe?g|gif|svg|webp)(\?.*)?$/ const imgTestReg = /\.(png|jpe?g|gif|svg|webp)(\?.*)?$/i
if (path.indexOf('//') !== -1 || imgTestReg.test(path)) { if (path.indexOf('//') !== -1 || imgTestReg.test(path)) {
return true return true
} }

View File

@@ -3,6 +3,7 @@
* galleryGroup and gallery * galleryGroup and gallery
* {% galleryGroup [name] [descr] [url] [img] %} * {% galleryGroup [name] [descr] [url] [img] %}
* {% gallery [lazyload],[rowHeight],[limit] %} * {% gallery [lazyload],[rowHeight],[limit] %}
* {% gallery url,[url],[lazyload],[rowHeight],[limit] %}
*/ */
'use strict' 'use strict'
@@ -12,28 +13,35 @@ const urlFor = require('hexo-util').url_for.bind(hexo)
function gallery (args, content) { function gallery (args, content) {
const { data, languages } = hexo.theme.i18n const { data, languages } = hexo.theme.i18n
args = args.join(' ').split(',') args = args.join(' ').split(',')
const rowHeight = args[1] || 220 let rowHeight, limit, lazyload, type, dataStr
const limit = args[2] || 10
const lazyload = args[0] === 'true' if (args[0] === 'url') {
const regex = /!\[(.*?)\]\(([^\s]*)\s*(?:["'](.*?)["']?)?\s*\)/g [type, dataStr, lazyload, rowHeight = 220, limit = 10] = args // url,[link],[lazyload],[rowHeight],[limit]
const lazyloadClass = lazyload ? 'lazyload' : '' } else {
let m [lazyload, rowHeight = 220, limit = 10] = args // [lazyload],[rowHeight],[limit]
const arr = [] const regex = /!\[(.*?)\]\(([^\s]*)\s*(?:["'](.*?)["']?)?\s*\)/g
while ((m = regex.exec(content)) !== null) { let m
if (m.index === regex.lastIndex) { const arr = []
regex.lastIndex++ while ((m = regex.exec(content)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++
}
arr.push({
url: m[2],
alt: m[1],
title: m[3]
})
} }
arr.push({ dataStr = JSON.stringify(arr)
url: m[2],
alt: m[1],
title: m[3]
})
} }
type = type ? ' url' : ' data'
const lazyloadClass = lazyload === 'true' ? 'lazyload' : ''
return `<div class="gallery"> return `<div class="gallery">
<div class="fj-gallery ${lazyloadClass}" data-rowHeight="${rowHeight}" data-limit="${limit}"> <div class="fj-gallery ${lazyloadClass + type}" data-rowHeight="${rowHeight}" data-limit="${limit}">
<span class="gallery-data">${JSON.stringify(arr)}</span> <span class="gallery-data">${dataStr}</span>
</div> </div>
<button class="gallery-load-more"><span>${data[languages[0]].load_more}</span><i class="fa-solid fa-arrow-down"></i></button> <button class="gallery-load-more"><span>${data[languages[0]].load_more}</span><i class="fa-solid fa-arrow-down"></i></button>
</div>` </div>`

22
scripts/tag/score.js Normal file
View File

@@ -0,0 +1,22 @@
/**
* Music Score
* {% score %}
*/
'use strict';
function score(args, content) {
function escapeHtmlTags(s) {
let lookup = {
'&': "&amp;",
'"': "&quot;",
'\'': "&apos;",
'<': "&lt;",
'>': "&gt;"
};
return s.replace(/[&"'<>]/g, c => lookup[c]);
}
return `<div class="abc-music-sheet">${escapeHtmlTags(content)}</div>`;
}
hexo.extend.tag.register('score', score, {ends: true});

View File

@@ -72,6 +72,30 @@
cursor: pointer cursor: pointer
transition: all .3s ease-out transition: all .3s ease-out
.custom-hr
position: relative
margin: 40px auto
border: 2px dashed var(--hr-border)
if hexo-config('hr_icon.enable')
width: calc(100% - 4px)
&:hover
&:before
left: calc(95% - 20px)
&:before
position: absolute
top: $hr-icon-top
left: 5%
z-index: 1
color: var(--hr-before-color)
content: $hr-icon
font-size: 20px
line-height: 1
transition: all 1s ease-in-out
@extend .fontawesomeIcon
maxWidth600() maxWidth600()
@media screen and (max-width: 600px) @media screen and (max-width: 600px)
{block} {block}

View File

@@ -6,7 +6,7 @@
--hr-before-color: lighten($theme-hr-color, 30%) --hr-before-color: lighten($theme-hr-color, 30%)
--search-bg: $search-bg --search-bg: $search-bg
--search-input-color: $search-input-color --search-input-color: $search-input-color
--search-result-title: $search-result-title --search-a-color: $search-a-color
--preloader-bg: $preloader-bg --preloader-bg: $preloader-bg
--preloader-color: $preloader-word-color --preloader-color: $preloader-word-color
--tab-border-color: $tab-border-color --tab-border-color: $tab-border-color
@@ -34,6 +34,8 @@
--headline-presudo: #a0a0a0 --headline-presudo: #a0a0a0
--scrollbar-color: $scrollbar-color --scrollbar-color: $scrollbar-color
--default-bg-color: $theme-color --default-bg-color: $theme-color
--zoom-bg: #fff
--mark-bg: alpha($dark-black, .3)
body body
position: relative position: relative
@@ -50,8 +52,8 @@ body
// scrollbar - chrome/safari // scrollbar - chrome/safari
*::-webkit-scrollbar *::-webkit-scrollbar
width: 8px width: 5px
height: 8px height: 5px
*::-webkit-scrollbar-thumb *::-webkit-scrollbar-thumb
background: var(--scrollbar-color) background: var(--scrollbar-color)
@@ -96,30 +98,6 @@ h6
* *
box-sizing: border-box box-sizing: border-box
hr
position: relative
margin: 40px auto
border: 2px dashed var(--hr-border)
if hexo-config('hr_icon.enable')
width: calc(100% - 4px)
&:hover
&:before
left: calc(95% - 20px)
&:before
position: absolute
top: $hr-icon-top
left: 5%
z-index: 1
color: var(--hr-before-color)
content: $hr-icon
font-size: 20px
line-height: 1
transition: all 1s ease-in-out
@extend .fontawesomeIcon
.table-wrap .table-wrap
overflow-x: scroll overflow-x: scroll
margin: 0 0 20px margin: 0 0 20px
@@ -174,9 +152,6 @@ if $site-name-font
.is-center .is-center
text-align: center text-align: center
.copy-true
user-select: all
.pull-left .pull-left
float: left float: left

View File

@@ -75,6 +75,14 @@ $code-block
&:hover &:hover
border-bottom-color: var(--hl-color) border-bottom-color: var(--hl-color)
&.copy-true
user-select: all
& > table,
& > pre
display: block !important
opacity: 0
.highlight-tools .highlight-tools
position: relative position: relative
display: flex display: flex

View File

@@ -52,7 +52,7 @@
transition: all .3s transition: all .3s
&:hover &:hover
transform: rotate(540deg) transform: rotate(360deg)
#card-info-btn #card-info-btn
display: block display: block
@@ -291,8 +291,8 @@
background: $theme-toc-color background: $theme-toc-color
color: $toc-active-color color: $toc-active-color
:only-child .sticky_layout:only-child
> .card-widget > :first-child
margin-top: 0 margin-top: 0
.card-more-btn .card-more-btn

View File

@@ -5,12 +5,12 @@
background-position: bottom background-position: bottom
background-size: cover background-size: cover
if hexo-config('footer_bg') != false if hexo-config('footer_bg') != false && hexo-config('mask.footer')
&:before &:before
position: absolute position: absolute
width: 100% width: 100%
height: 100% height: 100%
background-color: alpha($dark-black, .5) background-color: var(--mark-bg)
content: '' content: ''
#footer-wrap #footer-wrap

View File

@@ -7,12 +7,13 @@
background-repeat: no-repeat background-repeat: no-repeat
transition: all .5s transition: all .5s
&:not(.not-top-img):before if hexo-config('mask.header')
position: absolute &:not(.not-top-img):before
width: 100% position: absolute
height: 100% width: 100%
background-color: alpha($dark-black, .3) height: 100%
content: '' background-color: var(--mark-bg)
content: ''
// index // index
&.full_page &.full_page
@@ -97,9 +98,6 @@
+maxWidth768() +maxWidth768()
height: 360px height: 360px
&:before
background-color: alpha($dark-black, .5)
#post-info #post-info
position: absolute position: absolute
bottom: 100px bottom: 100px

View File

@@ -65,6 +65,9 @@ beautify()
ul > li ul > li
list-style-type: circle list-style-type: circle
hr
@extend .custom-hr
#article-container #article-container
word-wrap: break-word word-wrap: break-word
@@ -144,6 +147,12 @@ beautify()
p p
margin: 0 0 8px margin: 0 0 8px
> :last-child
margin-bottom: 0 !important
hr
margin: 20px 0
if hexo-config('beautify.enable') if hexo-config('beautify.enable')
if hexo-config('beautify.field') == 'site' if hexo-config('beautify.field') == 'site'
beautify() beautify()
@@ -151,9 +160,6 @@ beautify()
&.post-content &.post-content
beautify() beautify()
> :last-child
margin-bottom: 0 !important
#post #post
.tag_share .tag_share
&:after &:after

View File

@@ -82,15 +82,22 @@ if hexo-config('waline.bg')
display: none display: none
// Mathjax // Mathjax
.mathjax-overflow mjx-container
overflow-x: auto overflow-x: auto
overflow-y: hidden overflow-y: hidden
padding-bottom: 4px
span.mathjax-overflow
display: inline-block
padding: 0 2px
max-width: 100% max-width: 100%
vertical-align: bottom
&[display]
display: block !important
min-width: auto !important
&:not([display])
display: inline-grid !important
mjx-assistive-mml
right: 0
bottom: 0
.aplayer .aplayer
color: $font-black color: $font-black
@@ -113,4 +120,16 @@ span.mathjax-overflow
content: none content: none
.snackbar-css .snackbar-css
border-radius: 5px !important border-radius: 5px !important
.abc-music-sheet
margin: 0 0 20px
opacity: 0
transition: opacity .3s
&.abcjs-container
opacity: 1
+maxWidth768()
.fancybox__toolbar__column.is-middle
display: none

View File

@@ -6,7 +6,7 @@ if hexo-config('darkmode.enable') || hexo-config('display_mode') == 'dark'
--hr-before-color: alpha(#FFFFFF, .7) --hr-before-color: alpha(#FFFFFF, .7)
--search-bg: #121212 --search-bg: #121212
--search-input-color: alpha(#FFFFFF, .7) --search-input-color: alpha(#FFFFFF, .7)
--search-result-title: alpha(#FFFFFF, .9) --search-a-color: alpha(#FFFFFF, .7)
--preloader-bg: darken(#121212, 2) --preloader-bg: darken(#121212, 2)
--preloader-color: alpha(#FFFFFF, .7) --preloader-color: alpha(#FFFFFF, .7)
--tab-border-color: #2c2c2c --tab-border-color: #2c2c2c
@@ -38,10 +38,10 @@ if hexo-config('darkmode.enable') || hexo-config('display_mode') == 'dark'
--hlexpand-bg: linear-gradient(180deg, rgba(lighten(#121212, 2), .6), rgba(lighten(#121212, 2), .9)) --hlexpand-bg: linear-gradient(180deg, rgba(lighten(#121212, 2), .6), rgba(lighten(#121212, 2), .9))
--scrollbar-color: lighten(#121212, 5) --scrollbar-color: lighten(#121212, 5)
--timeline-bg: lighten(#121212, 5) --timeline-bg: lighten(#121212, 5)
--zoom-bg: #121212
--mark-bg: alpha($dark-black, .6)
#web_bg:before, #web_bg:before
#footer:before,
#page-header:before
position: absolute position: absolute
width: 100% width: 100%
height: 100% height: 100%

View File

@@ -54,8 +54,7 @@ if hexo-config('readmode')
display: none display: none
#page-header.post-bg #page-header.post-bg
background-color: transparent background: none !important
background-image: none !important
&:before &:before
opacity: 0 opacity: 0

View File

@@ -18,7 +18,7 @@
padding: 20px 5px padding: 20px 5px
+minWidth2000() +minWidth2000()
max-width: 1500px max-width: 70%
& > div:first-child:not(.recent-posts) & > div:first-child:not(.recent-posts)
@extend .cardHover @extend .cardHover

View File

@@ -8,7 +8,7 @@
flex-direction: row flex-direction: row
align-items: center align-items: center
overflow: hidden overflow: hidden
height: 18em height: 16.8em
+maxWidth768() +maxWidth768()
flex-direction: column flex-direction: column
@@ -24,7 +24,7 @@
.post_cover .post_cover
overflow: hidden overflow: hidden
width: 44% width: 42%
height: 100% height: 100%
+maxWidth768() +maxWidth768()
@@ -42,7 +42,7 @@
& >.recent-post-info & >.recent-post-info
padding: 0 40px padding: 0 40px
width: 57% width: 58%
+maxWidth768() +maxWidth768()
padding: 20px 20px 30px padding: 20px 20px 30px
@@ -57,7 +57,7 @@
& > .article-title & > .article-title
@extend .limit-more-line @extend .limit-more-line
color: var(--text-highlight-color) color: var(--text-highlight-color)
font-size: 1.72em font-size: 1.55em
line-height: 1.4 line-height: 1.4
transition: all .2s ease-in-out transition: all .2s ease-in-out
-webkit-line-clamp: 2 -webkit-line-clamp: 2
@@ -71,7 +71,7 @@
& > .article-meta-wrap & > .article-meta-wrap
margin: 6px 0 margin: 6px 0
color: $theme-meta-color color: $theme-meta-color
font-size: 90% font-size: .9em
& > .post-meta-date & > .post-meta-date
cursor: default cursor: default

View File

@@ -16,7 +16,7 @@
@extend .list-beauty @extend .list-beauty
a a
color: var(--search-result-title) color: var(--search-a-color)
&:hover &:hover
color: $search-color color: $search-color
@@ -26,12 +26,15 @@
color: $search-keyword-highlight color: $search-keyword-highlight
font-weight: bold font-weight: bold
.algolia-hits-item-title
font-weight: 600
.algolia-hit-item-content .algolia-hit-item-content
margin: 0 0 8px margin: 0 0 8px
word-break: break-word word-break: break-word
.ais-Pagination .ais-Pagination
margin: 20px 0 0 margin: 15px 0 0
padding: 0 padding: 0
text-align: center text-align: center
@@ -61,22 +64,16 @@
.ais-Pagination-item--disabled .ais-Pagination-item--disabled
visibility: hidden visibility: hidden
.algolia-logo
padding-top: 2px
width: 80px
height: 30px
#algolia-hits #algolia-hits
> div > div
overflow-y: scroll overflow-y: scroll
margin: 0 -20px margin: 0 -20px
padding: 0 22px padding: 0 22px
max-height: calc(80vh - 240px)
+minWidth768()
max-height: calc(80vh - 240px)
+maxWidth768() +maxWidth768()
height: calc(100vh - 260px) max-height: none
height: calc(var(--search-height) - 265px)
#algolia-info #algolia-info
div div
@@ -84,10 +81,7 @@
.algolia-poweredBy .algolia-poweredBy
float: right float: right
vertical-align: text-top
.apple svg
#algolia-search height: 1.1em
#algolia-hits
> div
+maxWidth768()
height: calc(90vh - 260px)

View File

@@ -9,6 +9,7 @@
width: 600px width: 600px
border-radius: 8px border-radius: 8px
background: var(--search-bg) background: var(--search-bg)
--search-height: 100vh
+maxWidth768() +maxWidth768()
top: 0 top: 0
@@ -37,6 +38,10 @@
&:hover &:hover
color: $search-color color: $search-color
hr
margin: 20px auto
@extend .custom-hr
#search-mask #search-mask
position: fixed position: fixed
@@ -46,4 +51,10 @@
left: 0 left: 0
z-index: 1000 z-index: 1000
display: none display: none
background: rgba($dark-black, .6) background: rgba($dark-black, .6)
if hexo-config('algolia_search.enable')
@require 'algolia'
if hexo-config('local_search.enable')
@require 'local-search'

View File

@@ -18,7 +18,7 @@
.search-wrap .search-wrap
display: none display: none
.local-search__hit-item .local-search-hit-item
position: relative position: relative
padding-left: 24px padding-left: 24px
line-height: 1.7 line-height: 1.7
@@ -43,27 +43,32 @@
a a
display: block display: block
color: var(--search-result-title) color: var(--search-a-color)
font-weight: 600
cursor: pointer
&:hover &:hover
color: $search-color color: $search-color
.search-result-title
font-weight: 600
.search-result .search-result
margin: 0 0 8px margin: 0 0 8px
word-break: break-word word-break: break-word
.search-keyword
color: $search-keyword-highlight
font-weight: bold
.search-result-list .search-result-list
overflow-y: overlay overflow-y: overlay
margin: 0 -20px margin: 0 -20px
padding: 0 22px padding: 0 22px
max-height: calc(80vh - 130px) max-height: calc(80vh - 200px)
+maxWidth768() +maxWidth768()
padding-bottom: 40px max-height: calc(var(--search-height) - 220px) !important
max-height: 75vh !important
.no-result
& + #local-search-stats-wrap
display: none
.search-keyword
background: transparent
color: $search-keyword-highlight
font-weight: bold

View File

@@ -12,10 +12,4 @@ if hexo-config('css_prefix')
@import '_mode/*' @import '_mode/*'
// search // search
if hexo-config('algolia_search.enable') @import '_search/index'
@import '_search/index'
@import '_search/algolia'
if hexo-config('local_search') && hexo-config('local_search.enable')
@import '_search/index'
@import '_search/local-search'

View File

@@ -82,7 +82,7 @@ $search-bg = #f6f8fa
$search-input-color = $font-black $search-input-color = $font-black
$search-color = $theme-color $search-color = $theme-color
$search-keyword-highlight = #F47466 $search-keyword-highlight = #F47466
$search-result-title = $font-black $search-a-color = $font-black
// comments // comments
$comments-switch-first-text = $bright-blue $comments-switch-first-text = $bright-blue
$comments-switch-second-text = $light-orange $comments-switch-second-text = $light-orange

View File

@@ -70,28 +70,17 @@ document.addEventListener('DOMContentLoaded', function () {
const highLight = GLOBAL_CONFIG.highlight const highLight = GLOBAL_CONFIG.highlight
if (!highLight) return if (!highLight) return
const isHighlightCopy = highLight.highlightCopy const { highlightCopy, highlightLang, highlightHeightLimit, plugin } = highLight
const isHighlightLang = highLight.highlightLang
const isHighlightShrink = GLOBAL_CONFIG_SITE.isHighlightShrink const isHighlightShrink = GLOBAL_CONFIG_SITE.isHighlightShrink
const highlightHeightLimit = highLight.highlightHeightLimit const isShowTool = highlightCopy || highlightLang || isHighlightShrink !== undefined
const isShowTool = isHighlightCopy || isHighlightLang || isHighlightShrink !== undefined const $figureHighlight = plugin === 'highlighjs' ? document.querySelectorAll('figure.highlight') : document.querySelectorAll('pre[class*="language-"]')
const $figureHighlight = highLight.plugin === 'highlighjs' ? document.querySelectorAll('figure.highlight') : document.querySelectorAll('pre[class*="language-"]')
if (!((isShowTool || highlightHeightLimit) && $figureHighlight.length)) return if (!((isShowTool || highlightHeightLimit) && $figureHighlight.length)) return
const isPrismjs = highLight.plugin === 'prismjs' const isPrismjs = plugin === 'prismjs'
let highlightShrinkEle = ''
let highlightCopyEle = ''
const highlightShrinkClass = isHighlightShrink === true ? 'closed' : '' const highlightShrinkClass = isHighlightShrink === true ? 'closed' : ''
const highlightShrinkEle = isHighlightShrink !== undefined ? `<i class="fas fa-angle-down expand ${highlightShrinkClass}"></i>` : ''
if (isHighlightShrink !== undefined) { const highlightCopyEle = highlightCopy ? '<div class="copy-notice"></div><i class="fas fa-paste copy-button"></i>' : ''
highlightShrinkEle = `<i class="fas fa-angle-down expand ${highlightShrinkClass}"></i>`
}
if (isHighlightCopy) {
highlightCopyEle = '<div class="copy-notice"></div><i class="fas fa-paste copy-button"></i>'
}
const copy = (text, ctx) => { const copy = (text, ctx) => {
if (document.queryCommandSupported && document.queryCommandSupported('copy')) { if (document.queryCommandSupported && document.queryCommandSupported('copy')) {
@@ -100,7 +89,7 @@ document.addEventListener('DOMContentLoaded', function () {
btf.snackbarShow(GLOBAL_CONFIG.copy.success) btf.snackbarShow(GLOBAL_CONFIG.copy.success)
} else { } else {
const prevEle = ctx.previousElementSibling const prevEle = ctx.previousElementSibling
prevEle.innerText = GLOBAL_CONFIG.copy.success prevEle.textContent = GLOBAL_CONFIG.copy.success
prevEle.style.opacity = 1 prevEle.style.opacity = 1
setTimeout(() => { prevEle.style.opacity = 0 }, 700) setTimeout(() => { prevEle.style.opacity = 0 }, 700)
} }
@@ -108,7 +97,7 @@ document.addEventListener('DOMContentLoaded', function () {
if (GLOBAL_CONFIG.Snackbar !== undefined) { if (GLOBAL_CONFIG.Snackbar !== undefined) {
btf.snackbarShow(GLOBAL_CONFIG.copy.noSupport) btf.snackbarShow(GLOBAL_CONFIG.copy.noSupport)
} else { } else {
ctx.previousElementSibling.innerText = GLOBAL_CONFIG.copy.noSupport ctx.previousElementSibling.textContent = GLOBAL_CONFIG.copy.noSupport
} }
} }
} }
@@ -119,8 +108,8 @@ document.addEventListener('DOMContentLoaded', function () {
$buttonParent.classList.add('copy-true') $buttonParent.classList.add('copy-true')
const selection = window.getSelection() const selection = window.getSelection()
const range = document.createRange() const range = document.createRange()
if (isPrismjs) range.selectNodeContents($buttonParent.querySelectorAll('pre code')[0]) const preCodeSelector = isPrismjs ? 'pre code' : 'table .code pre'
else range.selectNodeContents($buttonParent.querySelectorAll('table .code pre')[0]) range.selectNodeContents($buttonParent.querySelectorAll(`${preCodeSelector}`)[0])
selection.removeAllRanges() selection.removeAllRanges()
selection.addRange(range) selection.addRange(range)
const text = selection.toString() const text = selection.toString()
@@ -175,33 +164,29 @@ document.addEventListener('DOMContentLoaded', function () {
} }
} }
if (isHighlightLang) { if (isPrismjs) {
if (isPrismjs) { $figureHighlight.forEach(item => {
$figureHighlight.forEach(function (item) { if (highlightLang) {
const langName = item.getAttribute('data-language') ? item.getAttribute('data-language') : 'Code' const langName = item.getAttribute('data-language') || 'Code'
const highlightLangEle = `<div class="code-lang">${langName}</div>` const highlightLangEle = `<div class="code-lang">${langName}</div>`
btf.wrap(item, 'figure', { class: 'highlight' }) btf.wrap(item, 'figure', { class: 'highlight' })
createEle(highlightLangEle, item) createEle(highlightLangEle, item)
}) } else {
} else { btf.wrap(item, 'figure', { class: 'highlight' })
$figureHighlight.forEach(function (item) { createEle('', item)
}
})
} else {
$figureHighlight.forEach(function (item) {
if (highlightLang) {
let langName = item.getAttribute('class').split(' ')[1] let langName = item.getAttribute('class').split(' ')[1]
if (langName === 'plain' || langName === undefined) langName = 'Code' if (langName === 'plain' || langName === undefined) langName = 'Code'
const highlightLangEle = `<div class="code-lang">${langName}</div>` const highlightLangEle = `<div class="code-lang">${langName}</div>`
createEle(highlightLangEle, item, 'hl') createEle(highlightLangEle, item, 'hl')
}) } else {
}
} else {
if (isPrismjs) {
$figureHighlight.forEach(function (item) {
btf.wrap(item, 'figure', { class: 'highlight' })
createEle('', item)
})
} else {
$figureHighlight.forEach(function (item) {
createEle('', item, 'hl') createEle('', item, 'hl')
}) }
} })
} }
} }
@@ -243,8 +228,8 @@ document.addEventListener('DOMContentLoaded', function () {
return str return str
} }
const lazyloadFn = (i, arr) => { const lazyloadFn = (i, arr, limit) => {
const loadItem = i.getAttribute('data-limit') const loadItem = limit
const arrLength = arr.length const arrLength = arr.length
if (arrLength > loadItem) i.insertAdjacentHTML('beforeend', htmlStr(arr.splice(0, loadItem))) if (arrLength > loadItem) i.insertAdjacentHTML('beforeend', htmlStr(arr.splice(0, loadItem)))
else { else {
@@ -254,29 +239,43 @@ document.addEventListener('DOMContentLoaded', function () {
return arrLength > loadItem ? loadItem : arrLength return arrLength > loadItem ? loadItem : arrLength
} }
ele.forEach(item => { const fetchUrl = async (url) => {
const arr = JSON.parse(item.querySelector('.gallery-data').textContent) const response = await fetch(url)
return await response.json()
}
const runJustifiedGallery = (item, arr) => {
if (!item.classList.contains('lazyload')) item.innerHTML = htmlStr(arr) if (!item.classList.contains('lazyload')) item.innerHTML = htmlStr(arr)
else { else {
lazyloadFn(item, arr)
const limit = item.getAttribute('data-limit') const limit = item.getAttribute('data-limit')
lazyloadFn(item, arr, limit)
const clickBtnFn = () => { const clickBtnFn = () => {
const lastItemLength = lazyloadFn(item, arr) const lastItemLength = lazyloadFn(item, arr, limit)
fjGallery(item, 'appendImages', item.querySelectorAll(`.fj-gallery-item:nth-last-child(-n+${lastItemLength})`)) fjGallery(item, 'appendImages', item.querySelectorAll(`.fj-gallery-item:nth-last-child(-n+${lastItemLength})`))
btf.loadLightbox(item.querySelectorAll('img')) btf.loadLightbox(item.querySelectorAll('img'))
lastItemLength < limit && item.nextElementSibling.removeEventListener('click', clickBtnFn) lastItemLength < limit && item.nextElementSibling.removeEventListener('click', clickBtnFn)
} }
item.nextElementSibling.addEventListener('click', clickBtnFn) item.nextElementSibling.addEventListener('click', clickBtnFn)
} }
}) btf.initJustifiedGallery(item)
btf.loadLightbox(item.querySelectorAll('img'))
}
const addJustifiedGallery = () => {
ele.forEach(item => {
item.classList.contains('url')
? fetchUrl(item.textContent).then(res => { runJustifiedGallery(item, res) })
: runJustifiedGallery(item, JSON.parse(item.textContent))
})
}
if (window.fjGallery) { if (window.fjGallery) {
setTimeout(() => { btf.initJustifiedGallery(ele) }, 100) addJustifiedGallery()
return return
} }
getCSS(`${GLOBAL_CONFIG.source.justifiedGallery.css}`) getCSS(`${GLOBAL_CONFIG.source.justifiedGallery.css}`)
getScript(`${GLOBAL_CONFIG.source.justifiedGallery.js}`).then(() => { btf.initJustifiedGallery(ele) }) getScript(`${GLOBAL_CONFIG.source.justifiedGallery.js}`).then(addJustifiedGallery)
} }
/** /**
@@ -299,6 +298,11 @@ document.addEventListener('DOMContentLoaded', function () {
const scrollFn = function () { const scrollFn = function () {
const $rightside = document.getElementById('rightside') const $rightside = document.getElementById('rightside')
const innerHeight = window.innerHeight + 56 const innerHeight = window.innerHeight + 56
let initTop = 0
let isChatShow = true
const $header = document.getElementById('page-header')
const isChatBtn = typeof chatBtn !== 'undefined'
const isShowPercent = GLOBAL_CONFIG.percent.rightside
// 當滾動條小于 56 的時候 // 當滾動條小于 56 的時候
if (document.body.scrollHeight <= innerHeight) { if (document.body.scrollHeight <= innerHeight) {
@@ -307,33 +311,26 @@ document.addEventListener('DOMContentLoaded', function () {
} }
// find the scroll direction // find the scroll direction
function scrollDirection (currentTop) { const scrollDirection = currentTop => {
const result = currentTop > initTop // true is down & false is up const result = currentTop > initTop // true is down & false is up
initTop = currentTop initTop = currentTop
return result return result
} }
let initTop = 0
let isChatShow = true
const $header = document.getElementById('page-header')
const isChatBtnHide = typeof chatBtnHide === 'function'
const isChatBtnShow = typeof chatBtnShow === 'function'
const isShowPercent = GLOBAL_CONFIG.percent.rightside
const scrollTask = btf.throttle(() => { const scrollTask = btf.throttle(() => {
const currentTop = window.scrollY || document.documentElement.scrollTop const currentTop = window.scrollY || document.documentElement.scrollTop
const isDown = scrollDirection(currentTop) const isDown = scrollDirection(currentTop)
if (currentTop > 56) { if (currentTop > 56) {
if (isDown) { if (isDown) {
if ($header.classList.contains('nav-visible')) $header.classList.remove('nav-visible') if ($header.classList.contains('nav-visible')) $header.classList.remove('nav-visible')
if (isChatBtnShow && isChatShow === true) { if (isChatBtn && isChatShow === true) {
chatBtnHide() window.chatBtn.hide()
isChatShow = false isChatShow = false
} }
} else { } else {
if (!$header.classList.contains('nav-visible')) $header.classList.add('nav-visible') if (!$header.classList.contains('nav-visible')) $header.classList.add('nav-visible')
if (isChatBtnHide && isChatShow === false) { if (isChatBtn && isChatShow === false) {
chatBtnShow() window.chatBtn.show()
isChatShow = true isChatShow = true
} }
} }
@@ -478,6 +475,22 @@ document.addEventListener('DOMContentLoaded', function () {
window.addEventListener('scroll', tocScrollFn) window.addEventListener('scroll', tocScrollFn)
} }
const modeChangeFn = mode => {
if (!window.themeChange) {
return
}
const turnMode = item => window.themeChange[item](mode)
Object.keys(window.themeChange).forEach(item => {
if (['disqus', 'disqusjs'].includes(item)) {
setTimeout(() => turnMode(item), 300)
} else {
turnMode(item)
}
})
}
/** /**
* Rightside * Rightside
*/ */
@@ -490,7 +503,7 @@ document.addEventListener('DOMContentLoaded', function () {
newEle.className = 'fas fa-sign-out-alt exit-readmode' newEle.className = 'fas fa-sign-out-alt exit-readmode'
$body.appendChild(newEle) $body.appendChild(newEle)
function clickFn () { const clickFn = () => {
$body.classList.remove('read-mode') $body.classList.remove('read-mode')
newEle.remove() newEle.remove()
newEle.removeEventListener('click', clickFn) newEle.removeEventListener('click', clickFn)
@@ -499,8 +512,8 @@ document.addEventListener('DOMContentLoaded', function () {
newEle.addEventListener('click', clickFn) newEle.addEventListener('click', clickFn)
}, },
switchDarkMode: () => { // Switch Between Light And Dark Mode switchDarkMode: () => { // Switch Between Light And Dark Mode
const nowMode = document.documentElement.getAttribute('data-theme') === 'dark' ? 'dark' : 'light' const willChangeMode = document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark'
if (nowMode === 'light') { if (willChangeMode === 'dark') {
activateDarkMode() activateDarkMode()
saveToLocal.set('theme', 'dark', 2) saveToLocal.set('theme', 'dark', 2)
GLOBAL_CONFIG.Snackbar !== undefined && btf.snackbarShow(GLOBAL_CONFIG.Snackbar.day_to_night) GLOBAL_CONFIG.Snackbar !== undefined && btf.snackbarShow(GLOBAL_CONFIG.Snackbar.day_to_night)
@@ -509,11 +522,7 @@ document.addEventListener('DOMContentLoaded', function () {
saveToLocal.set('theme', 'light', 2) saveToLocal.set('theme', 'light', 2)
GLOBAL_CONFIG.Snackbar !== undefined && btf.snackbarShow(GLOBAL_CONFIG.Snackbar.night_to_day) GLOBAL_CONFIG.Snackbar !== undefined && btf.snackbarShow(GLOBAL_CONFIG.Snackbar.night_to_day)
} }
// handle some cases modeChangeFn(willChangeMode)
typeof utterancesTheme === 'function' && utterancesTheme()
typeof changeGiscusTheme === 'function' && changeGiscusTheme()
typeof FB === 'object' && window.loadFBComment && window.loadFBComment()
typeof runMermaid === 'function' && window.runMermaid()
}, },
showOrHideBtn: (e) => { // rightside 點擊設置 按鈕 展開 showOrHideBtn: (e) => { // rightside 點擊設置 按鈕 展開
const rightsideHideClassList = document.getElementById('rightside-config-hide').classList const rightsideHideClassList = document.getElementById('rightside-config-hide').classList
@@ -531,15 +540,16 @@ document.addEventListener('DOMContentLoaded', function () {
}, },
hideAsideBtn: () => { // Hide aside hideAsideBtn: () => { // Hide aside
const $htmlDom = document.documentElement.classList const $htmlDom = document.documentElement.classList
$htmlDom.contains('hide-aside') const saveStatus = $htmlDom.contains('hide-aside') ? 'show' : 'hide'
? saveToLocal.set('aside-status', 'show', 2) saveToLocal.set('aside-status', saveStatus, 2)
: saveToLocal.set('aside-status', 'hide', 2)
$htmlDom.toggle('hide-aside') $htmlDom.toggle('hide-aside')
}, },
runMobileToc: () => { runMobileToc: () => {
if (window.getComputedStyle(document.getElementById('card-toc')).getPropertyValue('opacity') === '0') window.mobileToc.open() if (window.getComputedStyle(document.getElementById('card-toc')).getPropertyValue('opacity') === '0') window.mobileToc.open()
else window.mobileToc.close() else window.mobileToc.close()
},
toggleChatDisplay: () => {
window.chatBtnFn()
} }
} }
@@ -564,6 +574,9 @@ document.addEventListener('DOMContentLoaded', function () {
case 'hide-aside-btn': case 'hide-aside-btn':
rightSideFn.hideAsideBtn() rightSideFn.hideAsideBtn()
break break
case 'chat-btn':
rightSideFn.toggleChatDisplay()
break
default: default:
break break
} }
@@ -582,21 +595,16 @@ document.addEventListener('DOMContentLoaded', function () {
} }
/** /**
* 複製時加上版權信息 * 複製時加上版權信息
*/ */
const addCopyright = () => { const addCopyright = () => {
const copyright = GLOBAL_CONFIG.copyright const copyright = GLOBAL_CONFIG.copyright
document.body.oncopy = (e) => { document.body.oncopy = (e) => {
e.preventDefault() e.preventDefault()
let textFont; const copyFont = window.getSelection(0).toString() const copyFont = window.getSelection(0).toString()
let textFont = copyFont
if (copyFont.length > copyright.limitCount) { if (copyFont.length > copyright.limitCount) {
textFont = copyFont + '\n' + '\n' + '\n' + textFont = `${copyFont}\n\n\n${copyright.languages.author}\n${copyright.languages.link}${window.location.href}\n${copyright.languages.source}\n${copyright.languages.info}`
copyright.languages.author + '\n' +
copyright.languages.link + window.location.href + '\n' +
copyright.languages.source + '\n' +
copyright.languages.info
} else {
textFont = copyFont
} }
if (e.clipboardData) { if (e.clipboardData) {
return e.clipboardData.setData('text', textFont) return e.clipboardData.setData('text', textFont)
@@ -613,7 +621,7 @@ document.addEventListener('DOMContentLoaded', function () {
const $runtimeCount = document.getElementById('runtimeshow') const $runtimeCount = document.getElementById('runtimeshow')
if ($runtimeCount) { if ($runtimeCount) {
const publishDate = $runtimeCount.getAttribute('data-publishDate') const publishDate = $runtimeCount.getAttribute('data-publishDate')
$runtimeCount.innerText = btf.diffDate(publishDate) + ' ' + GLOBAL_CONFIG.runtime $runtimeCount.textContent = `${btf.diffDate(publishDate)} ${GLOBAL_CONFIG.runtime}`
} }
} }
@@ -624,7 +632,7 @@ document.addEventListener('DOMContentLoaded', function () {
const $lastPushDateItem = document.getElementById('last-push-date') const $lastPushDateItem = document.getElementById('last-push-date')
if ($lastPushDateItem) { if ($lastPushDateItem) {
const lastPushDate = $lastPushDateItem.getAttribute('data-lastPushDate') const lastPushDate = $lastPushDateItem.getAttribute('data-lastPushDate')
$lastPushDateItem.innerText = btf.diffDate(lastPushDate, true) $lastPushDateItem.textContent = btf.diffDate(lastPushDate, true)
} }
} }
@@ -757,10 +765,9 @@ document.addEventListener('DOMContentLoaded', function () {
const relativeDate = function (selector) { const relativeDate = function (selector) {
selector.forEach(item => { selector.forEach(item => {
const $this = item const timeVal = item.getAttribute('datetime')
const timeVal = $this.getAttribute('datetime') item.textContent = btf.diffDate(timeVal, true)
$this.innerText = btf.diffDate(timeVal, true) item.style.display = 'inline'
$this.style.display = 'inline'
}) })
} }
@@ -775,6 +782,13 @@ document.addEventListener('DOMContentLoaded', function () {
clickFnOfSubMenu() clickFnOfSubMenu()
GLOBAL_CONFIG.islazyload && lazyloadImg() GLOBAL_CONFIG.islazyload && lazyloadImg()
GLOBAL_CONFIG.copyright !== undefined && addCopyright() GLOBAL_CONFIG.copyright !== undefined && addCopyright()
if (GLOBAL_CONFIG.autoDarkmode) {
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
if (saveToLocal.get('theme') !== undefined) return
e.matches ? modeChangeFn('dark') : modeChangeFn('light')
})
}
} }
window.refreshFn = function () { window.refreshFn = function () {

View File

@@ -1,10 +1,13 @@
window.addEventListener('load', () => { window.addEventListener('load', () => {
const $searchMask = document.getElementById('search-mask')
const $searchDialog = document.querySelector('#algolia-search .search-dialog')
const openSearch = () => { const openSearch = () => {
const bodyStyle = document.body.style const bodyStyle = document.body.style
bodyStyle.width = '100%' bodyStyle.width = '100%'
bodyStyle.overflow = 'hidden' bodyStyle.overflow = 'hidden'
btf.animateIn(document.getElementById('search-mask'), 'to_show 0.5s') btf.animateIn($searchMask, 'to_show 0.5s')
btf.animateIn(document.querySelector('#algolia-search .search-dialog'), 'titleScale 0.5s') btf.animateIn($searchDialog, 'titleScale 0.5s')
setTimeout(() => { document.querySelector('#algolia-search .ais-SearchBox-input').focus() }, 100) setTimeout(() => { document.querySelector('#algolia-search .ais-SearchBox-input').focus() }, 100)
// shortcut: ESC // shortcut: ESC
@@ -14,22 +17,33 @@ window.addEventListener('load', () => {
document.removeEventListener('keydown', f) document.removeEventListener('keydown', f)
} }
}) })
fixSafariHeight()
window.addEventListener('resize', fixSafariHeight)
} }
const closeSearch = () => { const closeSearch = () => {
const bodyStyle = document.body.style const bodyStyle = document.body.style
bodyStyle.width = '' bodyStyle.width = ''
bodyStyle.overflow = '' bodyStyle.overflow = ''
btf.animateOut(document.querySelector('#algolia-search .search-dialog'), 'search_close .5s') btf.animateOut($searchDialog, 'search_close .5s')
btf.animateOut(document.getElementById('search-mask'), 'to_hide 0.5s') btf.animateOut($searchMask, 'to_hide 0.5s')
window.removeEventListener('resize', fixSafariHeight)
}
// fix safari
const fixSafariHeight = () => {
if (window.innerWidth < 768) {
$searchDialog.style.setProperty('--search-height', window.innerHeight + 'px')
}
} }
const searchClickFn = () => { const searchClickFn = () => {
document.querySelector('#search-button > .search').addEventListener('click', openSearch) document.querySelector('#search-button > .search').addEventListener('click', openSearch)
} }
const searchClickFnOnce = () => { const searchFnOnce = () => {
document.getElementById('search-mask').addEventListener('click', closeSearch) $searchMask.addEventListener('click', closeSearch)
document.querySelector('#algolia-search .search-close-button').addEventListener('click', closeSearch) document.querySelector('#algolia-search .search-close-button').addEventListener('click', closeSearch)
} }
@@ -102,9 +116,9 @@ window.addEventListener('load', () => {
: '' : ''
return ` return `
<a href="${link}" class="algolia-hit-item-link"> <a href="${link}" class="algolia-hit-item-link">
${result.title.value || 'no-title'} <span class="algolia-hits-item-title">${result.title.value || 'no-title'}</span>
</a> <p class="algolia-hit-item-content">${content}</p>
<p class="algolia-hit-item-content">${content}</p>` </a>`
}, },
empty: function (data) { empty: function (data) {
return ( return (
@@ -150,10 +164,10 @@ window.addEventListener('load', () => {
search.start() search.start()
searchClickFn() searchClickFn()
searchClickFnOnce() searchFnOnce()
window.addEventListener('pjax:complete', () => { window.addEventListener('pjax:complete', () => {
getComputedStyle(document.querySelector('#algolia-search .search-dialog')).display === 'block' && closeSearch() !btf.isHidden($searchMask) && closeSearch()
searchClickFn() searchClickFn()
}) })

View File

@@ -1,17 +1,311 @@
/**
* Refer to hexo-generator-searchdb
* https://github.com/next-theme/hexo-generator-searchdb/blob/main/dist/search.js
* Modified by hexo-theme-butterfly
*/
class LocalSearch {
constructor ({
path = '',
unescape = false,
top_n_per_article = 1
}) {
this.path = path
this.unescape = unescape
this.top_n_per_article = top_n_per_article
this.isfetched = false
this.datas = null
}
getIndexByWord (words, text, caseSensitive = false) {
const index = []
const included = new Set()
if (!caseSensitive) {
text = text.toLowerCase()
}
words.forEach(word => {
if (this.unescape) {
const div = document.createElement('div')
div.innerText = word
word = div.innerHTML
}
const wordLen = word.length
if (wordLen === 0) return
let startPosition = 0
let position = -1
if (!caseSensitive) {
word = word.toLowerCase()
}
while ((position = text.indexOf(word, startPosition)) > -1) {
index.push({ position, word })
included.add(word)
startPosition = position + wordLen
}
})
// Sort index by position of keyword
index.sort((left, right) => {
if (left.position !== right.position) {
return left.position - right.position
}
return right.word.length - left.word.length
})
return [index, included]
}
// Merge hits into slices
mergeIntoSlice (start, end, index) {
let item = index[0]
let { position, word } = item
const hits = []
const count = new Set()
while (position + word.length <= end && index.length !== 0) {
count.add(word)
hits.push({
position,
length: word.length
})
const wordEnd = position + word.length
// Move to next position of hit
index.shift()
while (index.length !== 0) {
item = index[0]
position = item.position
word = item.word
if (wordEnd > position) {
index.shift()
} else {
break
}
}
}
return {
hits,
start,
end,
count: count.size
}
}
// Highlight title and content
highlightKeyword (val, slice) {
let result = ''
let index = slice.start
for (const { position, length } of slice.hits) {
result += val.substring(index, position)
index = position + length
result += `<mark class="search-keyword">${val.substr(position, length)}</mark>`
}
result += val.substring(index, slice.end)
return result
}
getResultItems (keywords) {
const resultItems = []
this.datas.forEach(({ title, content, url }) => {
// The number of different keywords included in the article.
const [indexOfTitle, keysOfTitle] = this.getIndexByWord(keywords, title)
const [indexOfContent, keysOfContent] = this.getIndexByWord(keywords, content)
const includedCount = new Set([...keysOfTitle, ...keysOfContent]).size
// Show search results
const hitCount = indexOfTitle.length + indexOfContent.length
if (hitCount === 0) return
const slicesOfTitle = []
if (indexOfTitle.length !== 0) {
slicesOfTitle.push(this.mergeIntoSlice(0, title.length, indexOfTitle))
}
let slicesOfContent = []
while (indexOfContent.length !== 0) {
const item = indexOfContent[0]
const { position } = item
// Cut out 120 characters. The maxlength of .search-input is 80.
const start = Math.max(0, position - 20)
const end = Math.min(content.length, position + 100)
slicesOfContent.push(this.mergeIntoSlice(start, end, indexOfContent))
}
// Sort slices in content by included keywords' count and hits' count
slicesOfContent.sort((left, right) => {
if (left.count !== right.count) {
return right.count - left.count
} else if (left.hits.length !== right.hits.length) {
return right.hits.length - left.hits.length
}
return left.start - right.start
})
// Select top N slices in content
const upperBound = parseInt(this.top_n_per_article, 10)
if (upperBound >= 0) {
slicesOfContent = slicesOfContent.slice(0, upperBound)
}
let resultItem = ''
url = new URL(url, location.origin)
url.searchParams.append('highlight', keywords.join(' '))
if (slicesOfTitle.length !== 0) {
resultItem += `<div class="local-search-hit-item"><a href="${url.href}"><span class="search-result-title">${this.highlightKeyword(title, slicesOfTitle[0])}</span>`
} else {
resultItem += `<div class="local-search-hit-item"><a href="${url.href}"><span class="search-result-title">${title}</span>`
}
slicesOfContent.forEach(slice => {
resultItem += `<p class="search-result">${this.highlightKeyword(content, slice)}...</p></a>`
})
resultItem += '</div>'
resultItems.push({
item: resultItem,
id: resultItems.length,
hitCount,
includedCount
})
})
return resultItems
}
fetchData () {
const isXml = !this.path.endsWith('json')
fetch(this.path)
.then(response => response.text())
.then(res => {
// Get the contents from search data
this.isfetched = true
this.datas = isXml
? [...new DOMParser().parseFromString(res, 'text/xml').querySelectorAll('entry')].map(element => ({
title: element.querySelector('title').textContent,
content: element.querySelector('content').textContent,
url: element.querySelector('url').textContent
}))
: JSON.parse(res)
// Only match articles with non-empty titles
this.datas = this.datas.filter(data => data.title).map(data => {
data.title = data.title.trim()
data.content = data.content ? data.content.trim().replace(/<[^>]+>/g, '') : ''
data.url = decodeURIComponent(data.url).replace(/\/{2,}/g, '/')
return data
})
// Remove loading animation
window.dispatchEvent(new Event('search:loaded'))
})
}
// Highlight by wrapping node in mark elements with the given class name
highlightText (node, slice, className) {
const val = node.nodeValue
let index = slice.start
const children = []
for (const { position, length } of slice.hits) {
const text = document.createTextNode(val.substring(index, position))
index = position + length
const mark = document.createElement('mark')
mark.className = className
mark.appendChild(document.createTextNode(val.substr(position, length)))
children.push(text, mark)
}
node.nodeValue = val.substring(index, slice.end)
children.forEach(element => {
node.parentNode.insertBefore(element, node)
})
}
// Highlight the search words provided in the url in the text
highlightSearchWords (body) {
const params = new URL(location.href).searchParams.get('highlight')
const keywords = params ? params.split(' ') : []
if (!keywords.length || !body) return
const walk = document.createTreeWalker(body, NodeFilter.SHOW_TEXT, null)
const allNodes = []
while (walk.nextNode()) {
if (!walk.currentNode.parentNode.matches('button, select, textarea, .mermaid')) allNodes.push(walk.currentNode)
}
allNodes.forEach(node => {
const [indexOfNode] = this.getIndexByWord(keywords, node.nodeValue)
if (!indexOfNode.length) return
const slice = this.mergeIntoSlice(0, node.nodeValue.length, indexOfNode)
this.highlightText(node, slice, 'search-keyword')
})
}
}
window.addEventListener('load', () => { window.addEventListener('load', () => {
// Search
const { path, top_n_per_article, unescape, languages } = GLOBAL_CONFIG.localSearch
const localSearch = new LocalSearch({
path,
top_n_per_article,
unescape
})
const input = document.querySelector('#local-search-input input')
const statsItem = document.getElementById('local-search-stats-wrap')
const $loadingStatus = document.getElementById('loading-status')
const inputEventFunction = () => {
if (!localSearch.isfetched) return
const searchText = input.value.trim().toLowerCase()
if (searchText !== '') $loadingStatus.innerHTML = '<i class="fas fa-spinner fa-pulse"></i>'
const keywords = searchText.split(/[-\s]+/)
const container = document.getElementById('local-search-results')
let resultItems = []
if (searchText.length > 0) {
// Perform local searching
resultItems = localSearch.getResultItems(keywords)
}
if (keywords.length === 1 && keywords[0] === '') {
container.classList.add('no-result')
container.textContent = ''
} else if (resultItems.length === 0) {
container.textContent = ''
statsItem.innerHTML = `<div class="search-result-stats">${languages.hits_empty.replace(/\$\{query}/, searchText)}</div>`
} else {
resultItems.sort((left, right) => {
if (left.includedCount !== right.includedCount) {
return right.includedCount - left.includedCount
} else if (left.hitCount !== right.hitCount) {
return right.hitCount - left.hitCount
}
return right.id - left.id
})
const stats = languages.hits_stats.replace(/\$\{hits}/, resultItems.length)
container.classList.remove('no-result')
container.innerHTML = `<div class="search-result-list">${resultItems.map(result => result.item).join('')}</div>`
statsItem.innerHTML = `<hr><div class="search-result-stats">${stats}</div>`
window.pjax && window.pjax.refresh(container)
}
$loadingStatus.textContent = ''
}
let loadFlag = false let loadFlag = false
let dataObj = []
const $searchMask = document.getElementById('search-mask') const $searchMask = document.getElementById('search-mask')
const $searchDialog = document.querySelector('#local-search .search-dialog')
// fix safari
const fixSafariHeight = () => {
if (window.innerWidth < 768) {
$searchDialog.style.setProperty('--search-height', window.innerHeight + 'px')
}
}
const openSearch = () => { const openSearch = () => {
const bodyStyle = document.body.style const bodyStyle = document.body.style
bodyStyle.width = '100%' bodyStyle.width = '100%'
bodyStyle.overflow = 'hidden' bodyStyle.overflow = 'hidden'
btf.animateIn($searchMask, 'to_show 0.5s') btf.animateIn($searchMask, 'to_show 0.5s')
btf.animateIn(document.querySelector('#local-search .search-dialog'), 'titleScale 0.5s') btf.animateIn($searchDialog, 'titleScale 0.5s')
setTimeout(() => { document.querySelector('#local-search-input input').focus() }, 100) setTimeout(() => { input.focus() }, 300)
if (!loadFlag) { if (!loadFlag) {
search() !localSearch.isfetched && localSearch.fetchData()
input.addEventListener('input', inputEventFunction)
loadFlag = true loadFlag = true
} }
// shortcut: ESC // shortcut: ESC
@@ -21,176 +315,46 @@ window.addEventListener('load', () => {
document.removeEventListener('keydown', f) document.removeEventListener('keydown', f)
} }
}) })
fixSafariHeight()
window.addEventListener('resize', fixSafariHeight)
} }
const closeSearch = () => { const closeSearch = () => {
const bodyStyle = document.body.style const bodyStyle = document.body.style
bodyStyle.width = '' bodyStyle.width = ''
bodyStyle.overflow = '' bodyStyle.overflow = ''
btf.animateOut(document.querySelector('#local-search .search-dialog'), 'search_close .5s') btf.animateOut($searchDialog, 'search_close .5s')
btf.animateOut($searchMask, 'to_hide 0.5s') btf.animateOut($searchMask, 'to_hide 0.5s')
window.removeEventListener('resize', fixSafariHeight)
} }
const searchClickFn = () => { const searchClickFn = () => {
document.querySelector('#search-button > .search').addEventListener('click', openSearch) document.querySelector('#search-button > .search').addEventListener('click', openSearch)
} }
const searchClickFnOnce = () => { const searchFnOnce = () => {
document.querySelector('#local-search .search-close-button').addEventListener('click', closeSearch) document.querySelector('#local-search .search-close-button').addEventListener('click', closeSearch)
$searchMask.addEventListener('click', closeSearch) $searchMask.addEventListener('click', closeSearch)
if (GLOBAL_CONFIG.localSearch.preload) dataObj = fetchData(GLOBAL_CONFIG.localSearch.path) if (GLOBAL_CONFIG.localSearch.preload) {
} localSearch.fetchData()
// check url is json or not
const isJson = url => {
const reg = /\.json$/
return reg.test(url)
}
const fetchData = async (path) => {
let data = []
const response = await fetch(path)
if (isJson(path)) {
data = await response.json()
} else {
const res = await response.text()
const t = await new window.DOMParser().parseFromString(res, 'text/xml')
const a = await t
data = [...a.querySelectorAll('entry')].map(item => {
return {
title: item.querySelector('title').textContent,
content: item.querySelector('content') && item.querySelector('content').textContent,
url: item.querySelector('url').textContent
}
})
} }
if (response.ok) { localSearch.highlightSearchWords(document.getElementById('article-container'))
const $loadDataItem = document.getElementById('loading-database')
$loadDataItem.nextElementSibling.style.display = 'block'
$loadDataItem.remove()
}
return data
} }
const search = () => { window.addEventListener('search:loaded', () => {
if (!GLOBAL_CONFIG.localSearch.preload) { const $loadDataItem = document.getElementById('loading-database')
dataObj = fetchData(GLOBAL_CONFIG.localSearch.path) $loadDataItem.nextElementSibling.style.display = 'block'
} $loadDataItem.remove()
})
const $input = document.querySelector('#local-search-input input')
const $resultContent = document.getElementById('local-search-results')
const $loadingStatus = document.getElementById('loading-status')
$input.addEventListener('input', function () {
const keywords = this.value.trim().toLowerCase().split(/[\s]+/)
if (keywords[0] !== '') $loadingStatus.innerHTML = '<i class="fas fa-spinner fa-pulse"></i>'
else {
$resultContent.innerHTML = ''
return
}
let str = '<div class="search-result-list">'
if (keywords.length <= 0) return
let count = 0
// perform local searching
dataObj.then(data => {
data.forEach(data => {
let isMatch = true
let dataTitle = data.title ? data.title.trim().toLowerCase() : ''
const dataContent = data.content ? data.content.trim().replace(/<[^>]+>/g, '').toLowerCase() : ''
const dataUrl = data.url.startsWith('/') ? data.url : GLOBAL_CONFIG.root + data.url
let indexTitle = -1
let indexContent = -1
let firstOccur = -1
// only match articles with not empty titles and contents
if (dataTitle !== '' || dataContent !== '') {
keywords.forEach((keyword, i) => {
indexTitle = dataTitle.indexOf(keyword)
indexContent = dataContent.indexOf(keyword)
if (indexTitle < 0 && indexContent < 0) {
isMatch = false
} else {
if (indexContent < 0) {
indexContent = 0
}
if (i === 0) {
firstOccur = indexContent
}
}
})
} else {
isMatch = false
}
// show search results
if (isMatch) {
if (firstOccur >= 0) {
// cut out 130 characters
// let start = firstOccur - 30 < 0 ? 0 : firstOccur - 30
// let end = firstOccur + 50 > dataContent.length ? dataContent.length : firstOccur + 50
let start = firstOccur - 30
let end = firstOccur + 100
let pre = ''
let post = ''
if (start < 0) {
start = 0
}
if (start === 0) {
end = 100
} else {
pre = '...'
}
if (end > dataContent.length) {
end = dataContent.length
} else {
post = '...'
}
let matchContent = dataContent.substring(start, end)
// highlight all keywords
keywords.forEach(keyword => {
let regexStr = keyword
const specialRegex = /[^\w\s]+/ // match special characters
if (keyword.length === 1 && specialRegex.test(keyword)) {
regexStr = `\\${keyword}`
}
const regS = new RegExp(regexStr, 'gi')
matchContent = matchContent.replace(regS, '<span class="search-keyword">' + keyword + '</span>')
dataTitle = dataTitle.replace(regS, '<span class="search-keyword">' + keyword + '</span>')
})
str += '<div class="local-search__hit-item"><a href="' + dataUrl + '" class="search-result-title">' + dataTitle + '</a>'
count += 1
if (dataContent !== '') {
str += '<p class="search-result">' + pre + matchContent + post + '</p>'
}
}
str += '</div>'
}
})
if (count === 0) {
str += '<div id="local-search__hits-empty">' + GLOBAL_CONFIG.localSearch.languages.hits_empty.replace(/\$\{query}/, this.value.trim()) +
'</div>'
}
str += '</div>'
$resultContent.innerHTML = str
if (keywords[0] !== '') $loadingStatus.innerHTML = ''
window.pjax && window.pjax.refresh($resultContent)
})
})
}
searchClickFn() searchClickFn()
searchClickFnOnce() searchFnOnce()
// pjax // pjax
window.addEventListener('pjax:complete', () => { window.addEventListener('pjax:complete', () => {
!btf.isHidden($searchMask) && closeSearch() !btf.isHidden($searchMask) && closeSearch()
localSearch.highlightSearchWords(document.getElementById('article-container'))
searchClickFn() searchClickFn()
}) })
}) })

View File

@@ -1,10 +1,6 @@
document.addEventListener('DOMContentLoaded', function () { document.addEventListener('DOMContentLoaded', function () {
const translate = GLOBAL_CONFIG.translate const { defaultEncoding, translateDelay, msgToTraditionalChinese, msgToSimplifiedChinese } = GLOBAL_CONFIG.translate
const snackbarData = GLOBAL_CONFIG.Snackbar const snackbarData = GLOBAL_CONFIG.Snackbar
const defaultEncoding = translate.defaultEncoding // 網站默認語言1: 繁體中文, 2: 簡體中文
const translateDelay = translate.translateDelay // 延遲時間,若不在前, 要設定延遲翻譯時間, 如100表示100ms,默認為0
const msgToTraditionalChinese = translate.msgToTraditionalChinese // 此處可以更改為你想要顯示的文字
const msgToSimplifiedChinese = translate.msgToSimplifiedChinese // 同上,但兩處均不建議更改
let currentEncoding = defaultEncoding let currentEncoding = defaultEncoding
const targetEncodingCookie = 'translate-chn-cht' const targetEncodingCookie = 'translate-chn-cht'
let targetEncoding = let targetEncoding =
@@ -12,7 +8,7 @@ document.addEventListener('DOMContentLoaded', function () {
? defaultEncoding ? defaultEncoding
: Number(saveToLocal.get('translate-chn-cht')) : Number(saveToLocal.get('translate-chn-cht'))
let translateButtonObject let translateButtonObject
const isSnackbar = GLOBAL_CONFIG.Snackbar !== undefined const isSnackbar = snackbarData !== undefined
function setLang () { function setLang () {
document.documentElement.lang = targetEncoding === 1 ? 'zh-TW' : 'zh-CN' document.documentElement.lang = targetEncoding === 1 ? 'zh-TW' : 'zh-CN'
@@ -58,12 +54,12 @@ document.addEventListener('DOMContentLoaded', function () {
if (targetEncoding === 1) { if (targetEncoding === 1) {
currentEncoding = 1 currentEncoding = 1
targetEncoding = 2 targetEncoding = 2
translateButtonObject.innerHTML = msgToTraditionalChinese translateButtonObject.textContent = msgToTraditionalChinese
isSnackbar && btf.snackbarShow(snackbarData.cht_to_chs) isSnackbar && btf.snackbarShow(snackbarData.cht_to_chs)
} else if (targetEncoding === 2) { } else if (targetEncoding === 2) {
currentEncoding = 2 currentEncoding = 2
targetEncoding = 1 targetEncoding = 1
translateButtonObject.innerHTML = msgToSimplifiedChinese translateButtonObject.textContent = msgToSimplifiedChinese
isSnackbar && btf.snackbarShow(snackbarData.chs_to_cht) isSnackbar && btf.snackbarShow(snackbarData.chs_to_cht)
} }
saveToLocal.set(targetEncodingCookie, targetEncoding, 2) saveToLocal.set(targetEncodingCookie, targetEncoding, 2)
@@ -104,7 +100,7 @@ document.addEventListener('DOMContentLoaded', function () {
translateButtonObject = document.getElementById('translateLink') translateButtonObject = document.getElementById('translateLink')
if (translateButtonObject) { if (translateButtonObject) {
if (currentEncoding !== targetEncoding) { if (currentEncoding !== targetEncoding) {
translateButtonObject.innerHTML = translateButtonObject.textContent =
targetEncoding === 1 targetEncoding === 1
? msgToSimplifiedChinese ? msgToSimplifiedChinese
: msgToTraditionalChinese : msgToTraditionalChinese

View File

@@ -79,31 +79,21 @@ const btf = {
const hour = minute * 60 const hour = minute * 60
const day = hour * 24 const day = hour * 24
const month = day * 30 const month = day * 30
const { dateSuffix } = GLOBAL_CONFIG
let result if (!more) return parseInt(dateDiff / day)
if (more) {
const monthCount = dateDiff / month
const dayCount = dateDiff / day
const hourCount = dateDiff / hour
const minuteCount = dateDiff / minute
if (monthCount > 12) { const monthCount = dateDiff / month
result = datePost.toISOString().slice(0, 10) const dayCount = dateDiff / day
} else if (monthCount >= 1) { const hourCount = dateDiff / hour
result = parseInt(monthCount) + ' ' + GLOBAL_CONFIG.date_suffix.month const minuteCount = dateDiff / minute
} else if (dayCount >= 1) {
result = parseInt(dayCount) + ' ' + GLOBAL_CONFIG.date_suffix.day if (monthCount > 12) return datePost.toISOString().slice(0, 10)
} else if (hourCount >= 1) { if (monthCount >= 1) return `${parseInt(monthCount)} ${dateSuffix.month}`
result = parseInt(hourCount) + ' ' + GLOBAL_CONFIG.date_suffix.hour if (dayCount >= 1) return `${parseInt(dayCount)} ${dateSuffix.day}`
} else if (minuteCount >= 1) { if (hourCount >= 1) return `${parseInt(hourCount)} ${dateSuffix.hour}`
result = parseInt(minuteCount) + ' ' + GLOBAL_CONFIG.date_suffix.min if (minuteCount >= 1) return `${parseInt(minuteCount)} ${dateSuffix.min}`
} else { return dateSuffix.just
result = GLOBAL_CONFIG.date_suffix.just
}
} else {
result = parseInt(dateDiff / day)
}
return result
}, },
loadComment: (dom, callback) => { loadComment: (dom, callback) => {
@@ -196,10 +186,9 @@ const btf = {
}, },
unwrap: el => { unwrap: el => {
const elParentNode = el.parentNode const parent = el.parentNode
if (elParentNode !== document.body) { if (parent && parent !== document.body) {
elParentNode.parentNode.insertBefore(el, elParentNode) parent.replaceChild(el, parent)
elParentNode.parentNode.removeChild(elParentNode)
} }
}, },
@@ -221,13 +210,7 @@ const btf = {
const service = GLOBAL_CONFIG.lightbox const service = GLOBAL_CONFIG.lightbox
if (service === 'mediumZoom') { if (service === 'mediumZoom') {
const zoom = mediumZoom(ele) mediumZoom(ele, { background: 'var(--zoom-bg)' })
zoom.on('open', e => {
const photoBg = document.documentElement.getAttribute('data-theme') === 'dark' ? '#121212' : '#fff'
zoom.update({
background: photoBg
})
})
} }
if (service === 'fancybox') { if (service === 'fancybox') {
@@ -243,7 +226,30 @@ const btf = {
Fancybox.bind('[data-fancybox]', { Fancybox.bind('[data-fancybox]', {
Hash: false, Hash: false,
Thumbs: { Thumbs: {
autoStart: false showOnStart: false
},
Images: {
Panzoom: {
maxScale: 4
}
},
Carousel: {
transition: 'slide'
},
Toolbar: {
display: {
left: ['infobar'],
middle: [
'zoomIn',
'zoomOut',
'toggle1to1',
'rotateCCW',
'rotateCW',
'flipX',
'flipY'
],
right: ['slideshow', 'thumbs', 'close']
}
} }
}) })
window.fancyboxRun = true window.fancyboxRun = true
@@ -252,7 +258,7 @@ const btf = {
}, },
initJustifiedGallery: function (selector) { initJustifiedGallery: function (selector) {
selector.forEach(function (i) { const runJustifiedGallery = i => {
if (!btf.isHidden(i)) { if (!btf.isHidden(i)) {
fjGallery(i, { fjGallery(i, {
itemSelector: '.fj-gallery-item', itemSelector: '.fj-gallery-item',
@@ -263,7 +269,10 @@ const btf = {
} }
}) })
} }
}) }
if (Array.from(selector).length === 0) runJustifiedGallery(selector)
else selector.forEach(i => { runJustifiedGallery(i) })
}, },
updateAnchor: (anchor) => { updateAnchor: (anchor) => {
@@ -286,5 +295,13 @@ const btf = {
const scrollPercentRounded = Math.round(scrollPercent * 100) const scrollPercentRounded = Math.round(scrollPercent * 100)
const percentage = (scrollPercentRounded > 100) ? 100 : (scrollPercentRounded <= 0) ? 0 : scrollPercentRounded const percentage = (scrollPercentRounded > 100) ? 100 : (scrollPercentRounded <= 0) ? 0 : scrollPercentRounded
return percentage return percentage
},
addModeChange: (name, fn) => {
if (window.themeChange && window.themeChange[name]) return
window.themeChange = {
...window.themeChange,
[name]: fn
}
} }
} }