From d8a1fa6417e261c0ceccdb03aba07a8101253f0f Mon Sep 17 00:00:00 2001 From: Jerry Date: Sun, 15 Sep 2024 00:43:03 +0800 Subject: [PATCH] =?UTF-8?q?breaking=20change:=201.=20=E9=83=A8=E5=88=86?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E6=9B=B4=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit feat: 1. 移除 messenger 聊天插件 2. 更新 fackbook 版本號 3. 增加 香港繁體、日文和韓語 4. 使用的新的複製api 代替舊的 5. 增加 umami 分析 6. 增加 umami 獲取訪問量/訪客數 7. snackbar 增加透明度 8. 文章頁下, nav fixed 下 顯示文章標題 improvement: 1. 代碼優化 2. 修改部分用語 3. 回復之前的相對時間邏輯 4. timeline tag 樣式優化 5. 優化 seo 6. 優化 artalk 的最新評論 fix: 1. tag-hide toggle 圓角問題 2. lazyload 為 false 時,artalk 無法正常加載評論的 bug 3. 修復 gallery 出現抖動的 bug --- README.md | 2 +- README_CN.md | 2 +- _config.yml | 37 ++- languages/default.yml | 58 ++--- languages/en.yml | 60 ++--- languages/ja.yml | 121 +++++++++ languages/ko.yml | 121 +++++++++ languages/zh-CN.yml | 44 ++-- languages/zh-HK.yml | 121 +++++++++ languages/zh-TW.yml | 61 +++-- layout/includes/additional-js.pug | 21 +- layout/includes/footer.pug | 15 +- layout/includes/head/pwa.pug | 24 +- layout/includes/header/index.pug | 15 +- layout/includes/header/menu_item.pug | 34 +-- layout/includes/header/nav.pug | 16 +- layout/includes/header/post-info.pug | 90 ++++--- layout/includes/header/social.pug | 10 +- layout/includes/layout.pug | 3 +- layout/includes/loading/fullpage-loading.pug | 6 +- layout/includes/loading/index.pug | 9 +- layout/includes/mixins/article-sort.pug | 12 +- layout/includes/mixins/indexPostUI.pug | 55 ++-- layout/includes/post/post-copyright.pug | 12 +- layout/includes/post/reward.pug | 5 +- layout/includes/sidebar.pug | 2 +- layout/includes/third-party/abcjs/index.pug | 2 +- .../third-party/card-post-count/fb.pug | 4 +- layout/includes/third-party/chat/chatra.pug | 18 +- layout/includes/third-party/chat/crisp.pug | 22 +- layout/includes/third-party/chat/index.pug | 4 +- .../includes/third-party/chat/messenger.pug | 44 ---- layout/includes/third-party/chat/tidio.pug | 8 +- .../includes/third-party/comments/artalk.pug | 2 +- .../comments/facebook_comments.pug | 4 +- layout/includes/third-party/math/index.pug | 16 +- layout/includes/third-party/math/katex.pug | 10 +- layout/includes/third-party/math/mermaid.pug | 14 +- .../third-party/newest-comments/artalk.pug | 103 +++----- .../third-party/newest-comments/common.pug | 60 +++++ .../newest-comments/disqus-comment.pug | 68 +---- .../newest-comments/github-issues.pug | 76 +----- .../third-party/newest-comments/remark42.pug | 68 +---- .../newest-comments/twikoo-comment.pug | 72 +----- .../third-party/newest-comments/valine.pug | 72 +----- .../third-party/newest-comments/waline.pug | 67 +---- layout/includes/third-party/pjax.pug | 91 +++---- .../includes/third-party/umami_analytics.pug | 65 +++++ layout/includes/widget/card_webinfo.pug | 14 +- layout/page.pug | 2 +- package.json | 2 +- scripts/events/comment.js | 13 +- scripts/events/merge_config.js | 32 ++- scripts/helpers/aside_archives.js | 98 +++---- scripts/helpers/aside_categories.js | 82 +++--- scripts/helpers/inject_head_js.js | 240 +++++++----------- scripts/helpers/page.js | 36 +-- scripts/helpers/series.js | 16 +- scripts/tag/button.js | 9 +- scripts/tag/flink.js | 39 ++- scripts/tag/series.js | 20 +- scripts/tag/tabs.js | 22 +- scripts/tag/timeline.js | 2 +- source/css/_global/function.styl | 5 +- source/css/_layout/chat.styl | 11 +- source/css/_layout/head.styl | 18 +- source/css/_layout/third-party.styl | 5 +- source/css/_page/archives.styl | 1 + source/css/_page/tags.styl | 2 +- source/css/_tags/gallery.styl | 4 + source/css/_tags/hide.styl | 2 +- source/css/_tags/timeline.styl | 4 +- source/css/var.styl | 16 +- source/js/main.js | 23 +- source/js/tw_cn.js | 36 ++- source/js/utils.js | 23 +- 76 files changed, 1321 insertions(+), 1302 deletions(-) create mode 100644 languages/ja.yml create mode 100644 languages/ko.yml create mode 100644 languages/zh-HK.yml delete mode 100644 layout/includes/third-party/chat/messenger.pug create mode 100644 layout/includes/third-party/newest-comments/common.pug create mode 100644 layout/includes/third-party/umami_analytics.pug diff --git a/README.md b/README.md index dfa63f89b..ce934c9bb 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,7 @@ npm i hexo-theme-butterfly - [x] Share (Sharejs/Addtoany) - [X] Comment (Disqus/Disqusjs/Livere/Gitalk/Valine/Waline/Utterances/Facebook Comments/Twikoo/Giscus/Remark42/artalk) - [x] Multiple Comment System Support -- [x] Online Chats (Chatra/Tidio/Daovoice/Crisp/messenger) +- [x] Online Chats (Chatra/Tidio/Daovoice/Crisp) - [x] Web analytics - [x] Google AdSense - [x] Webmaster Verification diff --git a/README_CN.md b/README_CN.md index bda0400cb..205d71d35 100644 --- a/README_CN.md +++ b/README_CN.md @@ -86,7 +86,7 @@ theme: butterfly - [x] 多種分享系統(Sharejs/Addtoany) - [X] 多種評論系統(Disqus/Disqusjs/Livere/Gitalk/Valine/Waline/Utterances/Facebook Comments/Twikoo/Giscus/Remark42/artalk) - [x] 支持雙評論部署 -- [x] 多種在線聊天(Chatra/Tidio/Daovoice/Crisp/messenger) +- [x] 多種在線聊天(Chatra/Tidio/Daovoice/Crisp) - [x] 多種分析系統 - [x] 谷歌廣告/手動廣告位置 - [x] 各種站長驗證 diff --git a/_config.yml b/_config.yml index 67638ba34..a448599af 100644 --- a/_config.yml +++ b/_config.yml @@ -645,7 +645,7 @@ artalk: # -------------------------------------- chat: - # Choose: chatra/tidio/daovoice/crisp/messenger + # Choose: chatra/tidio/daovoice/crisp # Leave it empty if you don't need chat use: # Chat Button [recommend] @@ -670,11 +670,6 @@ daovoice: crisp: website_id: -# https://developers.facebook.com/docs/messenger-platform/discovery/facebook-chat-plugin/ -messenger: - pageID: - lang: zh_TW - # -------------------------------------- # Analysis # -------------------------------------- @@ -691,6 +686,20 @@ cloudflare_analytics: # https://clarity.microsoft.com/ microsoft_clarity: +# https://umami.is/ +umami_analytics: + enable: false + # For self-hosted setups, configure the hostname of the Umami instance + serverURL: + website_id: + option: + UV_PV: + site_uv: false + site_pv: false + page_pv: false + # Umami Cloud (API key) / self-hosted Umami (token) + token: + # -------------------------------------- # Advertisement # -------------------------------------- @@ -787,29 +796,29 @@ beautify: # Specify the field to beautify (site or post) field: post # Specify the icon to be used as a prefix for the title, such as '\f0c1' - title-prefix-icon: + title_prefix_icon: # Specify the color of the title prefix icon, such as '#F47466' - title-prefix-icon-color: + title_prefix_icon_color: # Global font settings # Don't modify the following settings unless you know how they work font: - global-font-size: - code-font-size: - font-family: - code-font-family: + global_font_size: + code_font_size: + font_family: + code_font_family: # Font settings for the site title and site subtitle blog_title_font: font_link: - font-family: + font_family: # The setting of divider icon hr_icon: enable: true # The unicode value of Font Awesome icon, such as '\3423' icon: - icon-top: + icon_top: # Typewriter Effect # https://github.com/disjukr/activate-power-mode diff --git a/languages/default.yml b/languages/default.yml index bea841e1f..f35cb35bc 100644 --- a/languages/default.yml +++ b/languages/default.yml @@ -4,11 +4,11 @@ footer: copy: success: Copy Successful - error: Copy Error + error: Copy Failed noSupport: Browser Not Supported page: - articles: Articles + articles: All Articles tag: Tag category: Category archives: Archives @@ -29,26 +29,26 @@ post: author: Author link: Link copyright_notice: Copyright Notice - copyright_content: 'All articles in this blog are licensed under %s unless stating additionally.' + copyright_content: 'All articles on this blog are licensed under %s unless otherwise stated.' recommend: Related Articles - edit: Edited on + edit: Edit search: title: Search - load_data: Loading the Database + load_data: Loading Database input_placeholder: Search for Posts algolia_search: - hits_empty: "We didn't find any results for the search: ${query}." + hits_empty: 'No results found for: ${query}' hits_stats: '${hits} results found in ${time} ms' local_search: - hits_empty: "We didn't find any results for the search: ${query}" - hits_stats: '${hits} results found' + hits_empty: 'No results found for: ${query}' + hits_stats: '${hits} articles found' pagination: prev: Previous next: Next -comment: Comment +comment: Comments aside: articles: Articles @@ -58,29 +58,29 @@ aside: card_categories: Categories card_tags: Tags card_archives: Archives - card_recent_post: Recent Post + card_recent_post: Recent Posts card_webinfo: - headline: Info - article_name: Article + headline: Website Info + article_name: Article Count runtime: name: Runtime unit: days last_push_date: name: Last Update - site_wordcount: Total Count - site_uv_name: UV - site_pv_name: PV + site_wordcount: Total Word Count + site_uv_name: Unique Visitors + site_pv_name: Page Views more_button: View More card_newest_comments: headline: Latest Comments - loading_text: loading... + loading_text: Loading... error: Unable to retrieve comments, please check the configuration zero: No comments - image: image - link: link - code: code + image: Image + link: Link + code: Code card_toc: Contents - card_post_series: Series + card_post_series: Post Series date_suffix: just: Just now @@ -93,21 +93,21 @@ donate: Sponsor share: Share rightside: - readmode_title: Read Mode - translate_title: Toggle Between Traditional Chinese And Simplified Chinese - night_mode_title: Toggle Between Light And Dark Mode - back_to_top: Back To Top - toc: Table Of Contents - scroll_to_comment: Scroll To Comments - setting: Setting - aside: Toggle between Single-column and Double-column + readmode_title: Reading Mode + translate_title: Toggle Between Traditional and Simplified Chinese + night_mode_title: Toggle Between Light and Dark Mode + back_to_top: Back to Top + toc: Table of Contents + scroll_to_comment: Scroll to Comments + setting: Settings + aside: Toggle Between Single-column and Double-column chat: Chat copy_copyright: author: Author link: Link source: Source - info: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source. + info: Copyright belongs to the author. For commercial use, please contact the author for authorization. For non-commercial use, please indicate the source. Snackbar: chs_to_cht: You have switched to Traditional Chinese diff --git a/languages/en.yml b/languages/en.yml index 26be42b56..f35cb35bc 100644 --- a/languages/en.yml +++ b/languages/en.yml @@ -4,11 +4,11 @@ footer: copy: success: Copy Successful - error: Copy Error + error: Copy Failed noSupport: Browser Not Supported page: - articles: Articles + articles: All Articles tag: Tag category: Category archives: Archives @@ -29,26 +29,26 @@ post: author: Author link: Link copyright_notice: Copyright Notice - copyright_content: 'All articles in this blog are licensed under %s unless stating additionally.' + copyright_content: 'All articles on this blog are licensed under %s unless otherwise stated.' recommend: Related Articles - edit: Edited on + edit: Edit search: title: Search - load_data: Loading the Database + load_data: Loading Database input_placeholder: Search for Posts algolia_search: - hits_empty: "We didn't find any results for the search: ${query}." + hits_empty: 'No results found for: ${query}' hits_stats: '${hits} results found in ${time} ms' local_search: - hits_empty: "We didn't find any results for the search: ${query}" - hits_stats: '${hits} results found' + hits_empty: 'No results found for: ${query}' + hits_stats: '${hits} articles found' pagination: prev: Previous next: Next -comment: Comment +comment: Comments aside: articles: Articles @@ -58,29 +58,29 @@ aside: card_categories: Categories card_tags: Tags card_archives: Archives - card_recent_post: Recent Post + card_recent_post: Recent Posts card_webinfo: - headline: Info - article_name: Article + headline: Website Info + article_name: Article Count runtime: name: Runtime unit: days last_push_date: name: Last Update - site_wordcount: Total Count - site_uv_name: UV - site_pv_name: PV + site_wordcount: Total Word Count + site_uv_name: Unique Visitors + site_pv_name: Page Views more_button: View More card_newest_comments: headline: Latest Comments - loading_text: loading... + loading_text: Loading... error: Unable to retrieve comments, please check the configuration zero: No comments - image: image - link: link - code: code + image: Image + link: Link + code: Code card_toc: Contents - card_post_series: Series + card_post_series: Post Series date_suffix: just: Just now @@ -93,21 +93,21 @@ donate: Sponsor share: Share rightside: - readmode_title: Read Mode - translate_title: Toggle Between Traditional Chinese And Simplified Chinese - night_mode_title: Toggle Between Light And Dark Mode - back_to_top: Back To Top - toc: Table Of Contents - scroll_to_comment: Scroll To Comments - setting: Setting - aside: Toggle between Single-column and Double-column + readmode_title: Reading Mode + translate_title: Toggle Between Traditional and Simplified Chinese + night_mode_title: Toggle Between Light and Dark Mode + back_to_top: Back to Top + toc: Table of Contents + scroll_to_comment: Scroll to Comments + setting: Settings + aside: Toggle Between Single-column and Double-column chat: Chat copy_copyright: author: Author link: Link source: Source - info: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source. + info: Copyright belongs to the author. For commercial use, please contact the author for authorization. For non-commercial use, please indicate the source. Snackbar: chs_to_cht: You have switched to Traditional Chinese @@ -118,4 +118,4 @@ Snackbar: loading: Loading... load_more: Load More -error404: Page Not Found \ No newline at end of file +error404: Page Not Found diff --git a/languages/ja.yml b/languages/ja.yml new file mode 100644 index 000000000..1a291f8d0 --- /dev/null +++ b/languages/ja.yml @@ -0,0 +1,121 @@ +footer: + framework: フレームワーク + theme: テーマ + +copy: + success: コピー成功 + error: コピー失敗 + noSupport: ブラウザが対応していません + +page: + articles: 記事一覧 + tag: タグ + category: カテゴリ + archives: アーカイブ + +card_post_count: コメント数 + +no_title: タイトルなし + +post: + created: 作成日 + updated: 更新日 + wordcount: 総文字数 + min2read: 読む時間 + min2read_unit: 分 + page_pv: 閲覧数 + comments: コメント数 + copyright: + author: 著者 + link: リンク + copyright_notice: 著作権表示 + copyright_content: 'このブログのすべての記事は、%s ライセンスの下で提供されており、特に明記されていない限り、すべての権利を留保します。転載時には出典を明記してください: %s。' + recommend: 関連記事 + edit: 編集 + +search: + title: 検索 + load_data: データベースを読み込んでいます + input_placeholder: 記事を検索 + algolia_search: + hits_empty: '${query} の検索結果が見つかりませんでした。' + hits_stats: '${hits} 件の結果が ${time}ms で見つかりました' + local_search: + hits_empty: '${query} の検索結果が見つかりませんでした。' + hits_stats: '${hits} 件の記事が見つかりました' + +pagination: + prev: 前へ + next: 次へ + +comment: コメント + +aside: + articles: 記事 + tags: タグ + categories: カテゴリ + card_announcement: お知らせ + card_categories: カテゴリ + card_tags: タグ + card_archives: アーカイブ + card_recent_post: 最近の記事 + card_webinfo: + headline: サイト情報 + article_name: 記事数 + runtime: + name: 稼働時間 + unit: 日 + last_push_date: + name: 最終更新日 + site_wordcount: 総文字数 + site_uv_name: ユーザー数 + site_pv_name: ページビュー数 + more_button: もっと見る + card_newest_comments: + headline: 最新コメント + loading_text: ローディング中... + error: コメントを取得できませんでした。設定を確認してください。 + zero: コメントがありません + image: 画像 + link: リンク + code: コード + card_toc: 目次 + card_post_series: シリーズ記事 + +date_suffix: + just: たった今 + min: 分前 + hour: 時間前 + day: 日前 + month: ヶ月前 + +donate: 寄付 +share: 共有 + +rightside: + readmode_title: 読書モード + translate_title: 簡体字と繁体字の切り替え + night_mode_title: ライトモード/ダークモード切り替え + back_to_top: トップに戻る + toc: 目次 + scroll_to_comment: コメントへ移動 + setting: 設定 + aside: シングルカラムとダブルカラムの切り替え + chat: チャット + +copy_copyright: + author: 著者 + link: リンク + source: ソース + info: 著作権は著者に帰属します。商業的利用の場合は著者に連絡して許可を得てください。非商業的利用の場合は出典を明記してください。 + +Snackbar: + chs_to_cht: 繁体字に切り替えました + cht_to_chs: 簡体字に切り替えました + day_to_night: ダークモードに切り替えました + night_to_day: ライトモードに切り替えました + +loading: ローディング中... +load_more: もっと見る + +error404: ページが見つかりません diff --git a/languages/ko.yml b/languages/ko.yml new file mode 100644 index 000000000..7dca8da03 --- /dev/null +++ b/languages/ko.yml @@ -0,0 +1,121 @@ +footer: + framework: 프레임워크 + theme: 테마 + +copy: + success: 복사 성공 + error: 복사 실패 + noSupport: 브라우저가 지원되지 않음 + +page: + articles: 모든 글 + tag: 태그 + category: 카테고리 + archives: 아카이브 + +card_post_count: 댓글 수 + +no_title: 제목 없음 + +post: + created: 작성일 + updated: 수정일 + wordcount: 총 글자 수 + min2read: 읽기 시간 + min2read_unit: 분 + page_pv: 조회수 + comments: 댓글 + copyright: + author: 작성자 + link: 링크 + copyright_notice: 저작권 고지 + copyright_content: '이 블로그의 모든 글은 %s 라이선스를 따르며, 별도로 명시되지 않는 한 모든 권리를 보유합니다. 재배포 시 출처를 명시해 주세요: %s.' + recommend: 관련 글 + edit: 편집 + +search: + title: 검색 + load_data: 데이터베이스 로드 중 + input_placeholder: 글 검색 + algolia_search: + hits_empty: '${query}에 대한 결과를 찾을 수 없습니다.' + hits_stats: '${hits}개의 결과를 ${time}ms 만에 찾음' + local_search: + hits_empty: '${query}에 대한 결과를 찾을 수 없습니다.' + hits_stats: '${hits}개의 글을 찾음' + +pagination: + prev: 이전 + next: 다음 + +comment: 댓글 + +aside: + articles: 글 + tags: 태그 + categories: 카테고리 + card_announcement: 공지 + card_categories: 카테고리 + card_tags: 태그 + card_archives: 아카이브 + card_recent_post: 최근 글 + card_webinfo: + headline: 사이트 정보 + article_name: 글 수 + runtime: + name: 운영 시간 + unit: 일 + last_push_date: + name: 마지막 업데이트 + site_wordcount: 총 글자 수 + site_uv_name: 방문자 수 + site_pv_name: 총 조회수 + more_button: 더 보기 + card_newest_comments: + headline: 최신 댓글 + loading_text: 로딩 중... + error: 댓글을 가져올 수 없습니다. 설정을 확인해 주세요. + zero: 댓글 없음 + image: 이미지 + link: 링크 + code: 코드 + card_toc: 목차 + card_post_series: 시리즈 글 + +date_suffix: + just: 방금 + min: 분 전 + hour: 시간 전 + day: 일 전 + month: 달 전 + +donate: 후원 +share: 공유 + +rightside: + readmode_title: 읽기 모드 + translate_title: 번체와 간체 전환 + night_mode_title: 라이트/다크 모드 전환 + back_to_top: 맨 위로 + toc: 목차 + scroll_to_comment: 댓글로 이동 + setting: 설정 + aside: 단일/이중 열 전환 + chat: 채팅 + +copy_copyright: + author: 작성자 + link: 링크 + source: 출처 + info: 저작권은 작성자에게 있습니다. 상업적 사용을 위해서는 작성자의 허가를 받아야 하며, 비상업적 사용 시에는 출처를 명시해 주세요. + +Snackbar: + chs_to_cht: 번체로 전환되었습니다. + cht_to_chs: 간체로 전환되었습니다. + day_to_night: 다크 모드로 전환되었습니다. + night_to_day: 라이트 모드로 전환되었습니다. + +loading: 로딩 중... +load_more: 더 보기 + +error404: 페이지를 찾을 수 없습니다. diff --git a/languages/zh-CN.yml b/languages/zh-CN.yml index 18206bae0..1afa96b4b 100644 --- a/languages/zh-CN.yml +++ b/languages/zh-CN.yml @@ -4,45 +4,45 @@ footer: copy: success: 复制成功 - error: 复制错误 + error: 复制失败 noSupport: 浏览器不支持 page: - articles: 文章总览 + articles: 全部文章 tag: 标签 category: 分类 archives: 归档 card_post_count: 条评论 -no_title: 无题 +no_title: 无标题 post: created: 发表于 updated: 更新于 - wordcount: 字数总计 + wordcount: 总字数 min2read: 阅读时长 min2read_unit: 分钟 - page_pv: 阅读量 + page_pv: 浏览量 comments: 评论数 copyright: author: 文章作者 link: 文章链接 copyright_notice: 版权声明 copyright_content: '本博客所有文章除特别声明外,均采用 - %s 许可协议。转载请注明来自 %s!' + %s 许可协议。转载请注明来源 %s!' recommend: 相关推荐 edit: 编辑 search: title: 搜索 - load_data: 数据库加载中 + load_data: 数据加载中 input_placeholder: 搜索文章 algolia_search: - hits_empty: '找不到您查询的内容:${query}' - hits_stats: '找到 ${hits} 条结果,用时 ${time} 毫秒' + hits_empty: '未找到符合您查询的内容:${query}' + hits_stats: '找到 ${hits} 条结果,耗时 ${time} 毫秒' local_search: - hits_empty: '找不到您查询的内容:${query}' + hits_empty: '未找到符合您查询的内容:${query}' hits_stats: '共找到 ${hits} 篇文章' pagination: @@ -61,22 +61,22 @@ aside: card_archives: 归档 card_recent_post: 最新文章 card_webinfo: - headline: 网站资讯 + headline: 网站信息 article_name: 文章数目 runtime: - name: 已运行时间 + name: 运行时间 unit: 天 last_push_date: name: 最后更新时间 site_wordcount: 本站总字数 site_uv_name: 本站访客数 - site_pv_name: 本站总访问量 + site_pv_name: 本站总浏览量 more_button: 查看更多 card_newest_comments: headline: 最新评论 - loading_text: 正在加载中... + loading_text: 加载中... error: 无法获取评论,请确认相关配置是否正确 - zero: 没有评论 + zero: 暂无评论 image: 图片 link: 链接 code: 代码 @@ -96,10 +96,10 @@ share: 分享 rightside: readmode_title: 阅读模式 translate_title: 简繁转换 - night_mode_title: 浅色和深色模式转换 + night_mode_title: 日间和夜间模式切换 back_to_top: 回到顶部 toc: 目录 - scroll_to_comment: 直达评论 + scroll_to_comment: 前往评论 setting: 设置 aside: 单栏和双栏切换 chat: 聊天 @@ -111,12 +111,12 @@ copy_copyright: info: 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 Snackbar: - chs_to_cht: 你已切换为繁体中文 - cht_to_chs: 你已切换为简体中文 - day_to_night: 你已切换为深色模式 - night_to_day: 你已切换为浅色模式 + chs_to_cht: 已切换为繁体中文 + cht_to_chs: 已切换为简体中文 + day_to_night: 已切换为深色模式 + night_to_day: 已切换为浅色模式 loading: 加载中... load_more: 加载更多 -error404: 页面没有找到 +error404: 页面未找到 diff --git a/languages/zh-HK.yml b/languages/zh-HK.yml new file mode 100644 index 000000000..b1f99d7e8 --- /dev/null +++ b/languages/zh-HK.yml @@ -0,0 +1,121 @@ +footer: + framework: 框架 + theme: 主題 + +copy: + success: 複製成功 + error: 複製失敗 + noSupport: 瀏覽器不支援 + +page: + articles: 全部文章 + tag: 標籤 + category: 分類 + archives: 歸檔 + +card_post_count: 條評論 + +no_title: 無標題 + +post: + created: 發表於 + updated: 更新於 + wordcount: 字數統計 + min2read: 閱讀時間 + min2read_unit: 分鐘 + page_pv: 瀏覽量 + comments: 評論數 + copyright: + author: 文章作者 + link: 文章連結 + copyright_notice: 版權聲明 + copyright_content: '除特別聲明外,本博客所有文章均採用%s 授權協議。轉載請註明出處:%s。' + recommend: 相關文章 + edit: 編輯 + +search: + title: 搜尋 + load_data: 正在加載數據庫 + input_placeholder: 搜尋文章 + algolia_search: + hits_empty: '未找到相關內容:${query}' + hits_stats: '找到 ${hits} 條結果,耗時 ${time} 毫秒' + local_search: + hits_empty: '未找到相關內容:${query}' + hits_stats: '找到 ${hits} 篇文章' + +pagination: + prev: 上一頁 + next: 下一頁 + +comment: 評論 + +aside: + articles: 文章 + tags: 標籤 + categories: 分類 + card_announcement: 公告 + card_categories: 分類 + card_tags: 標籤 + card_archives: 歸檔 + card_recent_post: 最新文章 + card_webinfo: + headline: 網站資訊 + article_name: 文章數目 + runtime: + name: 運行時間 + unit: 天 + last_push_date: + name: 最後更新時間 + site_wordcount: 總字數 + site_uv_name: 訪客數 + site_pv_name: 總瀏覽量 + more_button: 查看更多 + card_newest_comments: + headline: 最新評論 + loading_text: 正在加載... + error: 無法取得評論,請確認配置是否正確 + zero: 暫無評論 + image: 圖片 + link: 連結 + code: 代碼 + card_toc: 目錄 + card_post_series: 系列文章 + +date_suffix: + just: 剛剛 + min: 分鐘前 + hour: 小時前 + day: 天前 + month: 個月前 + +donate: 贊助 +share: 分享 + +rightside: + readmode_title: 閱讀模式 + translate_title: 簡繁轉換 + night_mode_title: 切換日夜模式 + back_to_top: 回到頂部 + toc: 目錄 + scroll_to_comment: 前往評論 + setting: 設定 + aside: 單欄與雙欄切換 + chat: 聊天 + +copy_copyright: + author: 作者 + link: 連結 + source: 來源 + info: 版權屬於作者所有。商業用途請聯絡作者獲得授權,非商業用途請註明出處。 + +Snackbar: + chs_to_cht: 已切換為繁體中文 + cht_to_chs: 已切換為簡體中文 + day_to_night: 已切換為深色模式 + night_to_day: 已切換為淺色模式 + +loading: 正在加載... +load_more: 加載更多 + +error404: 未找到頁面 diff --git a/languages/zh-TW.yml b/languages/zh-TW.yml index 929df6030..c91cb73a1 100644 --- a/languages/zh-TW.yml +++ b/languages/zh-TW.yml @@ -4,45 +4,44 @@ footer: copy: success: 複製成功 - error: 複製錯誤 + error: 複製失敗 noSupport: 瀏覽器不支援 page: - articles: 文章總覽 + articles: 所有文章 tag: 標籤 category: 分類 archives: 歸檔 -card_post_count: 條評論 +card_post_count: 則評論 -no_title: 無題 +no_title: 無標題 post: created: 發表於 updated: 更新於 - wordcount: 字數總計 - min2read: 閱讀時長 + wordcount: 總字數 + min2read: 閱讀時間 min2read_unit: 分鐘 - page_pv: 閱讀量 + page_pv: 瀏覽量 comments: 評論數 copyright: author: 文章作者 link: 文章連結 - copyright_notice: 版權宣告 - copyright_content: '本部落格所有文章除特別宣告外,均採用 - %s 許可協議。轉載請註明來自 %s!' + copyright_notice: 版權聲明 + copyright_content: '本部落格所有文章除特別聲明外,均採用%s 授權協議。轉載請註明來源 %s!' recommend: 相關推薦 edit: 編輯 search: title: 搜尋 - load_data: 資料庫載入中 + load_data: 資料載入中 input_placeholder: 搜尋文章 algolia_search: - hits_empty: '找不到您查詢的內容:${query}' - hits_stats: '找到 ${hits} 條結果,用時 ${time} 毫秒' + hits_empty: '找不到符合您查詢的內容:${query}' + hits_stats: '找到 ${hits} 筆結果,耗時 ${time} 毫秒' local_search: - hits_empty: '找不到您查詢的內容:${query}' + hits_empty: '找不到符合您查詢的內容:${query}' hits_stats: '共找到 ${hits} 篇文章' pagination: @@ -62,21 +61,21 @@ aside: card_recent_post: 最新文章 card_webinfo: headline: 網站資訊 - article_name: 文章數目 + article_name: 文章數量 runtime: - name: 已執行時間 + name: 運行時間 unit: 天 last_push_date: name: 最後更新時間 - site_wordcount: 本站總字數 - site_uv_name: 本站訪客數 - site_pv_name: 本站總訪問量 + site_wordcount: 總字數 + site_uv_name: 訪客數 + site_pv_name: 總瀏覽量 more_button: 檢視更多 card_newest_comments: headline: 最新評論 - loading_text: 正在載入中... + loading_text: 載入中... error: 無法獲取評論,請確認相關配置是否正確 - zero: 沒有評論 + zero: 尚無評論 image: 圖片 link: 連結 code: 程式碼 @@ -95,11 +94,11 @@ share: 分享 rightside: readmode_title: 閱讀模式 - translate_title: 簡繁轉換 - night_mode_title: 淺色和深色模式轉換 - back_to_top: 回到頂部 + translate_title: 繁簡轉換 + night_mode_title: 日夜模式切換 + back_to_top: 回到頂端 toc: 目錄 - scroll_to_comment: 直達評論 + scroll_to_comment: 前往評論 setting: 設定 aside: 單欄和雙欄切換 chat: 聊天 @@ -108,15 +107,15 @@ copy_copyright: author: 作者 link: 連結 source: 來源 - info: 著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。 + info: 著作權歸作者所有。如需商業轉載,請聯絡作者獲得授權,非商業轉載請註明出處。 Snackbar: - chs_to_cht: 你已切換為繁體中文 - cht_to_chs: 你已切換為簡體中文 - day_to_night: 你已切換為深色模式 - night_to_day: 你已切換為淺色模式 + chs_to_cht: 已切換為繁體中文 + cht_to_chs: 已切換為簡體中文 + day_to_night: 已切換為深色模式 + night_to_day: 已切換為淺色模式 loading: 載入中... load_more: 載入更多 -error404: 頁面沒有找到 +error404: 找不到頁面 diff --git a/layout/includes/additional-js.pug b/layout/includes/additional-js.pug index 785e9345e..772893714 100644 --- a/layout/includes/additional-js.pug +++ b/layout/includes/additional-js.pug @@ -5,10 +5,8 @@ div if theme.translate.enable script(src=url_for(theme.asset.translate)) - if theme.lightbox === 'medium_zoom' - script(src=url_for(theme.asset.medium_zoom)) - else if theme.lightbox === 'fancybox' - script(src=url_for(theme.asset.fancybox)) + if theme.lightbox + script(src=url_for(theme.asset[theme.lightbox])) if theme.instantpage script(src=url_for(theme.asset.instantpage), type='module') @@ -30,7 +28,6 @@ div include ./third-party/subtitle.pug include ./third-party/math/index.pug - include ./third-party/abcjs/index.pug if commentsJsLoad @@ -39,27 +36,25 @@ div != partial("includes/third-party/prismjs", {}, { cache: true }) if theme.aside.enable && theme.aside.card_newest_comments.enable - if theme.pjax.enable - != partial("includes/third-party/newest-comments/index", {}, { cache: true }) - else if (!is_post() && page.aside !== false) + if theme.pjax.enable || (!is_post() && page.aside !== false) != partial("includes/third-party/newest-comments/index", {}, { cache: true }) != fragment_cache('injectBottom', function(){return injectHtml(theme.inject.bottom)}) != partial("includes/third-party/effect", {}, { cache: true }) - != partial("includes/third-party/chat/index", {}, { cache: true }) if theme.aplayerInject && theme.aplayerInject.enable - if theme.pjax.enable || theme.aplayerInject.per_page - include ./third-party/aplayer.pug - else if page.aplayer + if theme.pjax.enable || theme.aplayerInject.per_page || page.aplayer include ./third-party/aplayer.pug if theme.pjax.enable != partial("includes/third-party/pjax", {}, { cache: true }) + if theme.umami_analytics.enable + != partial("includes/third-party/umami_analytics", {}, { cache: true }) + if theme.busuanzi.site_uv || theme.busuanzi.site_pv || theme.busuanzi.page_pv 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}) \ No newline at end of file + != partial('includes/third-party/search/index', {}, { cache: true }) \ No newline at end of file diff --git a/layout/includes/footer.pug b/layout/includes/footer.pug index 4d2ae791d..f6c3e87b7 100644 --- a/layout/includes/footer.pug +++ b/layout/includes/footer.pug @@ -1,11 +1,12 @@ #footer-wrap if theme.footer.owner.enable - - var now = new Date() - - var nowYear = now.getFullYear() - if theme.footer.owner.since && theme.footer.owner.since != nowYear - .copyright!= `©${theme.footer.owner.since} - ${nowYear} By ${config.author}` - else - .copyright!= `©${nowYear} By ${config.author}` + - const currentYear = new Date().getFullYear() + - const sinceYear = theme.footer.owner.since + .copyright + if sinceYear && sinceYear != currentYear + != `©${sinceYear} - ${currentYear} By ${config.author}` + else + != `©${currentYear} By ${config.author}` if theme.footer.copyright .framework-info span= _p('footer.framework') + ' ' @@ -14,4 +15,4 @@ span= _p('footer.theme') + ' ' a(href='https://github.com/jerryc127/hexo-theme-butterfly')= 'Butterfly' if theme.footer.custom_text - .footer_custom_text!=`${theme.footer.custom_text}` + .footer_custom_text!= theme.footer.custom_text \ No newline at end of file diff --git a/layout/includes/head/pwa.pug b/layout/includes/head/pwa.pug index e9152f2e8..816026a95 100644 --- a/layout/includes/head/pwa.pug +++ b/layout/includes/head/pwa.pug @@ -1,11 +1,13 @@ -link(rel="manifest" href=url_for(theme.pwa.manifest)) -if(theme.pwa.theme_color) - meta(name="msapplication-TileColor" content=theme.pwa.theme_color) -if(theme.pwa.apple_touch_icon) - link(rel="apple-touch-icon" sizes="180x180" href=url_for(theme.pwa.apple_touch_icon)) -if(theme.pwa.favicon_32_32) - link(rel="icon" type="image/png" sizes="32x32" href=url_for(theme.pwa.favicon_32_32)) -if(theme.pwa.favicon_16_16) - link(rel="icon" type="image/png" sizes="16x16" href=url_for(theme.pwa.favicon_16_16)) -if(theme.pwa.mask_icon) - link(rel="mask-icon" href=url_for(theme.pwa.mask_icon) color="#5bbad5") +- const { manifest, theme_color, apple_touch_icon, favicon_32_32, favicon_16_16, mask_icon } = theme.pwa + +link(rel="manifest" href=url_for(manifest)) +if theme_color + meta(name="msapplication-TileColor" content=theme_color) +if apple_touch_icon + link(rel="apple-touch-icon" sizes="180x180" href=url_for(apple_touch_icon)) +if favicon_32_32 + link(rel="icon" type="image/png" sizes="32x32" href=url_for(favicon_32_32)) +if favicon_16_16 + link(rel="icon" type="image/png" sizes="16x16" href=url_for(favicon_16_16)) +if mask_icon + link(rel="mask-icon" href=url_for(mask_icon) color="#5bbad5") diff --git a/layout/includes/header/index.pug b/layout/includes/header/index.pug index c97cceeb0..caa79987f 100644 --- a/layout/includes/header/index.pug +++ b/layout/includes/header/index.pug @@ -25,11 +25,10 @@ if !theme.disable_top_img && page.top_img !== false if top_img !== false - bg_img = getBgPath(top_img) - - headerClassName = is_home() ? 'full_page' : 'not-home-page' - - headerClassName = is_post() ? 'post-bg' : headerClassName + - headerClassName = is_home() ? 'full_page' : is_post() ? 'post-bg' : 'not-home-page' -header#page-header(class=`${headerClassName+isFixedClass}` style=bg_img) - !=partial('includes/header/nav', {}, {cache: true}) +header#page-header(class=`${headerClassName + isFixedClass}` style=bg_img) + include ./nav.pug if top_img !== false if is_post() include ./post-info.pug @@ -40,11 +39,15 @@ header#page-header(class=`${headerClassName+isFixedClass}` style=bg_img) - var loadSubJs = true #site-subtitle span#subtitle - if(theme.social) + if theme.social #site_social_icons !=partial('includes/header/social', {}, {cache: true}) #scroll-down i.fas.fa-angle-down.scroll-down-effects else #page-site-info - h1#site-title=page.title || page.tag || page.category \ No newline at end of file + h1#site-title=page.title || page.tag || page.category + else + //- improvement seo + if !is_post() + h1.title-seo=page.title || page.tag || page.category || config.title \ No newline at end of file diff --git a/layout/includes/header/menu_item.pug b/layout/includes/header/menu_item.pug index b0d707619..6302ee404 100644 --- a/layout/includes/header/menu_item.pug +++ b/layout/includes/header/menu_item.pug @@ -3,25 +3,25 @@ if theme.menu each value, label in theme.menu if typeof value !== 'object' .menus_item - - const valueArray = value.split('||') - a.site-page(href=url_for(trim(valueArray[0]))) - if valueArray[1] - i.fa-fw(class=trim(valueArray[1])) - span=' '+label + - const [link, icon] = value.split('||').map(part => trim(part)) + a.site-page(href=url_for(link)) + if icon + i.fa-fw(class=icon) + span= ' ' + label else .menus_item - - const labelArray = label.split('||') - - const hideClass = labelArray[2] && trim(labelArray[2]) === 'hide' ? 'hide' : '' - span.site-page.group(class=`${hideClass}`) - if labelArray[1] - i.fa-fw(class=trim(labelArray[1])) - span=' '+ trim(labelArray[0]) + - const [groupLabel, groupIcon, groupClass] = label.split('||').map(part => trim(part)) + - const hideClass = groupClass === 'hide' ? 'hide' : '' + span.site-page.group(class=hideClass) + if groupIcon + i.fa-fw(class=groupIcon) + span= ' ' + groupLabel i.fas.fa-chevron-down ul.menus_item_child - each val,lab in value - - const valArray = val.split('||') + each val, lab in value + - const [childLink, childIcon] = val.split('||').map(part => trim(part)) li - a.site-page.child(href=url_for(trim(valArray[0]))) - if valArray[1] - i.fa-fw(class=trim(valArray[1])) - span=' '+ lab \ No newline at end of file + a.site-page.child(href=url_for(childLink)) + if childIcon + i.fa-fw(class=childIcon) + span= ' ' + lab \ No newline at end of file diff --git a/layout/includes/header/nav.pug b/layout/includes/header/nav.pug index 3ef226e55..97d5b1ecd 100644 --- a/layout/includes/header/nav.pug +++ b/layout/includes/header/nav.pug @@ -1,22 +1,22 @@ nav#nav span#blog-info - a(href=url_for('/') title=config.title) + a.nav-site-title(href=url_for('/')) if theme.nav.logo img.site-icon(src=url_for(theme.nav.logo) alt='Logo') if theme.nav.display_title span.site-name=config.title - + if is_post() + a.nav-page-title(href=url_for('/')) + span.site-name=(page.title || config.title) #menus - if (theme.search.use) + if theme.search.use #search-button span.site-page.social-icon.search i.fas.fa-search.fa-fw - span=' '+_p('search.title') + span= ' ' + _p('search.title') if theme.menu - !=partial('includes/header/menu_item', {}, {cache: true}) + != partial('includes/header/menu_item', {}, {cache: true}) #toggle-menu span.site-page - i.fas.fa-bars.fa-fw - - + i.fas.fa-bars.fa-fw \ No newline at end of file diff --git a/layout/includes/header/post-info.pug b/layout/includes/header/post-info.pug index 491dd6ebf..b75dc9654 100644 --- a/layout/includes/header/post-info.pug +++ b/layout/includes/header/post-info.pug @@ -4,41 +4,40 @@ if theme.post_edit.enable a.post-edit-link(href=theme.post_edit.url + page.source title=_p('post.edit') target="_blank") i.fas.fa-pencil-alt - + #post-meta .meta-firstline - if (theme.post_meta.post.date_type) + if theme.post_meta.post.date_type span.post-meta-date - if (theme.post_meta.post.date_type === 'both') + if theme.post_meta.post.date_type === 'both' i.far.fa-calendar-alt.fa-fw.post-meta-icon span.post-meta-label= _p('post.created') - time.post-meta-date-created(datetime=date_xml(page.date) title=_p('post.created') + ' ' + full_date(page.date))=date(page.date, config.date_format) + time.post-meta-date-created(datetime=date_xml(page.date) title=_p('post.created') + ' ' + full_date(page.date))= date(page.date, config.date_format) span.post-meta-separator | i.fas.fa-history.fa-fw.post-meta-icon span.post-meta-label= _p('post.updated') - time.post-meta-date-updated(datetime=date_xml(page.updated) title=_p('post.updated') + ' ' + full_date(page.updated))=date(page.updated, config.date_format) + time.post-meta-date-updated(datetime=date_xml(page.updated) title=_p('post.updated') + ' ' + full_date(page.updated))= date(page.updated, config.date_format) else - let data_type_update = theme.post_meta.post.date_type === 'updated' - let date_type = data_type_update ? 'updated' : 'date' - - let date_icon = data_type_update ? 'fas fa-history' :'far fa-calendar-alt' + - let date_icon = data_type_update ? 'fas fa-history' : 'far fa-calendar-alt' - let date_title = data_type_update ? _p('post.updated') : _p('post.created') i.fa-fw.post-meta-icon(class=date_icon) span.post-meta-label= date_title - time(datetime=date_xml(page[date_type]) title=date_title + ' ' + full_date(page[date_type]))=date(page[date_type], config.date_format) - if (theme.post_meta.post.categories && page.categories.data.length > 0) + time(datetime=date_xml(page[date_type]) title=date_title + ' ' + full_date(page[date_type]))= date(page[date_type], config.date_format) + if theme.post_meta.post.categories && page.categories.data.length > 0 span.post-meta-categories - if (theme.post_meta.post.date_type) + if theme.post_meta.post.date_type span.post-meta-separator | - each item, index in page.categories.data i.fas.fa-inbox.fa-fw.post-meta-icon a(href=url_for(item.path)).post-meta-categories #[=item.name] - if (index < page.categories.data.length - 1) + if index < page.categories.data.length - 1 i.fas.fa-angle-right.post-meta-separator .meta-secondline - let postWordcount = theme.wordcount.enable && (theme.wordcount.post_wordcount || theme.wordcount.min2read) - if (postWordcount) + if postWordcount span.post-meta-separator | span.post-meta-wordcount if theme.wordcount.post_wordcount @@ -51,42 +50,57 @@ i.far.fa-clock.fa-fw.post-meta-icon span.post-meta-label= _p('post.min2read') + ':' span= min2read(page.content, {cn: 350, en: 160}) + _p('post.min2read_unit') - + //- for pv and count - mixin pvBlock(parent_id,parent_class,parent_title) + mixin pvBlock(parent_id, parent_class, parent_title) span.post-meta-separator | - span(class=parent_class id=parent_id data-flag-title=page.title) + span(class=parent_class id=parent_id data-flag-title=parent_title) i.far.fa-eye.fa-fw.post-meta-icon - span.post-meta-label=_p('post.page_pv') + ':' + span.post-meta-label= _p('post.page_pv') + ':' if block block - - const commentUse = comments.use + - const commentUse = comments.use && comments.use[0] if page.comments !== false && commentUse && !comments.lazyload - if commentUse[0] === 'Valine' && theme.valine.visitor - +pvBlock(url_for(page.path),'leancloud_visitors',page.title) - span.leancloud-visitors-count - i.fa-solid.fa-spinner.fa-spin - else if commentUse[0] === 'Waline' && theme.waline.pageview - +pvBlock('','','') - span.waline-pageview-count(data-path=url_for(page.path)) - i.fa-solid.fa-spinner.fa-spin - else if commentUse[0] === 'Twikoo' && theme.twikoo.visitor - +pvBlock('','','') - span#twikoo_visitors - i.fa-solid.fa-spinner.fa-spin - else if commentUse[0] === 'Artalk' && theme.artalk.visitor - +pvBlock('','','') - span#ArtalkPV + case commentUse + when 'Valine' + if theme.valine.visitor + +pvBlock(url_for(page.path), 'leancloud_visitors', page.title) + span.leancloud-visitors-count + i.fa-solid.fa-spinner.fa-spin + when 'Waline' + if theme.waline.pageview + +pvBlock('', '', '') + span.waline-pageview-count(data-path=url_for(page.path)) + i.fa-solid.fa-spinner.fa-spin + when 'Twikoo' + if theme.twikoo.visitor + +pvBlock('', '', '') + span#twikoo_visitors + i.fa-solid.fa-spinner.fa-spin + when 'Artalk' + if theme.artalk.visitor + +pvBlock('', '', '') + span#ArtalkPV + i.fa-solid.fa-spinner.fa-spin + default + if theme.umami_analytics.enable && theme.umami_analytics.UV_PV.page_pv + +pvBlock('', '', '') + span#umamiPV(data-path=url_for(page.path)) + i.fa-solid.fa-spinner.fa-spin + else if theme.busuanzi.page_pv + +pvBlock('', 'post-meta-pv-cv', '') + span#busuanzi_value_page_pv + i.fa-solid.fa-spinner.fa-spin + else + if theme.umami_analytics.enable && theme.umami_analytics.UV_PV.page_pv + +pvBlock('', '', '') + span#umamiPV(data-path=url_for(page.path)) i.fa-solid.fa-spinner.fa-spin else if theme.busuanzi.page_pv - +pvBlock('','post-meta-pv-cv','') + +pvBlock('', 'post-meta-pv-cv', '') span#busuanzi_value_page_pv i.fa-solid.fa-spinner.fa-spin - else if theme.busuanzi.page_pv - +pvBlock('','post-meta-pv-cv','') - span#busuanzi_value_page_pv - i.fa-solid.fa-spinner.fa-spin if comments.count && !comments.lazyload && page.comments !== false && comments.use - var whichCount = comments.use[0] @@ -98,7 +112,7 @@ span.post-meta-label= _p('post.comments') + ':' if block block - + case whichCount when 'Disqus' +countBlock diff --git a/layout/includes/header/social.pug b/layout/includes/header/social.pug index b7b586e73..81b47cc3f 100644 --- a/layout/includes/header/social.pug +++ b/layout/includes/header/social.pug @@ -1,4 +1,8 @@ each url, icon in theme.social - a.social-icon(href=url_for(trim(url.split('||')[0])) target="_blank" - title=url.split('||')[1] === undefined ? '' : trim(url.split('||')[1])) - i(class=icon style=url.split('||')[2] === undefined ? '' : `color: ${trim(url.split('||')[2]).replace(/[\'\"]/g, '')};`) \ No newline at end of file + - + const [link, title, color] = url.split('||').map(i => trim(i)) + const href = url_for(link) + const iconStyle = color ? `color: ${color.replace(/[\'\"]/g, '')};` : '' + const iconTitle = title || '' + a.social-icon(href=href target="_blank" title=iconTitle) + i(class=icon style=iconStyle) \ No newline at end of file diff --git a/layout/includes/layout.pug b/layout/includes/layout.pug index 42b04d21c..81e7e257e 100644 --- a/layout/includes/layout.pug +++ b/layout/includes/layout.pug @@ -9,8 +9,7 @@ html(lang=config.language data-theme=theme.display_mode class=htmlClassHideAside head include ./head.pug body - if theme.preloader.enable - !=partial('includes/loading/index', {}, {cache: true}) + !=partial('includes/loading/index', {}, {cache: true}) if theme.background #web_bg(style=getBgPath(theme.background)) diff --git a/layout/includes/loading/fullpage-loading.pug b/layout/includes/loading/fullpage-loading.pug index 8f5783b43..774a6b902 100644 --- a/layout/includes/loading/fullpage-loading.pug +++ b/layout/includes/loading/fullpage-loading.pug @@ -24,10 +24,10 @@ script. } preloader.initLoading() - window.addEventListener('load',() => { preloader.endLoading() }) + window.addEventListener('load', preloader.endLoading) if (!{theme.pjax && theme.pjax.enable}) { - btf.addGlobalFn('pjaxSend', () => { preloader.initLoading() }, 'preloader_init') - btf.addGlobalFn('pjaxComplete', () => { preloader.endLoading() }, 'preloader_end') + btf.addGlobalFn('pjaxSend', preloader.initLoading, 'preloader_init') + btf.addGlobalFn('pjaxComplete', preloader.endLoading, 'preloader_end') } })() \ No newline at end of file diff --git a/layout/includes/loading/index.pug b/layout/includes/loading/index.pug index 663fe501b..6a6facc2e 100644 --- a/layout/includes/loading/index.pug +++ b/layout/includes/loading/index.pug @@ -1,4 +1,5 @@ -if theme.preloader.source === 1 - include ./fullpage-loading.pug -else - include ./pace.pug \ No newline at end of file +if theme.preloader.enable + if theme.preloader.source === 1 + include ./fullpage-loading.pug + else + include ./pace.pug \ No newline at end of file diff --git a/layout/includes/mixins/article-sort.pug b/layout/includes/mixins/article-sort.pug index 3eaf0383b..acc5d9f31 100644 --- a/layout/includes/mixins/article-sort.pug +++ b/layout/includes/mixins/article-sort.pug @@ -1,14 +1,14 @@ mixin articleSort(posts) .article-sort - - var year - - posts.each(function (article) { - - let tempYear = date(article.date, 'YYYY') - - let no_cover = article.cover === false || !theme.cover.archives_enable ? 'no-article-cover' : '' - - let title = article.title || _p('no_title') + - let year + - posts.forEach(article => { + - const tempYear = date(article.date, 'YYYY') + - const noCoverClass = article.cover === false || !theme.cover.archives_enable ? 'no-article-cover' : '' + - const title = article.title || _p('no_title') if tempYear !== year - year = tempYear .article-sort-item.year= year - .article-sort-item(class=no_cover) + .article-sort-item(class=noCoverClass) if article.cover && theme.cover.archives_enable a.article-sort-item-img(href=url_for(article.path) title=title) if article.cover_type === 'img' diff --git a/layout/includes/mixins/indexPostUI.pug b/layout/includes/mixins/indexPostUI.pug index fcdad2e9d..7e80df96d 100644 --- a/layout/includes/mixins/indexPostUI.pug +++ b/layout/includes/mixins/indexPostUI.pug @@ -1,19 +1,16 @@ mixin indexPostUI() - - let indexLayout = theme.index_layout - - let masonryLayoutClass = (indexLayout === 6 || indexLayout === 7) ? 'masonry' : '' + - const indexLayout = theme.index_layout + - const masonryLayoutClass = (indexLayout === 6 || indexLayout === 7) ? 'masonry' : '' #recent-posts.recent-posts.nc(class=masonryLayoutClass) .recent-post-items - each article , index in page.posts.data + each article, index in page.posts.data .recent-post-item - - - let link = article.link || article.path - let title = article.title || _p('no_title') - let leftOrRight = indexLayout === 3 - ? index%2 == 0 ? 'left' : 'right' - : indexLayout === 2 ? 'right' : '' - let post_cover = article.cover - let no_cover = article.cover === false || !theme.cover.index_enable ? 'no-cover' : '' - - + - const link = article.link || article.path + - const title = article.title || _p('no_title') + - const leftOrRight = indexLayout === 3 ? (index % 2 === 0 ? 'left' : 'right') : (indexLayout === 2 ? 'right' : '') + - const post_cover = article.cover + - const no_cover = article.cover === false || !theme.cover.index_enable ? 'no-cover' : '' + if post_cover && theme.cover.index_enable .post_cover(class=leftOrRight) a(href=url_for(link) title=title) @@ -23,43 +20,43 @@ mixin indexPostUI() div.post-bg(style=`background: ${post_cover}`) .recent-post-info(class=no_cover) a.article-title(href=url_for(link) title=title) - if (is_home() && (article.top || article.sticky > 0)) + if is_home() && (article.top || article.sticky > 0) i.fas.fa-thumbtack.sticky = title .article-meta-wrap - if (theme.post_meta.page.date_type) + if theme.post_meta.page.date_type span.post-meta-date - if (theme.post_meta.page.date_type === 'both') + if theme.post_meta.page.date_type === 'both' i.far.fa-calendar-alt span.article-meta-label=_p('post.created') - time.post-meta-date-created(datetime=date_xml(article.date) title=_p('post.created') + ' ' + full_date(article.date))=date(article.date, config.date_format) + time.post-meta-date-created(datetime=date_xml(article.date) title=_p('post.created') + ' ' + full_date(article.date))= date(article.date, config.date_format) span.article-meta-separator | i.fas.fa-history span.article-meta-label=_p('post.updated') - time.post-meta-date-updated(datetime=date_xml(article.updated) title=_p('post.updated') + ' ' + full_date(article.updated))=date(article.updated, config.date_format) + time.post-meta-date-updated(datetime=date_xml(article.updated) title=_p('post.updated') + ' ' + full_date(article.updated))= date(article.updated, config.date_format) else - - let data_type_updated = theme.post_meta.page.date_type === 'updated' - - let date_type = data_type_updated ? 'updated' : 'date' - - let date_icon = data_type_updated ? 'fas fa-history' :'far fa-calendar-alt' - - let date_title = data_type_updated ? _p('post.updated') : _p('post.created') + - const data_type_updated = theme.post_meta.page.date_type === 'updated' + - const date_type = data_type_updated ? 'updated' : 'date' + - const date_icon = data_type_updated ? 'fas fa-history' : 'far fa-calendar-alt' + - const date_title = data_type_updated ? _p('post.updated') : _p('post.created') i(class=date_icon) - span.article-meta-label=date_title - time(datetime=date_xml(article[date_type]) title=date_title + ' ' + full_date(article[date_type]))=date(article[date_type], config.date_format) - if (theme.post_meta.page.categories && article.categories.data.length > 0) + span.article-meta-label= date_title + time(datetime=date_xml(article[date_type]) title=date_title + ' ' + full_date(article[date_type]))= date(article[date_type], config.date_format) + if theme.post_meta.page.categories && article.categories.data.length > 0 span.article-meta span.article-meta-separator | each item, index in article.categories.data i.fas.fa-inbox a(href=url_for(item.path)).article-meta__categories #[=item.name] - if (index < article.categories.data.length - 1) + if index < article.categories.data.length - 1 i.fas.fa-angle-right.article-meta-link - if (theme.post_meta.page.tags && article.tags.length > 0) + if theme.post_meta.page.tags && article.tags.length > 0 span.article-meta.tags span.article-meta-separator | each item, index in article.tags.data i.fas.fa-tag a(href=url_for(item.path)).article-meta__tags #[=item.name] - if (index < article.tags.data.length - 1) + if index < article.tags.data.length - 1 span.article-meta-link #[='•'] mixin countBlockInIndex @@ -119,7 +116,7 @@ mixin indexPostUI() .content!= truncate(article.content, theme.index_post_content.length) if theme.ad && theme.ad.index - if (index + 1) % 3 == 0 - .recent-post-item.ads-wrap!=theme.ad.index + if (index + 1) % 3 === 0 + .recent-post-item.ads-wrap!= theme.ad.index include ../pagination.pug \ No newline at end of file diff --git a/layout/includes/post/post-copyright.pug b/layout/includes/post/post-copyright.pug index e0b09df5e..c76f4b424 100644 --- a/layout/includes/post/post-copyright.pug +++ b/layout/includes/post/post-copyright.pug @@ -1,15 +1,15 @@ if theme.post_copyright.enable && page.copyright !== false - - let author = page.copyright_author || config.author - - let authorHref = page.copyright_author_href || theme.post_copyright.author_href || config.url - - let url = page.copyright_url || page.permalink - - let info = page.copyright_info || _p('post.copyright.copyright_content', theme.post_copyright.license_url, theme.post_copyright.license, config.url, config.title) + - const author = page.copyright_author || config.author + - const authorHref = page.copyright_author_href || theme.post_copyright.author_href || config.url + - const url = page.copyright_url || page.permalink + - const info = page.copyright_info || _p('post.copyright.copyright_content', theme.post_copyright.license_url, theme.post_copyright.license, config.url, config.title) .post-copyright .post-copyright__author span.post-copyright-meta i.fas.fa-circle-user.fa-fw = _p('post.copyright.author') + ": " span.post-copyright-info - a(href=authorHref)=author + a(href=authorHref)= author .post-copyright__type span.post-copyright-meta i.fas.fa-square-arrow-up-right.fa-fw @@ -20,4 +20,4 @@ if theme.post_copyright.enable && page.copyright !== false span.post-copyright-meta i.fas.fa-circle-exclamation.fa-fw = _p('post.copyright.copyright_notice') + ": " - span.post-copyright-info!= info + span.post-copyright-info!= info \ No newline at end of file diff --git a/layout/includes/post/reward.pug b/layout/includes/post/reward.pug index fb559465a..fe62f14ef 100644 --- a/layout/includes/post/reward.pug +++ b/layout/includes/post/reward.pug @@ -5,9 +5,8 @@ .reward-main ul.reward-all each item in theme.reward.QR_code - - var clickTo = item.link ? item.link : item.img + - const clickTo = item.link || item.img li.reward-item a(href=url_for(clickTo) target='_blank') img.post-qr-code-img(src=url_for(item.img) alt=item.text) - .post-qr-code-desc=item.text - + .post-qr-code-desc=item.text \ No newline at end of file diff --git a/layout/includes/sidebar.pug b/layout/includes/sidebar.pug index c4aeffff7..7eabbf1c3 100644 --- a/layout/includes/sidebar.pug +++ b/layout/includes/sidebar.pug @@ -6,7 +6,7 @@ if theme.menu img(src=url_for(theme.avatar.img) onerror=`onerror=null;src='${theme.error_img.flink}'` alt="avatar") .site-data.is-center a(href=url_for(config.archive_dir) + '/') - .headline= _p('aside.articles') + .headline= _p('aside.articles') .length-num= site.posts.length a(href=url_for(config.tag_dir) + '/' ) .headline= _p('aside.tags') diff --git a/layout/includes/third-party/abcjs/index.pug b/layout/includes/third-party/abcjs/index.pug index 1112626e6..12d14786c 100644 --- a/layout/includes/third-party/abcjs/index.pug +++ b/layout/includes/third-party/abcjs/index.pug @@ -1,4 +1,4 @@ -if theme.abcjs && theme.abcjs.enable +if theme.abcjs.enable if theme.abcjs.per_page if is_post() || is_page() include ./abcjs.pug diff --git a/layout/includes/third-party/card-post-count/fb.pug b/layout/includes/third-party/card-post-count/fb.pug index fb504d349..e6daba173 100644 --- a/layout/includes/third-party/card-post-count/fb.pug +++ b/layout/includes/third-party/card-post-count/fb.pug @@ -1,5 +1,5 @@ -- const fbSDKVer = 'v16.0' -- const fbSDK = theme.chat.use === 'messenger' ? `https://connect.facebook.net/${theme.facebook_comments.lang}/sdk/xfbml.customerchat.js#xfbml=1&version=${fbSDKVer}` : `https://connect.facebook.net/${theme.facebook_comments.lang}/sdk.js#xfbml=1&version=${fbSDKVer}` +- const fbSDKVer = 'v20.0' +- const fbSDK = `https://connect.facebook.net/${theme.facebook_comments.lang}/sdk.js#xfbml=1&version=${fbSDKVer}` script. (()=>{ diff --git a/layout/includes/third-party/chat/chatra.pug b/layout/includes/third-party/chat/chatra.pug index 928ac197a..41f042321 100644 --- a/layout/includes/third-party/chat/chatra.pug +++ b/layout/includes/third-party/chat/chatra.pug @@ -15,22 +15,15 @@ script. Chatra('show') } - window.ChatraSetup = { - startHidden: true - } + window.ChatraSetup = { startHidden: true } window.chatBtnFn = () => { - const isShow = document.getElementById('chatra').classList.contains('chatra--expanded') - isShow ? close() : open() + document.getElementById('chatra').classList.contains('chatra--expanded') ? close() : open() } } else if (isChatHideShow) { window.chatBtn = { - hide: () => { - Chatra('hide') - }, - show: () => { - Chatra('show') - } + hide: () => Chatra('hide'), + show: () => Chatra('show') } } @@ -38,13 +31,12 @@ script. w.ChatraID = '#{theme.chatra.id}' var s = d.createElement('script') w[c] = w[c] || function() { - (w[c].q = w[c].q || []).push(arguments) + (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') - })() diff --git a/layout/includes/third-party/chat/crisp.pug b/layout/includes/third-party/chat/crisp.pug index 24c8c1ca6..e25a17fee 100644 --- a/layout/includes/third-party/chat/crisp.pug +++ b/layout/includes/third-party/chat/crisp.pug @@ -20,26 +20,18 @@ script. $crisp.push(["do", "chat:open"]) } - const close = () => { - $crisp.push(["do", "chat:hide"]) - } + const close = () => $crisp.push(["do", "chat:hide"]) close() - $crisp.push(["on", "chat:closed", function() { - close() - }]) - window.chatBtnFn = () => { - $crisp.is("chat:visible") ? close() : open() - } + $crisp.push(["on", "chat:closed", 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"]) - } + hide: () => $crisp.push(["do", "chat:hide"]), + show: () => $crisp.push(["do", "chat:show"]) } } })() \ No newline at end of file diff --git a/layout/includes/third-party/chat/index.pug b/layout/includes/third-party/chat/index.pug index 6fa1131de..c53484928 100644 --- a/layout/includes/third-party/chat/index.pug +++ b/layout/includes/third-party/chat/index.pug @@ -6,6 +6,4 @@ case theme.chat.use when 'daovoice' include ./daovoice.pug when 'crisp' - include ./crisp.pug - when 'messenger' - include ./messenger.pug \ No newline at end of file + include ./crisp.pug \ No newline at end of file diff --git a/layout/includes/third-party/chat/messenger.pug b/layout/includes/third-party/chat/messenger.pug deleted file mode 100644 index 41eef4ad1..000000000 --- a/layout/includes/third-party/chat/messenger.pug +++ /dev/null @@ -1,44 +0,0 @@ -- let { pageID, lang } = theme.messenger -- lang = theme.comments.use && theme.comments.use.includes('Facebook Comments') ? theme.facebook_comments.lang : lang - -#fb-customer-chat.fb-customerchat(page_id=pageID attribution='biz_inbox') - -script. - (() => { - document.getElementById('fb-root') ? '' : document.body.insertAdjacentHTML('afterend', '
') - - window.fbAsyncInit = function() { - FB.init({ - xfbml: true, - version: 'v16.0' - }); - }; - - (function(d, s, id) { - var js, fjs = d.getElementsByTagName(s)[0]; - if (d.getElementById(id)) return; - js = d.createElement(s); js.id = id; - js.src = 'https://connect.facebook.net/!{lang}/sdk/xfbml.customerchat.js'; - fjs.parentNode.insertBefore(js, fjs); - }(document, 'script', 'facebook-jssdk')); - - const isChatBtn = !{theme.chat.rightside_button} - const isChatHideShow = !{theme.chat.button_hide_show} - - if (isChatBtn) { - window.chatBtnFn = () => { - const isShow = document.querySelector('.fb_customer_chat_bounce_in_v2') - isShow ? FB.CustomerChat.hide() : FB.CustomerChat.show() - } - } else if (isChatHideShow) { - window.chatBtn = { - hide: () => { - FB.CustomerChat.hide() - }, - show: () => { - FB.CustomerChat.show(false) - } - } - } - })() - diff --git a/layout/includes/third-party/chat/tidio.pug b/layout/includes/third-party/chat/tidio.pug index a4194c46f..78361af77 100644 --- a/layout/includes/third-party/chat/tidio.pug +++ b/layout/includes/third-party/chat/tidio.pug @@ -33,12 +33,8 @@ script. } } else if (isChatHideShow) { window.chatBtn = { - hide: () => { - window.tidioChatApi && window.tidioChatApi.hide() - }, - show: () => { - window.tidioChatApi && window.tidioChatApi.show() - } + hide: () => window.tidioChatApi && window.tidioChatApi.hide(), + show: () => window.tidioChatApi && window.tidioChatApi.show() } } })() diff --git a/layout/includes/third-party/comments/artalk.pug b/layout/includes/third-party/comments/artalk.pug index 646a42467..befc32e3b 100644 --- a/layout/includes/third-party/comments/artalk.pug +++ b/layout/includes/third-party/comments/artalk.pug @@ -48,7 +48,7 @@ script. if ('!{use[0]}' === 'Artalk' || !!{lazyload}) { if (!{lazyload}) btf.loadComment(document.getElementById('artalk-wrap'), loadArtalk) - else loadArtalk() + else setTimeout(loadArtalk, 100) } else { window.loadOtherComment = loadArtalk } diff --git a/layout/includes/third-party/comments/facebook_comments.pug b/layout/includes/third-party/comments/facebook_comments.pug index b6617ec03..3b47452d4 100644 --- a/layout/includes/third-party/comments/facebook_comments.pug +++ b/layout/includes/third-party/comments/facebook_comments.pug @@ -1,5 +1,5 @@ -- const fbSDKVer = 'v16.0' -- const fbSDK = theme.chat.use === 'messenger' ? `https://connect.facebook.net/${theme.facebook_comments.lang}/sdk/xfbml.customerchat.js#xfbml=1&version=${fbSDKVer}` : `https://connect.facebook.net/${theme.facebook_comments.lang}/sdk.js#xfbml=1&version=${fbSDKVer}` +- const fbSDKVer = 'v20.0' +- const fbSDK = `https://connect.facebook.net/${theme.facebook_comments.lang}/sdk.js#xfbml=1&version=${fbSDKVer}` script. (()=>{ diff --git a/layout/includes/third-party/math/index.pug b/layout/includes/third-party/math/index.pug index cf4741dae..068a78fdf 100644 --- a/layout/includes/third-party/math/index.pug +++ b/layout/includes/third-party/math/index.pug @@ -1,19 +1,11 @@ case theme.math.use when 'mathjax' - if theme.math.per_page - if is_post() || is_page() - include ./mathjax.pug - else - if page.mathjax - include ./mathjax.pug + if (theme.math.per_page && (is_post() || is_page())) || page.mathjax + include ./mathjax.pug when 'katex' - if theme.math.per_page - if is_post() || is_page() - include ./katex.pug - else - if page.katex - include ./katex.pug + if (theme.math.per_page && (is_post() || is_page())) || page.katex + include ./katex.pug if theme.mermaid.enable include ./mermaid.pug \ No newline at end of file diff --git a/layout/includes/third-party/math/katex.pug b/layout/includes/third-party/math/katex.pug index c38a4b494..0e4195d15 100644 --- a/layout/includes/third-party/math/katex.pug +++ b/layout/includes/third-party/math/katex.pug @@ -1,15 +1,15 @@ script. (async () => { const showKatex = () => { - const mathElements = document.querySelectorAll('#article-container .katex') - mathElements.length && mathElements.forEach((el) => { - el.classList.add('katex-show') - }) + document.querySelectorAll('#article-container .katex').forEach(el => el.classList.add('katex-show')) } + if (!window.katex_js_css) { window.katex_js_css = true await btf.getCSS('!{url_for(theme.asset.katex)}') - if (!{theme.math.katex.copy_tex}) await btf.getScript('!{url_for(theme.asset.katex_copytex)}') + if (!{theme.math.katex.copy_tex}) { + await btf.getScript('!{url_for(theme.asset.katex_copytex)}') + } } showKatex() diff --git a/layout/includes/third-party/math/mermaid.pug b/layout/includes/third-party/math/mermaid.pug index 21898c312..a668659d9 100644 --- a/layout/includes/third-party/math/mermaid.pug +++ b/layout/includes/third-party/math/mermaid.pug @@ -1,13 +1,13 @@ script. (() => { - const runMermaid = (ele) => { + const runMermaid = ele => { window.loadMermaid = true const theme = document.documentElement.getAttribute('data-theme') === 'dark' ? '!{theme.mermaid.theme.dark}' : '!{theme.mermaid.theme.light}' - Array.from(ele).forEach((item, index) => { + ele.forEach((item, index) => { const mermaidSrc = item.firstElementChild - const mermaidThemeConfig = '%%{init:{ \'theme\':\'' + theme + '\'}}%%\n' - const mermaidID = 'mermaid-' + index + const mermaidThemeConfig = `%%{init:{ 'theme':'${theme}'}}%%\n` + const mermaidID = `mermaid-${index}` const mermaidDefinition = mermaidThemeConfig + mermaidSrc.textContent const renderFn = mermaid.render(mermaidID, mermaidDefinition) @@ -16,14 +16,14 @@ script. } // mermaid v9 and v10 compatibility - typeof renderFn === 'string' ? renderMermaid(renderFn) : renderFn.then(({svg}) => renderMermaid(svg)) + typeof renderFn === 'string' ? renderMermaid(renderFn) : renderFn.then(({ svg }) => renderMermaid(svg)) }) } const codeToMermaid = () => { const codeMermaidEle = document.querySelectorAll('pre > code.mermaid') if (codeMermaidEle.length === 0) return - + codeMermaidEle.forEach(ele => { const preEle = document.createElement('pre') preEle.className = 'mermaid-src' @@ -45,7 +45,7 @@ script. btf.addGlobalFn('themeChange', runMermaidFn, 'mermaid') window.loadMermaid ? runMermaidFn() : btf.getScript('!{url_for(theme.asset.mermaid)}').then(runMermaidFn) } - + btf.addGlobalFn('encrypt', loadMermaid, 'mermaid') window.pjax ? loadMermaid() : document.addEventListener('DOMContentLoaded', loadMermaid) })() \ No newline at end of file diff --git a/layout/includes/third-party/newest-comments/artalk.pug b/layout/includes/third-party/newest-comments/artalk.pug index bec42d21c..af669eed1 100644 --- a/layout/includes/third-party/newest-comments/artalk.pug +++ b/layout/includes/third-party/newest-comments/artalk.pug @@ -2,106 +2,63 @@ - const avatarCdn = (option !== null && option.gravatar && option.gravatar.mirror) || '' - const avatarDefault = (option !== null && option.gravatar && (option.gravatar.params || option.gravatar.default)) || '' +!= partial("includes/third-party/newest-comments/common.pug", {}, { cache: true }) + script. window.addEventListener('load', () => { - const changeContent = (content) => { - if (content === '') return content - - content = content.replace(/]+>/ig, '[!{_p("aside.card_newest_comments.image")}]') // replace image link - content = content.replace(/]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[!{_p("aside.card_newest_comments.link")}]') // replace url - content = content.replace(/
.*?<\/pre>/gi, '[!{_p("aside.card_newest_comments.code")}]') // replace code
-      content = content.replace(/<[^>]+>/g,"") // remove html tag
-
-      if (content.length > 150) {
-        content = content.substring(0,150) + '...'
-      }
-      return content
-    }
+    const keyName = 'artalk-newest-comments'
+    const { changeContent, generateHtml, run } = window.newestComments
 
-    const generateHtml = array => {
-      let result = ''
+    const getAvatarValue = async () => {
+      const predefinedAvatarCdn = '!{avatarCdn}'
+      const predefinedAvatarDefault = '!{avatarDefault}'
 
-      if (array.length) {
-        for (let i = 0; i < array.length; i++) {
-          result += '
' + const avatarDefaultFormat = e => e.startsWith('d=') ? e : `d=${e}` - if (!{theme.aside.card_newest_comments.avatar}) { - const name = '!{theme.lazyload.enable ? "data-lazy-src" : "src"}' - result += `${array[i].nick}` - } - - result += `
- ${array[i].content} -
${array[i].nick} /
-
` - } - } else { - result += '!{_p("aside.card_newest_comments.zero")}' + if (predefinedAvatarCdn && predefinedAvatarDefault) { + return { avatarCdn: predefinedAvatarCdn, avatarDefault: avatarDefaultFormat(predefinedAvatarDefault) } } - - let $dom = document.querySelector('#card-newest-comments .aside-list') - $dom && ($dom && ($dom.innerHTML= result)) - window.lazyLoadInstance && window.lazyLoadInstance.update() - window.pjax && window.pjax.refresh($dom) - } - - const getSetting = async () => { + try { - const res = await fetch('!{server}/api/v2/conf', { method: 'GET' }) - return await res.json() + const res = await fetch('!{server}/api/v2/conf') + const result = await res.json() + const { mirror, params, default: defaults } = result.frontend_conf.gravatar + const avatarCdn = predefinedAvatarCdn || mirror + let avatarDefault = avatarDefaultFormat(predefinedAvatarDefault || params || defaults) + return { avatarCdn, avatarDefault} } catch (e) { - console.log(e) + console.error(e) + return { avatarCdn: predefinedAvatarCdn, avatarDefault: avatarDefaultFormat(predefinedAvatarDefault) } } } - const headerList = { - method: 'GET', - } - const searchParams = new URLSearchParams({ 'site_name': '!{site}', 'limit': '!{theme.aside.card_newest_comments.limit}', }) - const getComment = async () => { + const getComment = async (ele) => { try { - const res = await fetch(`!{server}/api/v2/stats/latest_comments?${searchParams}`, headerList) + const res = await fetch(`!{server}/api/v2/stats/latest_comments?${searchParams}`) const result = await res.json() - const avatarStr = await getSetting() - const { mirror, params, default:defaults } = avatarStr.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) { + const { avatarCdn, avatarDefault } = await getAvatarValue() + const artalk = result.data.map(e => { + const avatar = avatarCdn && e.email_encrypted ? `${avatarCdn}${e.email_encrypted}?${avatarDefault}` : '' return { - 'avatar': `${avatarCdn}${e.email_encrypted}?${avatarDefault}`, + 'avatar': avatar, 'content': changeContent(e.content_marked), 'nick': e.nick, 'url': e.page_url, 'date': e.date, } }) - btf.saveToLocal.set('artalk-newest-comments', JSON.stringify(artalk), !{theme.aside.card_newest_comments.storage}/(60*24)) - generateHtml(artalk) + btf.saveToLocal.set(keyName, JSON.stringify(artalk), !{theme.aside.card_newest_comments.storage}/(60*24)) + generateHtml(artalk, ele) } catch (e) { console.log(e) - const $dom = document.querySelector('#card-newest-comments .aside-list') - $dom.textContent= "!{_p('aside.card_newest_comments.error')}" + ele.textContent= "!{_p('aside.card_newest_comments.error')}" } } - const newestCommentInit = () => { - if (document.querySelector('#card-newest-comments .aside-list')) { - const data = btf.saveToLocal.get('artalk-newest-comments') - if (data) { - generateHtml(JSON.parse(data)) - } else { - getComment() - } - } - } - - newestCommentInit() - btf.addGlobalFn('pjaxComplete', newestCommentInit, 'artalk_newestComment') - - }) + run(keyName, getComment) + }) \ No newline at end of file diff --git a/layout/includes/third-party/newest-comments/common.pug b/layout/includes/third-party/newest-comments/common.pug new file mode 100644 index 000000000..093bd27bd --- /dev/null +++ b/layout/includes/third-party/newest-comments/common.pug @@ -0,0 +1,60 @@ +script. + window.newestComments = { + changeContent: content => { + if (content === '') return content + + content = content.replace(/]+>/ig, '[!{_p("aside.card_newest_comments.image")}]') // replace image link + content = content.replace(/]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[!{_p("aside.card_newest_comments.link")}]') // replace url + content = content.replace(/
.*?<\/pre>/gi, '[!{_p("aside.card_newest_comments.code")}]') // replace code
+      content = content.replace(/.*?<\/code>/gi, '[!{_p("aside.card_newest_comments.code")}]') // replace code      
+      content = content.replace(/<[^>]+>/g, "") // remove html tag
+
+      if (content.length > 150) {
+        content = content.substring(0, 150) + '...'
+      }
+      return content
+    },
+
+    generateHtml: (array, ele) => {
+      let result = ''
+
+      if (array.length) {
+        for (let i = 0; i < array.length; i++) {
+          result += '
' + + if (!{theme.aside.card_newest_comments.avatar} && array[i].avatar) { + const imgAttr = '!{theme.lazyload.enable ? "data-lazy-src" : "src"}' + result += `${array[i].nick}` + } + + result += `
+ ${array[i].content} +
${array[i].nick} /
+
` + } + } else { + result += '!{_p("aside.card_newest_comments.zero")}' + } + + ele.innerHTML = result + window.lazyLoadInstance && window.lazyLoadInstance.update() + window.pjax && window.pjax.refresh(ele) + }, + + newestCommentInit: (name, getComment) => { + const $dom = document.querySelector('#card-newest-comments .aside-list') + if ($dom) { + const data = btf.saveToLocal.get(name) + if (data) { + newestComments.generateHtml(JSON.parse(data), $dom) + } else { + getComment($dom) + } + } + }, + + run: (name, getComment) => { + newestComments.newestCommentInit(name, getComment) + btf.addGlobalFn('pjaxComplete', () => newestComments.newestCommentInit(name, getComment), name) + } + } \ No newline at end of file diff --git a/layout/includes/third-party/newest-comments/disqus-comment.pug b/layout/includes/third-party/newest-comments/disqus-comment.pug index e62c5f7dd..96eaa023b 100644 --- a/layout/includes/third-party/newest-comments/disqus-comment.pug +++ b/layout/includes/third-party/newest-comments/disqus-comment.pug @@ -1,20 +1,11 @@ +!= partial("includes/third-party/newest-comments/common.pug", {}, { cache: true }) + script. window.addEventListener('load', () => { - const changeContent = (content) => { - if (content === '') return content - - content = content.replace(/]+>/ig, '[!{_p("aside.card_newest_comments.image")}]') // replace image link - content = content.replace(/]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[!{_p("aside.card_newest_comments.link")}]') // replace url - content = content.replace(/.*?<\/code>/gi, '[!{_p("aside.card_newest_comments.code")}]') // replace code - content = content.replace(/<[^>]+>/g,"") // remove html tag - - if (content.length > 150) { - content = content.substring(0,150) + '...' - } - return content - } + const keyName = 'disqus-newest-comments' + const { changeContent, generateHtml, run } = window.newestComments - const getComment = () => { + const getComment = ele => { fetch('https://disqus.com/api/3.0/forums/listPosts.json?forum=!{forum}&related=thread&limit=!{theme.aside.card_newest_comments.limit}&api_key=!{apiKey}') .then(response => response.json()) .then(data => { @@ -28,54 +19,15 @@ script. } }) - btf.saveToLocal.set('disqus-newest-comments', JSON.stringify(disqusArray), !{theme.aside.card_newest_comments.storage}/(60*24)) - generateHtml(disqusArray) + btf.saveToLocal.set(keyName, JSON.stringify(disqusArray), !{theme.aside.card_newest_comments.storage}/(60*24)) + generateHtml(disqusArray, ele) }).catch(e => { - const $dom = document.querySelector('#card-newest-comments .aside-list') - $dom.textContent= "!{_p('aside.card_newest_comments.error')}" + console.error(e) + ele.textContent= "!{_p('aside.card_newest_comments.error')}" }) } - const generateHtml = array => { - let result = '' - - if (array.length) { - for (let i = 0; i < array.length; i++) { - result += '
' - - if (!{theme.aside.card_newest_comments.avatar}) { - const name = '!{theme.lazyload.enable ? "data-lazy-src" : "src"}' - result += `${array[i].nick}` - } - - result += `
- ${array[i].content} -
${array[i].nick}
-
` - } - } else { - result += '!{_p("aside.card_newest_comments.zero")}' - } - - let $dom = document.querySelector('#card-newest-comments .aside-list') - $dom && ($dom.innerHTML= result) - window.lazyLoadInstance && window.lazyLoadInstance.update() - window.pjax && window.pjax.refresh($dom) - } - - const newestCommentInit = () => { - if (document.querySelector('#card-newest-comments .aside-list')) { - const data = btf.saveToLocal.get('disqus-newest-comments') - if (data) { - generateHtml(JSON.parse(data)) - } else { - getComment() - } - } - } - - newestCommentInit() - btf.addGlobalFn('pjaxComplete', newestCommentInit, 'disqus_newestComment') + run(keyName, getComment) }) diff --git a/layout/includes/third-party/newest-comments/github-issues.pug b/layout/includes/third-party/newest-comments/github-issues.pug index 46d95470e..d36f1b2de 100644 --- a/layout/includes/third-party/newest-comments/github-issues.pug +++ b/layout/includes/third-party/newest-comments/github-issues.pug @@ -1,20 +1,11 @@ +!= partial("includes/third-party/newest-comments/common.pug", {}, { cache: true }) + script. window.addEventListener('load', () => { - const changeContent = (content) => { - if (content === '') return content - - content = content.replace(/]+>/ig, '[!{_p("aside.card_newest_comments.image")}]') // replace image link - content = content.replace(/]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[!{_p("aside.card_newest_comments.link")}]') // replace url - content = content.replace(/
.*?<\/pre>/gi, '[!{_p("aside.card_newest_comments.code")}]') // replace code
-      content = content.replace(/<[^>]+>/g,"") // remove html tag
-
-      if (content.length > 150) {
-        content = content.substring(0,150) + '...'
-      }
-      return content
-    }
+    const keyName = 'github-newest-comments'
+    const { changeContent, generateHtml, run } = window.newestComments
 
-    const findTrueUrl = (array) => {
+    const findTrueUrl = (array, ele) => {
       Promise.all(array.map(item =>
         fetch(item.url).then(resp => resp.json()).then(data => {
           let urlArray = data.body ? data.body.match(/(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/ig) : []
@@ -35,12 +26,12 @@ script.
             }
           })
 
-          btf.saveToLocal.set('github-newest-comments', JSON.stringify(array), !{theme.aside.card_newest_comments.storage}/(60*24))
-          generateHtml(array)
+          btf.saveToLocal.set(keyName, JSON.stringify(array), !{theme.aside.card_newest_comments.storage}/(60*24))
+          generateHtml(array, ele)
       });
     }
 
-    const getComment = () => {
+    const getComment = ele => {
       fetch('https://api.github.com/repos/!{userRepo}/issues/comments?sort=updated&direction=desc&per_page=!{theme.aside.card_newest_comments.limit}&page=1',{
         "headers": {
           Accept: 'application/vnd.github.v3.html+json'
@@ -54,57 +45,16 @@ script.
               'content': changeContent(item.body_html || item.body),
               'nick': item.user.login,
               'url': item.issue_url,
-              'date': item.updated_at,
-              'githubUrl': item.html_url
+              'date': item.updated_at
             }
           })
-          findTrueUrl(githubArray)
+          findTrueUrl(githubArray, ele)
         }).catch(e => {
-          const $dom = document.querySelector('#card-newest-comments .aside-list')
-          $dom.textContent= "!{_p('aside.card_newest_comments.error')}"
+          console.error(e)
+          ele.textContent= "!{_p('aside.card_newest_comments.error')}"
         })
     }
-
-    const generateHtml = array => {
-      let result = ''
-
-      if (array.length) {
-        for (let i = 0; i < array.length; i++) {
-          result += '
' - - if (!{theme.aside.card_newest_comments.avatar}) { - const name = '!{theme.lazyload.enable ? "data-lazy-src" : "src"}' - result += `${array[i].nick}` - } - - result += `
- ${array[i].content} -
${array[i].nick} /
-
` - } - } else { - result += '!{_p("aside.card_newest_comments.zero")}' - } - - let $dom = document.querySelector('#card-newest-comments .aside-list') - $dom && ($dom.innerHTML= result) - window.lazyLoadInstance && window.lazyLoadInstance.update() - window.pjax && window.pjax.refresh($dom) - } - - const newestCommentInit = () => { - if (document.querySelector('#card-newest-comments .aside-list')) { - const data = btf.saveToLocal.get('github-newest-comments') - if (data) { - generateHtml(JSON.parse(data)) - } else { - getComment() - } - } - } - - newestCommentInit() - btf.addGlobalFn('pjaxComplete', newestCommentInit, 'github_newestComment') + run(keyName, getComment) }) diff --git a/layout/includes/third-party/newest-comments/remark42.pug b/layout/includes/third-party/newest-comments/remark42.pug index 680f82644..c83fd0caa 100644 --- a/layout/includes/third-party/newest-comments/remark42.pug +++ b/layout/includes/third-party/newest-comments/remark42.pug @@ -2,52 +2,14 @@ script. window.addEventListener('load', () => { - const changeContent = (content) => { - if (content === '') return content + const keyName = 'remark42-newest-comments' + const { changeContent, generateHtml, run } = window.newestComments - content = content.replace(/]+>/ig, '[!{_p("aside.card_newest_comments.image")}]') // replace image link - content = content.replace(/]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[!{_p("aside.card_newest_comments.link")}]') // replace url - content = content.replace(/
.*?<\/pre>/gi, '[!{_p("aside.card_newest_comments.code")}]') // replace code
-      content = content.replace(/<[^>]+>/g,"") // remove html tag
-
-      if (content.length > 150) {
-        content = content.substring(0,150) + '...'
-      }
-      return content
-    }
-
-    const generateHtml = array => {
-      let result = ''
-
-      if (array.length) {
-        for (let i = 0; i < array.length; i++) {
-          result += '
' - - if (!{theme.aside.card_newest_comments.avatar}) { - const name = '!{theme.lazyload.enable ? "data-lazy-src" : "src"}' - result += `${array[i].nick}` - } - - result += `
- ${array[i].content} -
${array[i].nick} /
-
` - } - } else { - result += '!{_p("aside.card_newest_comments.zero")}' - } - - let $dom = document.querySelector('#card-newest-comments .aside-list') - $dom && ($dom.innerHTML= result) - window.lazyLoadInstance && window.lazyLoadInstance.update() - window.pjax && window.pjax.refresh($dom) - } - - const getComment = () => { + const getComment = ele => { fetch('!{host}/api/v1/last/!{theme.aside.card_newest_comments.limit}?site=!{siteId}') .then(response => response.json()) .then(data => { - const remark42 = data.map(function (e) { + const remark42 = data.map(e => { return { 'avatar': e.user.picture, 'content': changeContent(e.text), @@ -56,25 +18,13 @@ script. 'date': e.time, } }) - btf.saveToLocal.set('remark42-newest-comments', JSON.stringify(remark42), !{theme.aside.card_newest_comments.storage}/(60*24)) - generateHtml(remark42) + btf.saveToLocal.set(keyName, JSON.stringify(remark42), !{theme.aside.card_newest_comments.storage}/(60*24)) + generateHtml(remark42, ele) }).catch(e => { - const $dom = document.querySelector('#card-newest-comments .aside-list') - $dom.textContent= "!{_p('aside.card_newest_comments.error')}" + console.error(e) + ele.textContent= "!{_p('aside.card_newest_comments.error')}" }) } - const newestCommentInit = () => { - if (document.querySelector('#card-newest-comments .aside-list')) { - const data = btf.saveToLocal.get('remark42-newest-comments') - if (data) { - generateHtml(JSON.parse(data)) - } else { - getComment() - } - } - } - - newestCommentInit() - btf.addGlobalFn('pjaxComplete', newestCommentInit, 'remark42_newestComment') + run(keyName, getComment) }) diff --git a/layout/includes/third-party/newest-comments/twikoo-comment.pug b/layout/includes/third-party/newest-comments/twikoo-comment.pug index 35caf59b5..941f42b04 100644 --- a/layout/includes/third-party/newest-comments/twikoo-comment.pug +++ b/layout/includes/third-party/newest-comments/twikoo-comment.pug @@ -1,27 +1,18 @@ +!= partial("includes/third-party/newest-comments/common.pug", {}, { cache: true }) + script. window.addEventListener('load', () => { - const changeContent = (content) => { - if (content === '') return content - - content = content.replace(/]+>/ig, '[!{_p("aside.card_newest_comments.image")}]') // replace image link - content = content.replace(/]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[!{_p("aside.card_newest_comments.link")}]') // replace url - content = content.replace(/
.*?<\/pre>/gi, '[!{_p("aside.card_aside.card_aside.card_newest_comments.code")}]') // replace code
-      content = content.replace(/<[^>]+>/g,"") // remove html tag
-
-      if (content.length > 150) {
-        content = content.substring(0,150) + '...'
-      }
-      return content
-    }
+    const keyName = 'twikoo-newest-comments'
+    const { changeContent, generateHtml, run } = window.newestComments
 
-    const getComment = () => {
+    const getComment = ele => {
       const runTwikoo = () => {
         twikoo.getRecentComments({
           envId: '!{theme.twikoo.envId}',
           region: '!{theme.twikoo.region}',
           pageSize: !{theme.aside.card_newest_comments.limit},
           includeReply: true
-        }).then(function (res) {
+        }).then(res => {
           const twikooArray = res.map(e => {
             return {
               'content': changeContent(e.comment),
@@ -32,11 +23,11 @@ script.
             }
           })
 
-          btf.saveToLocal.set('twikoo-newest-comments', JSON.stringify(twikooArray), !{theme.aside.card_newest_comments.storage}/(60*24))
-          generateHtml(twikooArray)
-        }).catch(function (err) {
-          const $dom = document.querySelector('#card-newest-comments .aside-list')
-          $dom.textContent= "!{_p('aside.card_newest_comments.error')}"
+          btf.saveToLocal.set(keyName, JSON.stringify(twikooArray), !{theme.aside.card_newest_comments.storage}/(60*24))
+          generateHtml(twikooArray, ele)
+        }).catch(err => {
+          console.error(err)
+          ele.textContent= "!{_p('aside.card_newest_comments.error')}"
         })
       }
 
@@ -47,46 +38,7 @@ script.
       }
     }
 
-    const generateHtml = array => {
-      let result = ''
-
-      if (array.length) {
-        for (let i = 0; i < array.length; i++) {
-          result += '
' - - if (!{theme.aside.card_newest_comments.avatar}) { - const name = '!{theme.lazyload.enable ? "data-lazy-src" : "src"}' - result += `${array[i].nick}` - } - - result += `
- ${array[i].content} -
${array[i].nick} /
-
` - } - } else { - result += '!{_p("aside.card_newest_comments.zero")}' - } - - let $dom = document.querySelector('#card-newest-comments .aside-list') - $dom && ($dom.innerHTML= result) - window.lazyLoadInstance && window.lazyLoadInstance.update() - window.pjax && window.pjax.refresh($dom) - } - - const newestCommentInit = () => { - if (document.querySelector('#card-newest-comments .aside-list')) { - const data = btf.saveToLocal.get('twikoo-newest-comments') - if (data) { - generateHtml(JSON.parse(data)) - } else { - getComment() - } - } - } - - newestCommentInit() - btf.addGlobalFn('pjaxComplete', newestCommentInit, 'twikoo_newestComment') + run(keyName, getComment) }) diff --git a/layout/includes/third-party/newest-comments/valine.pug b/layout/includes/third-party/newest-comments/valine.pug index e0159b9ef..6b87683b3 100644 --- a/layout/includes/third-party/newest-comments/valine.pug +++ b/layout/includes/third-party/newest-comments/valine.pug @@ -1,21 +1,12 @@ - let default_avatar = theme.valine.avatar script(src=url_for(theme.asset.blueimp_md5)) +!= partial("includes/third-party/newest-comments/common.pug", {}, { cache: true }) + script. window.addEventListener('load', () => { - const changeContent = (content) => { - if (content === '') return content - - content = content.replace(/]+>/ig, '[!{_p("aside.card_newest_comments.image")}]') // replace image link - content = content.replace(/]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[!{_p("aside.card_newest_comments.link")}]') // replace url - content = content.replace(/
.*?<\/pre>/gi, '[!{_p("aside.card_newest_comments.code")}]') // replace code
-      content = content.replace(/<[^>]+>/g,"") // remove html tag
-
-      if (content.length > 150) {
-        content = content.substring(0,150) + '...'
-      }
-      return content
-    }
+    const keyName = 'valine-newest-comments'
+    const { changeContent, generateHtml, run } = window.newestComments
 
     const getIcon = (icon, mail) => {
       if (icon) return icon
@@ -24,34 +15,7 @@ script.
       return iconUrl
     }
 
-    const generateHtml = array => {
-      let result = ''
-
-      if (array.length) {
-        for (let i = 0; i < array.length; i++) {
-          result += '
' - - if (!{theme.aside.card_newest_comments.avatar}) { - const name = '!{theme.lazyload.enable ? "data-lazy-src" : "src"}' - result += `${array[i].nick}` - } - - result += `
- ${array[i].content} -
${array[i].nick} /
-
` - } - } else { - result += '!{_p("aside.card_newest_comments.zero")}' - } - - let $dom = document.querySelector('#card-newest-comments .aside-list') - $dom && ($dom.innerHTML= result) - window.lazyLoadInstance && window.lazyLoadInstance.update() - window.pjax && window.pjax.refresh($dom) - } - - const getComment = () => { + const getComment = ele => { const serverURL = '!{theme.valine.serverURLs || `https://${theme.valine.appId.substring(0,8)}.api.lncldglobal.com` }' var settings = { @@ -66,7 +30,7 @@ script. fetch(`${serverURL}/1.1/classes/Comment?limit=!{theme.aside.card_newest_comments.limit}&order=-createdAt`,settings) .then(response => response.json()) .then(data => { - const valineArray = data.results.map(function (e) { + const valineArray = data.results.map(e => { return { 'avatar': getIcon(e.QQAvatar, e.mail), 'content': changeContent(e.comment), @@ -75,25 +39,13 @@ script. 'date': e.updatedAt, } }) - btf.saveToLocal.set('valine-newest-comments', JSON.stringify(valineArray), !{theme.aside.card_newest_comments.storage}/(60*24)) - generateHtml(valineArray) + btf.saveToLocal.set(keyName, JSON.stringify(valineArray), !{theme.aside.card_newest_comments.storage}/(60*24)) + generateHtml(valineArray, ele) }).catch(e => { - const $dom = document.querySelector('#card-newest-comments .aside-list') - $dom.textContent= "!{_p('aside.card_newest_comments.error')}" - }) - } - - const newestCommentInit = () => { - if (document.querySelector('#card-newest-comments .aside-list')) { - const data = btf.saveToLocal.get('valine-newest-comments') - if (data) { - generateHtml(JSON.parse(data)) - } else { - getComment() - } - } + console.error(e) + ele.textContent= "!{_p('aside.card_newest_comments.error')}" + }) } - newestCommentInit() - btf.addGlobalFn('pjaxComplete', newestCommentInit, 'valine_newestComment') + run(keyName, getComment) }) diff --git a/layout/includes/third-party/newest-comments/waline.pug b/layout/includes/third-party/newest-comments/waline.pug index b1888cbd4..4031d3420 100644 --- a/layout/includes/third-party/newest-comments/waline.pug +++ b/layout/includes/third-party/newest-comments/waline.pug @@ -1,49 +1,13 @@ - const serverURL = theme.waline.serverURL.replace(/\/$/, '') +!= partial("includes/third-party/newest-comments/common.pug", {}, { cache: true }) + script. window.addEventListener('load', () => { - const changeContent = content => { - if (content === '') return content - - content = content.replace(/]+>/ig, '[!{_p("aside.card_newest_comments.image")}]') // replace image link - content = content.replace(/]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[!{_p("aside.card_newest_comments.link")}]') // replace url - content = content.replace(/
.*?<\/pre>/gi, '[!{_p("aside.card_newest_comments.code")}]') // replace code
-      content = content.replace(/<[^>]+>/g,"") // remove html tag
-
-      if (content.length > 150) {
-        content = content.substring(0,150) + '...'
-      }
-      return content
-    }
-
-    const generateHtml = array => {
-      let result = ''
-
-      if (array.length) {
-        for (let i = 0; i < array.length; i++) {
-          result += '
' - - if (!{theme.aside.card_newest_comments.avatar}) { - const name = '!{theme.lazyload.enable ? "data-lazy-src" : "src"}' - result += `${array[i].nick}` - } - - result += `
- ${array[i].content} -
${array[i].nick} /
-
` - } - } else { - result += '!{_p("aside.card_newest_comments.zero")}' - } - - let $dom = document.querySelector('#card-newest-comments .aside-list') - $dom && ($dom.innerHTML= result) - window.lazyLoadInstance && window.lazyLoadInstance.update() - window.pjax && window.pjax.refresh($dom) - } + const keyName = 'waline-newest-comments' + const { changeContent, generateHtml, run } = window.newestComments - const getComment = async () => { + const getComment = async (ele) => { try { const res = await fetch('!{serverURL}/api/comment?type=recent&count=!{theme.aside.card_newest_comments.limit}', { method: 'GET' }) const result = await res.json() @@ -56,26 +20,13 @@ script. 'date': e.time || e.insertedAt } }) - btf.saveToLocal.set('waline-newest-comments', JSON.stringify(walineArray), !{theme.aside.card_newest_comments.storage}/(60*24)) - generateHtml(walineArray) + btf.saveToLocal.set(keyName, JSON.stringify(walineArray), !{theme.aside.card_newest_comments.storage}/(60*24)) + generateHtml(walineArray, ele) } catch (err) { console.error(err) - const $dom = document.querySelector('#card-newest-comments .aside-list') - $dom.textContent= "!{_p('aside.card_newest_comments.error')}" - } - } - - const newestCommentInit = () => { - if (document.querySelector('#card-newest-comments .aside-list')) { - const data = btf.saveToLocal.get('waline-newest-comments') - if (data) { - generateHtml(JSON.parse(data)) - } else { - getComment() - } + ele.textContent= "!{_p('aside.card_newest_comments.error')}" } } - newestCommentInit() - btf.addGlobalFn('pjaxComplete', newestCommentInit, 'waline_newestComment') + run(keyName, getComment) }) diff --git a/layout/includes/third-party/pjax.pug b/layout/includes/third-party/pjax.pug index 55e386c7f..c63caf189 100644 --- a/layout/includes/third-party/pjax.pug +++ b/layout/includes/third-party/pjax.pug @@ -1,9 +1,9 @@ - var pjaxExclude = 'a:not([target="_blank"])' if theme.pjax.exclude each val in theme.pjax.exclude - - pjaxExclude = pjaxExclude + `:not([href="${val}"])` + - pjaxExclude += `:not([href="${val}"])` -- let pjaxSelectors = ['head > title','#config-diff','#body-wrap','#rightside-config-hide','#rightside-config-show','.js-pjax'] +- let pjaxSelectors = ['head > title', '#config-diff', '#body-wrap', '#rightside-config-hide', '#rightside-config-show', '.js-pjax'] - let choose = theme.comments.use if choose @@ -14,49 +14,50 @@ if choose script(src=url_for(theme.asset.pjax)) script. - let pjaxSelectors = !{JSON.stringify(pjaxSelectors)} - - var pjax = new Pjax({ - elements: '!{pjaxExclude}', - selectors: pjaxSelectors, - cacheBust: false, - analytics: !{theme.google_analytics ? true : false}, - scrollRestoration: false - }) - - const triggerPjaxFn = (val) => { - if (!val) return - Object.values(val).forEach(fn => { fn() }) - } - - document.addEventListener('pjax:send', function () { - - // removeEventListener - btf.removeGlobalFnEvent('pjaxSendOnce') - btf.removeGlobalFnEvent('themeChange') - - //reset readmode - const $bodyClassList = document.body.classList - $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode') - - triggerPjaxFn(window.globalFn.pjaxSend) - }) - - document.addEventListener('pjax:complete', () => { - btf.removeGlobalFnEvent('pjaxCompleteOnce') - document.querySelectorAll('script[data-pjax]').forEach(item => { - const newScript = document.createElement('script') - const content = item.text || item.textContent || item.innerHTML || "" - Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value)) - newScript.appendChild(document.createTextNode(content)) - item.parentNode.replaceChild(newScript, item) + (() => { + const pjaxSelectors = !{JSON.stringify(pjaxSelectors)} + + window.pjax = new Pjax({ + elements: '!{pjaxExclude}', + selectors: pjaxSelectors, + cacheBust: false, + analytics: !{theme.google_analytics ? true : false}, + scrollRestoration: false }) - triggerPjaxFn(window.globalFn.pjaxComplete) - }) - - document.addEventListener('pjax:error', e => { - if (e.request.status === 404) { - pjax.loadUrl('!{url_for("/404.html")}') + const triggerPjaxFn = (val) => { + if (!val) return + Object.values(val).forEach(fn => fn()) } - }) + + document.addEventListener('pjax:send', () => { + // removeEventListener + btf.removeGlobalFnEvent('pjaxSendOnce') + btf.removeGlobalFnEvent('themeChange') + + // reset readmode + const $bodyClassList = document.body.classList + if ($bodyClassList.contains('read-mode')) $bodyClassList.remove('read-mode') + + triggerPjaxFn(window.globalFn.pjaxSend) + }) + + document.addEventListener('pjax:complete', () => { + btf.removeGlobalFnEvent('pjaxCompleteOnce') + document.querySelectorAll('script[data-pjax]').forEach(item => { + const newScript = document.createElement('script') + const content = item.text || item.textContent || item.innerHTML || "" + Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value)) + newScript.appendChild(document.createTextNode(content)) + item.parentNode.replaceChild(newScript, item) + }) + + triggerPjaxFn(window.globalFn.pjaxComplete) + }) + + document.addEventListener('pjax:error', e => { + if (e.request.status === 404) { + pjax.loadUrl('!{url_for("/404.html")}') + } + }) + })() \ No newline at end of file diff --git a/layout/includes/third-party/umami_analytics.pug b/layout/includes/third-party/umami_analytics.pug new file mode 100644 index 000000000..518afd53f --- /dev/null +++ b/layout/includes/third-party/umami_analytics.pug @@ -0,0 +1,65 @@ +- let { serverURL, website_id, option, UV_PV } = theme.umami_analytics +- const isServerURL = !!serverURL +- const baseURL = serverURL ? serverURL.replace(/\/$/, '') : 'https://cloud.umami.is' +- const apiUrl = serverURL ? serverURL.replace(/\/$/, '') + '/api' : 'https://api.umami.is/v1' + +script. + (() => { + const option = !{JSON.stringify(option)} + const config = !{JSON.stringify(UV_PV)} + + const runTrack = () => { + umami.track(props => ({ ...props, url: window.location.pathname, title: GLOBAL_CONFIG_SITE.title })) + } + + const loadUmamiJS = () => { + btf.getScript('!{baseURL}/script.js', { + 'data-website-id': '!{website_id}', + 'data-auto-track': 'false', + ...option + }).then(runTrack) + } + + const getData = async (isPost) => { + const now = Date.now() + const keyUrl = isPost ? `&url=${window.location.pathname}` : '' + const headerList = { 'Accept': 'application/json' } + if (!{isServerURL}) headerList['Authorization'] = `Bearer ${config.token}` + else headerList['x-umami-api-key'] = config.token + const res = await fetch(`!{apiUrl}/websites/!{website_id}/stats?startAt=0000000000&endAt=${now}${keyUrl}`, { + method: "GET", + headers: headerList + }) + return await res.json() + } + + const insertData = async () => { + try { + if (GLOBAL_CONFIG_SITE.isPost && config.page_pv) { + const pagePV = document.getElementById('umamiPV') + if (pagePV) { + const data = await getData(true) + pagePV.textContent = data.pageviews.value + } + } else { + const data = (config.site_uv || config.site_pv) && await getData() + if (config.site_uv) { + const siteUV = document.getElementById('umami-site-uv') + if (siteUV) siteUV.textContent = data.visitors.value + } + if (config.site_pv) { + const sitePV = document.getElementById('umami-site-pv') + if (sitePV) sitePV.textContent = data.pageviews.value + } + } + } catch (e) { + console.error('Failed to load Umami Analytics:', e) + } + } + + btf.addGlobalFn('pjaxComplete', runTrack, 'umami_analytics_run_track') + btf.addGlobalFn('pjaxComplete', insertData, 'umami_analytics_insert') + + loadUmamiJS() + insertData() + })() \ No newline at end of file diff --git a/layout/includes/widget/card_webinfo.pug b/layout/includes/widget/card_webinfo.pug index acf3048fb..09ea9c41c 100644 --- a/layout/includes/widget/card_webinfo.pug +++ b/layout/includes/widget/card_webinfo.pug @@ -17,12 +17,22 @@ if theme.aside.card_webinfo.enable .webinfo-item .item-name=_p('aside.card_webinfo.site_wordcount') + " :" .item-count=totalcount(site) - if theme.busuanzi.site_uv + if theme.umami_analytics.enable && theme.umami_analytics.UV_PV.site_uv + .webinfo-item + .item-name= _p('aside.card_webinfo.site_uv_name') + " :" + .item-count#umami-site-uv + i.fa-solid.fa-spinner.fa-spin + else if theme.busuanzi.site_uv .webinfo-item .item-name= _p('aside.card_webinfo.site_uv_name') + " :" .item-count#busuanzi_value_site_uv i.fa-solid.fa-spinner.fa-spin - if theme.busuanzi.site_pv + if theme.umami_analytics.enable && theme.umami_analytics.UV_PV.site_pv + .webinfo-item + .item-name= _p('aside.card_webinfo.site_pv_name') + " :" + .item-count#umami-site-pv + i.fa-solid.fa-spinner.fa-spin + else if theme.busuanzi.site_pv .webinfo-item .item-name= _p('aside.card_webinfo.site_pv_name') + " :" .item-count#busuanzi_value_site_pv diff --git a/layout/page.pug b/layout/page.pug index eb2663e6d..5fdbbbd37 100644 --- a/layout/page.pug +++ b/layout/page.pug @@ -11,7 +11,7 @@ block content #page(class=noCardLayout) if top_img === false && page.title - h1.page-title= page.title + .page-title= page.title case page.type when 'tags' diff --git a/package.json b/package.json index 3945458de..7f86e4840 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hexo-theme-butterfly", - "version": "5.0.0-b1", + "version": "5.0.0-b2", "description": "A Simple and Card UI Design theme for Hexo", "main": "package.json", "scripts": { diff --git a/scripts/events/comment.js b/scripts/events/comment.js index ebbe439ac..b38e1de74 100644 --- a/scripts/events/comment.js +++ b/scripts/events/comment.js @@ -6,9 +6,12 @@ hexo.extend.filter.register('before_generate', () => { const themeConfig = hexo.theme.config let { use } = themeConfig.comments if (!use) return - if (typeof use === 'string') { - use = use.split(',') - } - const newArray = use.map(item => item.toLowerCase().replace(/\b[a-z]/g, s => s.toUpperCase())) - themeConfig.comments.use = newArray + + // 確保 use 是一個陣列 + use = Array.isArray(use) ? use : use.split(',') + + // 將每個項目轉換為小寫並將首字母大寫 + themeConfig.comments.use = use.map(item => + item.trim().toLowerCase().replace(/\b[a-z]/g, s => s.toUpperCase()) + ) }) diff --git a/scripts/events/merge_config.js b/scripts/events/merge_config.js index ebca510a3..07e8bce56 100644 --- a/scripts/events/merge_config.js +++ b/scripts/events/merge_config.js @@ -386,14 +386,22 @@ hexo.extend.filter.register('before_generate', () => { crisp: { website_id: null }, - messenger: { - pageID: null, - lang: 'zh_TW' - }, baidu_analytics: null, google_analytics: null, cloudflare_analytics: null, microsoft_clarity: null, + umami_analytics: { + enable: false, + serverURL: null, + website_id: null, + option: null, + UV_PV: { + site_uv: false, + site_pv: false, + page_pv: false, + token: null + } + }, google_adsense: { enable: false, auto_ads: true, @@ -425,23 +433,23 @@ hexo.extend.filter.register('before_generate', () => { beautify: { enable: false, field: 'post', - 'title-prefix-icon': null, - 'title-prefix-icon-color': null + title_prefix_icon: null, + title_prefix_icon_color: null }, font: { - 'global-font-size': null, - 'code-font-size': null, - 'font-family': null, - 'code-font-family': null + global_font_size: null, + code_font_size: null, + font_family: null, + code_font_family: null }, blog_title_font: { font_link: null, - 'font-family': null + font_family: null }, hr_icon: { enable: true, icon: null, - 'icon-top': null + icon_top: null }, activate_power_mode: { enable: false, diff --git a/scripts/helpers/aside_archives.js b/scripts/helpers/aside_archives.js index 779c1d45f..1cf752181 100644 --- a/scripts/helpers/aside_archives.js +++ b/scripts/helpers/aside_archives.js @@ -1,98 +1,68 @@ -/** - * Butterfly - * for aside archives - */ - 'use strict' hexo.extend.helper.register('aside_archives', function (options = {}) { - const { config } = this + const { config, page, site, url_for, _p } = this const archiveDir = config.archive_dir const { timezone } = config - const lang = toMomentLocale(this.page.lang || this.page.language || config.language) - let { format } = options + const lang = toMomentLocale(page.lang || page.language || config.language) const type = options.type || 'monthly' - const { transform } = options + const format = options.format || (type === 'monthly' ? 'MMMM YYYY' : 'YYYY') const showCount = Object.prototype.hasOwnProperty.call(options, 'show_count') ? options.show_count : true const order = options.order || -1 + const limit = options.limit const compareFunc = type === 'monthly' ? (yearA, monthA, yearB, monthB) => yearA === yearB && monthA === monthB : (yearA, monthA, yearB, monthB) => yearA === yearB - const limit = options.limit - let result = '' - - if (!format) { - format = type === 'monthly' ? 'MMMM YYYY' : 'YYYY' - } - const posts = this.site.posts.sort('date', order) - if (!posts.length) return result + const posts = site.posts.sort('date', order) + if (!posts.length) return '' const data = [] - let length = 0 - posts.forEach(post => { - // Clone the date object to avoid pollution let date = post.date.clone() - if (timezone) date = date.tz(timezone) const year = date.year() const month = date.month() + 1 - const lastData = data[length - 1] - if (!lastData || !compareFunc(lastData.year, lastData.month, year, month)) { + if (!data.length || !compareFunc(data[data.length - 1].year, data[data.length - 1].month, year, month)) { if (lang) date = date.locale(lang) - const name = date.format(format) - length = data.push({ - name, - year, - month, - count: 1 - }) + data.push({ name: date.format(format), year, month, count: 1 }) } else { - lastData.count++ + data[data.length - 1].count++ } }) const link = item => { let url = `${archiveDir}/${item.year}/` - if (type === 'monthly') { - if (item.month < 10) url += '0' - url += `${item.month}/` + url += item.month < 10 ? `0${item.month}/` : `${item.month}/` } - - return this.url_for(url) + return url_for(url) } const len = data.length - const Judge = limit === 0 ? len : Math.min(len, limit) - - result += `
${this._p('aside.card_archives')}` - - if (len > Judge) { - result += ` - ` - } - - result += '
    ' - - for (let i = 0; i < Judge; i++) { + const limitLength = limit === 0 ? len : Math.min(len, limit) + + let result = ` +
    + + ${_p('aside.card_archives')} + ${len > limitLength ? `` : ''} +
    + ' @@ -100,12 +70,6 @@ hexo.extend.helper.register('aside_archives', function (options = {}) { }) const toMomentLocale = function (lang) { - if (lang === undefined) { - return undefined - } - - // moment.locale('') equals moment.locale('en') - // moment.locale(null) equals moment.locale('en') if (!lang || lang === 'en' || lang === 'default') { return 'en' } diff --git a/scripts/helpers/aside_categories.js b/scripts/helpers/aside_categories.js index 244b163e7..4fb31355d 100644 --- a/scripts/helpers/aside_categories.js +++ b/scripts/helpers/aside_categories.js @@ -1,66 +1,52 @@ -/** - * Butterfly - * for aside categories - */ - 'use strict' -hexo.extend.helper.register('aside_categories', function (categories, options) { - if (!options && (!categories || !Object.prototype.hasOwnProperty.call(categories, 'length')) - ) { - options = categories +hexo.extend.helper.register('aside_categories', function (categories, options = {}) { + if (!categories || !Object.prototype.hasOwnProperty.call(categories, 'length')) { + options = categories || {} categories = this.site.categories } if (!categories || !categories.length) return '' - options = options || {} + const { config } = this - const showCount = Object.prototype.hasOwnProperty.call(options, 'show_count') - ? options.show_count - : true + const showCount = Object.prototype.hasOwnProperty.call(options, 'show_count') ? options.show_count : true const depth = options.depth ? parseInt(options.depth, 10) : 0 const orderby = options.orderby || 'name' const order = options.order || 1 const categoryDir = this.url_for(config.category_dir) - const limit = options.limit === 0 ? categories.length : options.limit + const limit = options.limit === 0 ? categories.length : (options.limit || categories.length) const isExpand = options.expand !== 'none' const expandClass = isExpand && options.expand === true ? 'expand' : '' const buttonLabel = this._p('aside.more_button') - const prepareQuery = (parent) => { - const query = {} - if (parent) { query.parent = parent } else { query.parent = { $exists: false } } - return categories.find(query).sort(orderby, order).filter((cat) => cat.length) + + const prepareQuery = parent => { + const query = parent ? { parent } : { parent: { $exists: false } } + return categories.find(query).sort(orderby, order).filter(cat => cat.length) } - let expandBtn = '' - const hierarchicalList = (t, level, parent, topparent = true) => { + const hierarchicalList = (remaining, level = 0, parent) => { let result = '' - const isTopParent = topparent - if (t > 0) { - prepareQuery(parent).forEach((cat, i) => { - if (t > 0) { - t = t - 1 - let child + if (remaining > 0) { + prepareQuery(parent).forEach(cat => { + if (remaining > 0) { + remaining -= 1 + let child = '' if (!depth || level + 1 < depth) { - const childList = hierarchicalList(t, level + 1, cat._id, false) - child = childList[0] - t = childList[1] + const childList = hierarchicalList(remaining, level + 1, cat._id) + child = childList.result + remaining = childList.remaining } - const parentClass = isExpand && isTopParent && child ? 'parent' : '' - + const parentClass = isExpand && !parent && child ? 'parent' : '' result += `
  • ` - result += `` - result += `${cat.name}` if (showCount) { result += `${cat.length}` } - if (isExpand && isTopParent && child) { - expandBtn = ' expandBtn' + if (isExpand && !parent && child) { result += `` } @@ -74,26 +60,22 @@ hexo.extend.helper.register('aside_categories', function (categories, options) { } }) } - - return [result, t] + return { result, remaining } } - const list = hierarchicalList(limit, 0) + const list = hierarchicalList(limit) - const moreButton = function () { - if (categories.length <= limit) return '' - const moreHtml = ` - ` - - return moreHtml - } + const moreButton = categories.length > limit + ? ` + ` + : '' return `
    ${this._p('aside.card_categories')} - ${moreButton()} -
    -
      - ${list[0]} -
    ` + ${moreButton} + +
      + ${list.result} +
    ` }) diff --git a/scripts/helpers/inject_head_js.js b/scripts/helpers/inject_head_js.js index 574d18ea6..63723af17 100644 --- a/scripts/helpers/inject_head_js.js +++ b/scripts/helpers/inject_head_js.js @@ -1,14 +1,3 @@ -/** - * Butterfly - * inject js to head - * - * addGlobalFn - * pjaxSendOnce - remove in pjaxSend - * pjaxCompleteOnce - remove in pjaxComplete - * pjaxSend - run in pjaxSend - * pjaxComplete - run in pjaxComplete - */ - 'use strict' hexo.extend.helper.register('inject_head_js', function () { @@ -16,93 +5,62 @@ hexo.extend.helper.register('inject_head_js', function () { const start = darkmode.start || 6 const end = darkmode.end || 18 const { theme_color } = hexo.theme.config - 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 createCustonJs = () => { - return ` - const saveToLocal = { - set: (key, value, ttl) => { - if (ttl === 0) return - const now = Date.now() - const expiry = now + ttl * 86400000 - const item = { - value, - expiry - } - localStorage.setItem(key, JSON.stringify(item)) - }, - - get: key => { - const itemStr = localStorage.getItem(key) - - if (!itemStr) { - return undefined - } - const item = JSON.parse(itemStr) - const now = Date.now() - - if (now > item.expiry) { - localStorage.removeItem(key) - return undefined - } - return item.value + 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 createCustomJs = () => ` + const saveToLocal = { + set: (key, value, ttl) => { + if (!ttl) return + const expiry = Date.now() + ttl * 86400000 + localStorage.setItem(key, JSON.stringify({ value, expiry })) + }, + get: key => { + const itemStr = localStorage.getItem(key) + if (!itemStr) return undefined + const { value, expiry } = JSON.parse(itemStr) + if (Date.now() > expiry) { + localStorage.removeItem(key) + return undefined } + return value } - - window.btf = { - saveToLocal: saveToLocal, - getScript: (url, attr = {}) => new Promise((resolve, reject) => { - const script = document.createElement('script') - script.src = url - script.async = true - script.onerror = reject - script.onload = script.onreadystatechange = function() { - const loadState = this.readyState - if (loadState && loadState !== 'loaded' && loadState !== 'complete') return - script.onload = script.onreadystatechange = null - resolve() - } - - Object.keys(attr).forEach(key => { - script.setAttribute(key, attr[key]) - }) - - document.head.appendChild(script) - }), - - getCSS: (url, id = false) => new Promise((resolve, reject) => { - const link = document.createElement('link') - link.rel = 'stylesheet' - link.href = url - if (id) link.id = id - 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) - }), - - addGlobalFn: (key, fn, name = false, parent = window) => { - const pjaxEnable = ${pjax.enable} - if (!pjaxEnable && key.startsWith('pjax')) return + } - const globalFn = parent.globalFn || {} - const keyObj = globalFn[key] || {} - - if (name && keyObj[name]) return - - name = name || Object.keys(keyObj).length - keyObj[name] = fn - globalFn[key] = keyObj - parent.globalFn = globalFn + window.btf = { + saveToLocal, + getScript: (url, attr = {}) => new Promise((resolve, reject) => { + const script = document.createElement('script') + script.src = url + script.async = true + Object.entries(attr).forEach(([key, val]) => script.setAttribute(key, val)) + script.onload = script.onreadystatechange = () => { + if (!script.readyState || /loaded|complete/.test(script.readyState)) resolve() + } + script.onerror = reject + document.head.appendChild(script) + }), + getCSS: (url, id) => new Promise((resolve, reject) => { + const link = document.createElement('link') + link.rel = 'stylesheet' + link.href = url + if (id) link.id = id + link.onload = link.onreadystatechange = () => { + if (!link.readyState || /loaded|complete/.test(link.readyState)) resolve() } + link.onerror = reject + document.head.appendChild(link) + }), + addGlobalFn: (key, fn, name = false, parent = window) => { + if (!${pjax.enable} && key.startsWith('pjax')) return + const globalFn = parent.globalFn || {} + globalFn[key] = globalFn[key] || {} + if (name && globalFn[key][name]) return + globalFn[key][name || Object.keys(globalFn[key]).length] = fn + parent.globalFn = globalFn } - ` - } + } + ` const createDarkmodeJs = () => { if (!darkmode.enable) return '' @@ -123,80 +81,76 @@ hexo.extend.helper.register('inject_head_js', function () { btf.activateDarkMode = activateDarkMode btf.activateLightMode = activateLightMode - - const t = saveToLocal.get('theme') - ` - - const autoChangeMode = darkmode.autoChangeMode - if (autoChangeMode === 1) { - darkmodeJs += ` - const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches - const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches - const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches - const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified + const theme = saveToLocal.get('theme') + ` - if (t === undefined) { - if (isLightMode) activateLightMode() - else if (isDarkMode) activateDarkMode() - else if (isNotSpecified || hasNoSupport) { - const now = new Date() - const hour = now.getHours() + switch (darkmode.autoChangeMode) { + case 1: + darkmodeJs += ` + const mediaQueryDark = window.matchMedia('(prefers-color-scheme: dark)') + const mediaQueryLight = window.matchMedia('(prefers-color-scheme: light)') + + if (theme === undefined) { + if (mediaQueryLight.matches) activateLightMode() + else if (mediaQueryDark.matches) activateDarkMode() + else { + const hour = new Date().getHours() const isNight = hour <= ${start} || hour >= ${end} isNight ? activateDarkMode() : activateLightMode() } - window.matchMedia('(prefers-color-scheme: dark)').addListener(e => { + mediaQueryDark.addEventListener('change', () => { if (saveToLocal.get('theme') === undefined) { e.matches ? activateDarkMode() : activateLightMode() } }) - } else if (t === 'light') activateLightMode() - else activateDarkMode() + } else { + theme === 'light' ? activateLightMode() : activateDarkMode() + } ` - } else if (autoChangeMode === 2) { - darkmodeJs += ` - const now = new Date() - const hour = now.getHours() + break + case 2: + darkmodeJs += ` + const hour = new Date().getHours() const isNight = hour <= ${start} || hour >= ${end} - if (t === undefined) isNight ? activateDarkMode() : activateLightMode() - else if (t === 'light') activateLightMode() - else activateDarkMode() + if (theme === undefined) isNight ? activateDarkMode() : activateLightMode() + else theme === 'light' ? activateLightMode() : activateDarkMode() + ` + break + default: + darkmodeJs += ` + theme === 'dark' ? activateDarkMode() : theme === 'light' ? activateLightMode() : null ` - } else { - darkmodeJs += ` - if (t === 'dark') activateDarkMode() - else if (t === 'light') activateLightMode() - ` } return darkmodeJs } - const createAsideStatus = () => { + const createAsideStatusJs = () => { if (!aside.enable || !aside.button) return '' - return ` const asideStatus = saveToLocal.get('aside-status') if (asideStatus !== undefined) { - if (asideStatus === 'hide') { - document.documentElement.classList.add('hide-aside') - } else { - document.documentElement.classList.remove('hide-aside') - } + document.documentElement.classList.toggle('hide-aside', asideStatus === 'hide') } ` } - const createDetectApple = () => { - return ` - const detectApple = () => { - if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){ - document.documentElement.classList.add('apple') - } + const createDetectAppleJs = () => ` + const detectApple = () => { + if (/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)) { + document.documentElement.classList.add('apple') } - detectApple() - ` - } - - return `` + } + detectApple() + ` + + return `` }) diff --git a/scripts/helpers/page.js b/scripts/helpers/page.js index a0ae86086..2bdcffd13 100644 --- a/scripts/helpers/page.js +++ b/scripts/helpers/page.js @@ -9,43 +9,33 @@ hexo.extend.helper.register('truncate', (content, length) => { hexo.extend.helper.register('cloudTags', function (options = {}) { const env = this - let { source, minfontsize, maxfontsize, limit, unit, orderby, order } = options - unit = unit || 'px' + let { source, minfontsize, maxfontsize, limit, unit = 'px', orderby, order } = options - let result = '' if (limit > 0) { source = source.limit(limit) } - const sizes = [] - source.sort('length').forEach(tag => { - const { length } = tag - if (sizes.includes(length)) return - sizes.push(length) - }) + const sizes = [...new Set(source.map(tag => tag.length).sort((a, b) => a - b))] const getRandomColor = () => { const randomColor = () => Math.floor(Math.random() * 201) const r = randomColor() const g = randomColor() const b = randomColor() - // 確保顏色不是太暗,通過增加一個最低值 return `rgb(${Math.max(r, 50)}, ${Math.max(g, 50)}, ${Math.max(b, 50)})` } - const generateStyle = (size, unit) => { - const fontSize = parseFloat(size.toFixed(2)) + unit - const color = getRandomColor() - return `font-size: ${fontSize}; color: ${color};` - } + const generateStyle = (size, unit) => + `font-size: ${parseFloat(size.toFixed(2)) + unit}; color: ${getRandomColor()};` const length = sizes.length - 1 - source.sort(orderby, order).forEach(tag => { + const result = source.sort(orderby, order).map(tag => { const ratio = length ? sizes.indexOf(tag.length) / length : 0 const size = minfontsize + ((maxfontsize - minfontsize) * ratio) const style = generateStyle(size, unit) - result += `${tag.name}` - }) + return `${tag.name}` + }).join('') + return result }) @@ -57,9 +47,8 @@ hexo.extend.helper.register('md5', function (path) { return crypto.createHash('md5').update(decodeURI(this.url_for(path))).digest('hex') }) -hexo.extend.helper.register('injectHtml', function (data) { - if (!data) return '' - return data.join('') +hexo.extend.helper.register('injectHtml', data => { + return data ? data.join('') : '' }) hexo.extend.helper.register('findArchivesTitle', function (page, menu, date) { @@ -75,7 +64,8 @@ hexo.extend.helper.register('findArchivesTitle', function (page, menu, date) { const loop = (m) => { for (const key in m) { if (typeof m[key] === 'object') { - loop(m[key]) + const result = loop(m[key]) + if (result) return result } if (/\/archives\//.test(m[key])) { @@ -87,7 +77,7 @@ hexo.extend.helper.register('findArchivesTitle', function (page, menu, date) { return loop(menu) || defaultTitle }) -hexo.extend.helper.register('getBgPath', function (path) { +hexo.extend.helper.register('getBgPath', path => { if (!path) return '' const absoluteUrlPattern = /^(?:[a-z][a-z\d+.-]*:)?\/\//i diff --git a/scripts/helpers/series.js b/scripts/helpers/series.js index e1c933837..ba202af7b 100644 --- a/scripts/helpers/series.js +++ b/scripts/helpers/series.js @@ -2,14 +2,14 @@ hexo.extend.helper.register('groupPosts', function () { const getGroupArray = array => { - const groups = {} - array.forEach(item => { - const Key = item.series - if (!Key) return - groups[Key] = groups[Key] || [] - groups[Key].push(item) - }) - return groups + return array.reduce((groups, item) => { + const key = item.series + if (key) { + groups[key] = groups[key] || [] + groups[key].push(item) + } + return groups + }, {}) } const sortPosts = posts => { diff --git a/scripts/tag/button.js b/scripts/tag/button.js index 624cdd342..44f664820 100644 --- a/scripts/tag/button.js +++ b/scripts/tag/button.js @@ -10,11 +10,12 @@ const urlFor = require('hexo-util').url_for.bind(hexo) const btn = args => { - args = args.join(' ').split(',') - const [url = '', text = '', icon = '', option = ''] = args.map(arg => arg.trim()) + const [url = '', text = '', icon = '', option = ''] = args.join(' ').split(',').map(arg => arg.trim()) - return `${icon.length ? `` : ''}${text.length ? `${text}` : ''}` + const iconHTML = icon ? `` : '' + const textHTML = text ? `${text}` : '' + + return `${iconHTML}${textHTML}` } hexo.extend.tag.register('btn', btn, { ends: false }) diff --git a/scripts/tag/flink.js b/scripts/tag/flink.js index e41a52ffe..b54ccecfd 100644 --- a/scripts/tag/flink.js +++ b/scripts/tag/flink.js @@ -7,30 +7,25 @@ const urlFor = require('hexo-util').url_for.bind(hexo) const flinkFn = (args, content) => { - content = hexo.render.renderSync({ text: content, engine: 'yaml' }) - + const data = hexo.render.renderSync({ text: content, engine: 'yaml' }) let result = '' - content.forEach(i => { - const className = i.class_name ? `` : '' - const classDesc = i.class_desc ? `` : '' - - let listResult = '' - - i.link_list.forEach(j => { - listResult += ` - ` - }) - - result += `${className}${classDesc} ` + data.forEach(item => { + const className = item.class_name ? `` : '' + const classDesc = item.class_desc ? `` : '' + + const listResult = item.link_list.map(link => ` + `).join('') + + result += `${className}${classDesc}` }) return `` diff --git a/scripts/tag/series.js b/scripts/tag/series.js index 81088369c..4d811ea76 100644 --- a/scripts/tag/series.js +++ b/scripts/tag/series.js @@ -14,9 +14,10 @@ const groups = {} hexo.extend.filter.register('before_post_render', data => { if (!hexo.theme.config.series.enable) return data + const { layout, series } = data if (layout === 'post' && series) { - groups[series] = groups[series] || [] + if (!groups[series]) groups[series] = [] groups[series].push({ title: data.title, path: data.path, @@ -47,23 +48,16 @@ function series (args) { const itemA = isSortByTitle ? a.title.toUpperCase() : a.date const itemB = isSortByTitle ? b.title.toUpperCase() : b.date - if (itemA < itemB) { - return isAsc ? -1 : 1 - } - if (itemA > itemB) { - return isAsc ? 1 : -1 - } - return 0 + return itemA < itemB ? (isAsc ? -1 : 1) : itemA > itemB ? (isAsc ? 1 : -1) : 0 } seriesArr.sort(compareFn) - let result = '' - seriesArr.forEach(ele => { - result += `
  • ${ele.title}
  • ` - }) + const listItems = seriesArr.map(ele => + `
  • ${ele.title}
  • ` + ).join('') - return series.number ? `
      ${result}
    ` : `
      ${result}
    ` + return series.number ? `
      ${listItems}
    ` : `
      ${listItems}
    ` } hexo.extend.tag.register('series', series, { ends: false }) diff --git a/scripts/tag/tabs.js b/scripts/tag/tabs.js index 29321fdfb..8fffa9315 100644 --- a/scripts/tag/tabs.js +++ b/scripts/tag/tabs.js @@ -23,35 +23,27 @@ const postTabs = (args, content) => { } for (let i = 0; i < matches.length; i += 2) { - const tabParameters = matches[i].split('@') + const [tabCaption = '', tabIcon = ''] = matches[i].split('@') let postContent = matches[i + 1] - let tabCaption = tabParameters[0] || '' - let tabIcon = tabParameters[1] || '' postContent = hexo.render.renderSync({ text: postContent, engine: 'markdown' }).trim() - tabId += 1 - if (tabCaption.length === 0 && tabIcon.length === 0) tabCaption = tabName + ' ' + tabId + const caption = (tabCaption || tabIcon) ? tabCaption : `${tabName} ${tabId}` + const iconHtml = tabIcon ? `` : '' + const isActive = (tabActive > 0 && tabActive === tabId) || (tabActive === 0 && tabId === 1) ? ' active' : '' - const icon = tabIcon.trim() - tabIcon.length > 0 && (tabIcon = ``) + if (isActive) noDefault = false - let isActive = '' - if ((tabActive > 0 && tabActive === tabId) || (tabActive === 0 && tabId === 1)) { - isActive = ' active' - noDefault = false - } - tabNav += `` + tabNav += `` tabContent += `
    ${postContent}
    ` } const toTop = '
    ' - tabNav = `` tabContent = `
    ${tabContent}
    ` - return `
    ${tabNav + tabContent + toTop}
    ` + return `
    ${tabNav}${tabContent}${toTop}
    ` } hexo.extend.tag.register('tabs', postTabs, { ends: true }) diff --git a/scripts/tag/timeline.js b/scripts/tag/timeline.js index 6dde854e4..12579406c 100644 --- a/scripts/tag/timeline.js +++ b/scripts/tag/timeline.js @@ -35,7 +35,7 @@ const timeLineFn = (args, content) => { result += `
    ${tlTitleHtml + tlContentHtml}
    ` } - return `
    ${result}
    ` + return `
    ${result}
    ` } hexo.extend.tag.register('timeline', timeLineFn, { ends: true }) diff --git a/source/css/_global/function.styl b/source/css/_global/function.styl index a210c525e..c0ad3519e 100644 --- a/source/css/_global/function.styl +++ b/source/css/_global/function.styl @@ -15,10 +15,13 @@ text-rendering: auto -webkit-font-smoothing: antialiased -addBorderRadius(x = 6) +addBorderRadius(x = 6, hide = false) if hexo-config('rounded_corners_ui') border-radius: unit(x, 'px') + if hide + overflow: hidden + // card hover .cardHover background: var(--card-bg) diff --git a/source/css/_layout/chat.styl b/source/css/_layout/chat.styl index 6b9551bd8..ebe464dd1 100644 --- a/source/css/_layout/chat.styl +++ b/source/css/_layout/chat.styl @@ -6,13 +6,4 @@ if hexo-config('chat.rightside_button') == true width: 1px !important height: 1px !important opacity: 0 !important - pointer-events: none - - if hexo-config('chat.use') == 'messenger' - .fb_dialog, - .fb-customerchat - visibility: hidden !important - width: 1px !important - height: 1px !important - opacity: 0 !important - pointer-events: none + pointer-events: none \ No newline at end of file diff --git a/source/css/_layout/head.styl b/source/css/_layout/head.styl index 06e89d4c0..a18360370 100644 --- a/source/css/_layout/head.styl +++ b/source/css/_layout/head.styl @@ -128,6 +128,9 @@ height: 60px background: 0 + .title-seo + display: none + #nav background: rgba(255, 255, 255, .8) box-shadow: 0 5px 6px -5px rgba(133, 133, 133, .6) @@ -157,6 +160,12 @@ .site-name text-shadow: none + & > a:first-child + display: none + + & > a:last-child + display: inline + a, span.site-page, #toggle-menu @@ -195,8 +204,10 @@ max-height: calc(100vh - 170px) #page - h1.page-title - margin: 8px 0 20px + .page-title + margin: 0 0 10px + font-weight: bold + font-size: 2em // for not top_img #post @@ -301,6 +312,9 @@ height: 36px vertical-align: middle + .nav-page-title + display: none + #toggle-menu display: none padding: 2px 0 0 6px diff --git a/source/css/_layout/third-party.styl b/source/css/_layout/third-party.styl index aa20ed401..50c76f579 100644 --- a/source/css/_layout/third-party.styl +++ b/source/css/_layout/third-party.styl @@ -139,8 +139,9 @@ if hexo-config('math.use') &:before content: none -.snackbar-css - border-radius: 5px !important +.snackbar-container.snackbar-css + addBorderRadius(5) + opacity: .85 !important .abc-music-sheet margin: 0 0 20px diff --git a/source/css/_page/archives.styl b/source/css/_page/archives.styl index 35efa6b77..0adf37b88 100644 --- a/source/css/_page/archives.styl +++ b/source/css/_page/archives.styl @@ -69,6 +69,7 @@ &.year font-size: 1.43em + margin-bottom: 10px &:hover &:before diff --git a/source/css/_page/tags.styl b/source/css/_page/tags.styl index d8f407ad3..cfd25576e 100644 --- a/source/css/_page/tags.styl +++ b/source/css/_page/tags.styl @@ -22,6 +22,6 @@ +maxWidth768() font-size: 2em -h1.page-title +.page-title & + .tag-cloud-list text-align: left diff --git a/source/css/_tags/gallery.styl b/source/css/_tags/gallery.styl index fc817e771..1ab8acbb4 100644 --- a/source/css/_tags/gallery.styl +++ b/source/css/_tags/gallery.styl @@ -127,8 +127,12 @@ &:hover background: var(--btn-hover-color) + i + margin-left: 8px + i margin-left: 4px + transition: all .3s .loading-container display: inline-block diff --git a/source/css/_tags/hide.styl b/source/css/_tags/hide.styl index a37939774..35cf3a0b5 100644 --- a/source/css/_tags/hide.styl +++ b/source/css/_tags/hide.styl @@ -36,7 +36,7 @@ .toggle margin-bottom: 20px border: 1px solid $tag-hide-toggle-bg - addBorderRadius() + addBorderRadius(5, true) & > .toggle-button padding: 6px 15px diff --git a/source/css/_tags/timeline.styl b/source/css/_tags/timeline.styl index aba927bab..5e1b89c1b 100644 --- a/source/css/_tags/timeline.styl +++ b/source/css/_tags/timeline.styl @@ -1,7 +1,7 @@ #article-container .timeline - margin: 0 0 20px 10px - padding: 14px 20px 5px + margin: 0 10px 20px + padding: 14px 0 5px 20px border-left: 2px solid var(--timeline-color, $theme-color) for $type in $color-types diff --git a/source/css/var.styl b/source/css/var.styl index 7b5b6e536..6ab9a8312 100644 --- a/source/css/var.styl +++ b/source/css/var.styl @@ -18,20 +18,20 @@ $chinseFont = $language == 'zh-CN' ? 'Microsoft YaHei' : 'Microsoft JhengHei' $dafault-font-family = -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Helvetica Neue', Lato, Roboto, 'PingFang SC', $chinseFont, sans-serif $dafault-code-font = consolas, Menlo, 'PingFang SC', $chinseFont, sans-serif -$font-family = hexo-config('font.font-family') ? unquote(hexo-config('font.font-family')) : $dafault-font-family -$code-font-family = hexo-config('font.code-font-family') ? unquote(hexo-config('font.code-font-family')) : $dafault-code-font -$site-name-font = hexo-config('blog_title_font.font-family') && unquote(hexo-config('blog_title_font.font-family')) +$font-family = hexo-config('font.font_family') ? unquote(hexo-config('font.font_family')) : $dafault-font-family +$code-font-family = hexo-config('font.code_font_family') ? unquote(hexo-config('font.code_font_family')) : $dafault-code-font +$site-name-font = hexo-config('blog_title_font.font_family') && unquote(hexo-config('blog_title_font.font_family')) // hr $hrEnable = hexo-config('hr_icon') && hexo-config('hr_icon.enable') $hr-icon = $hrEnable && hexo-config('hr_icon.icon') ? hexo-config('hr_icon.icon') : '\f0c4' -$hr-icon-top = $hrEnable && hexo-config('hr_icon.icon-top') ? convert(hexo-config('hr_icon.icon-top')) : -10px +$hr-icon-top = $hrEnable && hexo-config('hr_icon.icon_top') ? convert(hexo-config('hr_icon.icon_top')) : -10px // page beatutify $beautifyEnable = hexo-config('beautify.enable') -$title-prefix-icon = $beautifyEnable && hexo-config('beautify.title-prefix-icon') ? hexo-config('beautify.title-prefix-icon') : '\f0c1' -$title-prefix-icon-color = $beautifyEnable && hexo-config('beautify.title-prefix-icon-color') ? convert(hexo-config('beautify.title-prefix-icon-color')) : $light-red +$title-prefix-icon = $beautifyEnable && hexo-config('beautify.title_prefix_icon') ? hexo-config('beautify.title_prefix_icon') : '\f0c1' +$title-prefix-icon-color = $beautifyEnable && hexo-config('beautify.title_prefix_icon_color') ? convert(hexo-config('beautify.title_prefix_icon_color')) : $light-red // Global Variables -$font-size = hexo-config('font.global-font-size') ? convert(hexo-config('font.global-font-size')) : 14px -$code-font-size = hexo-config('font.code-font-size') ? convert(hexo-config('font.code-font-size')) : var(--global-font-size) +$font-size = hexo-config('font.global_font_size') ? convert(hexo-config('font.global_font_size')) : 14px +$code-font-size = hexo-config('font.code_font_size') ? convert(hexo-config('font.code_font_size')) : var(--global-font-size) $font-color = #1F2D3D $text-line-height = 2 $index_top_img_height = hexo-config('index_top_img_height') ? convert(hexo-config('index_top_img_height')) : 100vh diff --git a/source/js/main.js b/source/js/main.js index d5371edb9..dc6648af6 100644 --- a/source/js/main.js +++ b/source/js/main.js @@ -82,11 +82,12 @@ document.addEventListener('DOMContentLoaded', () => { } } - const copy = ctx => { - if (document.queryCommandSupported && document.queryCommandSupported('copy')) { - document.execCommand('copy') + const copy = async (text, ctx) => { + try { + await navigator.clipboard.writeText(text) alertInfo(ctx, GLOBAL_CONFIG.copy.success) - } else { + } catch (err) { + console.error('Failed to copy: ', err) alertInfo(ctx, GLOBAL_CONFIG.copy.noSupport) } } @@ -95,14 +96,10 @@ document.addEventListener('DOMContentLoaded', () => { const highlightCopyFn = (ele, clickEle) => { const $buttonParent = ele.parentNode $buttonParent.classList.add('copy-true') - const selection = window.getSelection() - const range = document.createRange() const preCodeSelector = isPrismjs ? 'pre code' : 'table .code pre' - range.selectNodeContents($buttonParent.querySelector(`${preCodeSelector}`)) - selection.removeAllRanges() - selection.addRange(range) - copy(clickEle.previousElementSibling) - selection.removeAllRanges() + const codeElement = $buttonParent.querySelector(preCodeSelector) + if (!codeElement) return + copy(codeElement.innerText, clickEle.previousElementSibling) $buttonParent.classList.remove('copy-true') } @@ -238,8 +235,8 @@ document.addEventListener('DOMContentLoaded', () => { gap: 5, isConstantSize: true, sizeRange: [150, 600], - useResizeObserver: true, - observeChildren: true, + // useResizeObserver: true, + // observeChildren: true, useTransform: true // useRecycle: false }) diff --git a/source/js/tw_cn.js b/source/js/tw_cn.js index 9ac846d1f..c19d69cd9 100644 --- a/source/js/tw_cn.js +++ b/source/js/tw_cn.js @@ -20,19 +20,31 @@ document.addEventListener('DOMContentLoaded', () => { } const translateBody = (fobj) => { - const objs = typeof fobj === 'object' ? fobj.childNodes : document.body.childNodes - for (let i = 0; i < objs.length; i++) { - const obj = objs.item(i) - if ('BR|HR'.includes(obj.tagName) || obj === translateButtonObject) continue - - if (obj.title) obj.title = translateText(obj.title) - if (obj.alt) obj.alt = translateText(obj.alt) - if (obj.placeholder) obj.placeholder = translateText(obj.placeholder) - if (obj.tagName === 'INPUT' && obj.value && obj.type !== 'text' && obj.type !== 'hidden') { - obj.value = translateText(obj.value) + const nodes = typeof fobj === 'object' ? fobj.childNodes : document.body.childNodes + + for (const node of nodes) { + // Skip BR, HR tags, or the translate button object + if (['BR', 'HR'].includes(node.tagName) || node === translateButtonObject) continue + + if (node.nodeType === Node.ELEMENT_NODE) { + const { tagName, title, alt, placeholder, value, type } = node + + // Translate title, alt, placeholder + if (title) node.title = translateText(title) + if (alt) node.alt = translateText(alt) + if (placeholder) node.placeholder = translateText(placeholder) + + // Translate input value except text and hidden types + if (tagName === 'INPUT' && value && type !== 'text' && type !== 'hidden') { + node.value = translateText(value) + } + + // Recursively translate child nodes + translateBody(node) + } else if (node.nodeType === Node.TEXT_NODE) { + // Translate text node data + node.data = translateText(node.data) } - if (obj.nodeType === 3) obj.data = translateText(obj.data) - else translateBody(obj) } } diff --git a/source/js/utils.js b/source/js/utils.js index 3ac6f0a15..781f0f043 100644 --- a/source/js/utils.js +++ b/source/js/utils.js @@ -98,10 +98,10 @@ if (!more) return Math.floor(diffDay) - if (diffMonth > 24) return datePost.toISOString().slice(0, 10) - if (diffMonth >= 3) return `${Math.floor(diffMonth)} ${dateSuffix.month}` - if (diffDay >= 3) return `${Math.floor(diffDay)} ${dateSuffix.day}` - if (diffHour >= 3) return `${Math.floor(diffHour)} ${dateSuffix.hour}` + if (diffMonth > 12) return datePost.toISOString().slice(0, 10) + if (diffMonth >= 1) return `${Math.floor(diffMonth)} ${dateSuffix.month}` + if (diffDay >= 1) return `${Math.floor(diffDay)} ${dateSuffix.day}` + if (diffHour >= 1) return `${Math.floor(diffHour)} ${dateSuffix.hour}` if (diffMin >= 1) return `${Math.floor(diffMin)} ${dateSuffix.min}` return dateSuffix.just }, @@ -145,18 +145,19 @@ requestAnimationFrame(animate) }, - animateIn: (ele, text) => { + animateIn: (ele, animation) => { ele.style.display = 'block' - ele.style.animation = text + ele.style.animation = animation }, - animateOut: (ele, text) => { - ele.addEventListener('animationend', function f () { + animateOut: (ele, animation) => { + const handleAnimationEnd = () => { ele.style.display = '' ele.style.animation = '' - ele.removeEventListener('animationend', f) - }) - ele.style.animation = text + ele.removeEventListener('animationend', handleAnimationEnd) + } + ele.addEventListener('animationend', handleAnimationEnd) + ele.style.animation = animation }, wrap: (selector, eleType, options) => {