Mayx's Home Page
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

174 lines
6.6 KiB

  1. /**
  2. * PJAX 初始化与页面切换重绑定脚本
  3. * 依赖jQuery, jquery.pjax.min.js
  4. * 加载顺序 jquery.pjax.min.js 之后body 末尾
  5. */
  6. (function ($) {
  7. // ========== 常量 ==========
  8. var CONTAINER = '#pjax-container';
  9. var PJAX_OPTS = {
  10. container: CONTAINER,
  11. fragment: CONTAINER,
  12. timeout: 8000,
  13. scrollTo: false
  14. };
  15. // ========== 各组件重初始化 ==========
  16. /** AI 摘要(post.html 内联脚本,pjax 后由 executeScripts 触发) */
  17. function reinitAISummary() {
  18. if (typeof ai_gen === 'function' && $('#ai-output').length) {
  19. try { ai_gen(); } catch (e) { /* ignore */ }
  20. }
  21. }
  22. /** 关键词高亮 */
  23. function reinitHighlight() {
  24. var keyword = new URLSearchParams(window.location.search).get('kw');
  25. if (!keyword) return;
  26. keyword = keyword.trim();
  27. if (!keyword) return;
  28. var escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  29. var regex = new RegExp('(' + escaped + ')', 'gi');
  30. var escapeHTML = function (str) {
  31. return str.replace(/[&<>"']/g, function (t) {
  32. return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[t] || t;
  33. });
  34. };
  35. function walk(node) {
  36. $(node).contents().each(function () {
  37. if (this.nodeType === Node.TEXT_NODE) {
  38. var $t = $(this);
  39. var text = escapeHTML($t.text());
  40. if (regex.test(text)) $t.replaceWith(text.replace(regex, '<mark>$1</mark>'));
  41. } else if (this.nodeType === Node.ELEMENT_NODE && !$(this).is('script, style, noscript, textarea')) {
  42. walk(this);
  43. }
  44. });
  45. }
  46. $('section').each(function () { walk(this); });
  47. }
  48. /** Google Analytics 页面浏览事件 */
  49. function trackPageView() {
  50. if (typeof gtag === 'function') {
  51. gtag('config', window._gaId || '', { page_path: window.location.pathname });
  52. }
  53. }
  54. /** Live2D 重初始化 */
  55. var _live2dSelectors = ['.post-link', '#search-input'];
  56. var _live2dDelegateBound = false;
  57. function reinitLive2d() {
  58. if (!window._live2d) return;
  59. var pathname = window.location.pathname;
  60. // 更新"想问这篇文章"相关状态(仅真正的文章页显示)
  61. $('#post_id').val(pathname);
  62. if ($(CONTAINER + ' #gitalk-container').length > 0) {
  63. $('.live_talk_input_name_body').show();
  64. } else {
  65. $('.live_talk_input_name_body').hide();
  66. $('#load_this').prop('checked', false);
  67. }
  68. // 音乐按钮:根据当前页面是否有 BGM 输入来显示/隐藏
  69. if (typeof window._live2d.initBGM === 'function') {
  70. window._live2d.initBGM();
  71. }
  72. // 事件委托绑定(只执行一次)
  73. if (!_live2dDelegateBound && typeof String.prototype.renderTip === 'function') {
  74. var selector = CONTAINER + ' ' + _live2dSelectors.join(', ' + CONTAINER + ' ');
  75. $(document).on('mouseover._live2d_pjax', selector, function (e) {
  76. var $el = $(e.currentTarget || e.target);
  77. if ($el.is('.post-link')) {
  78. window._live2d.showMessage('要看看 ' + $el.text() + ' 么?', 3000);
  79. } else if ($el.is('#search-input')) {
  80. window._live2d.showMessage('在找什么东西呢,需要帮忙吗?', 3000);
  81. }
  82. });
  83. $(document).on('mouseout._live2d_pjax', selector, function () {
  84. if (window._live2d.showHitokoto) window._live2d.showHitokoto();
  85. });
  86. _live2dDelegateBound = true;
  87. }
  88. // 欢迎语
  89. if (typeof window._live2d.showMessage === 'function') {
  90. window._live2d.showMessage(getWelcomeText(pathname), 6000);
  91. }
  92. }
  93. // ========== PJAX 导航 ==========
  94. /** PJAX 完成后的统一处理 */
  95. function doPjaxComplete() {
  96. $('body').removeClass('pjax-loading');
  97. // 清理可能残留的浮层(如推荐文章 tooltip,hover 后点击跳转时 mouseleave 来不及触发)
  98. $('.content-tooltip').remove();
  99. onPjaxComplete();
  100. }
  101. /** 暴露给模板内 onclick/onchange 调用的导航函数 */
  102. window.go = function (url) {
  103. $.pjax({ url: url, ...PJAX_OPTS });
  104. };
  105. // ========== 初始化 ==========
  106. /** 每次 pjax 完成后执行所有重初始化 */
  107. function onPjaxComplete() {
  108. initVisitors();
  109. initCopyButtons();
  110. reinitHighlight();
  111. reinitAISummary();
  112. reinitLive2d();
  113. trackPageView();
  114. window.scrollTo(0, 0);
  115. }
  116. $(document).ready(function () {
  117. // 排除列表:外链、锚点、静态资源、Live2D 目录
  118. var exclude = ':not([target="_blank"]):not([href^="http"]):not([href^="//"])' +
  119. ':not([href^="mailto"]):not([href^="#"])' +
  120. ':not([href$=".xml"]):not([href$=".json"]):not([href$=".tgz"]):not([href$=".zip"])' +
  121. ':not([href^="/Live2dHistoire"])';
  122. $(document).pjax('a' + exclude, PJAX_OPTS.container, PJAX_OPTS);
  123. $(document).on('submit', 'form#search-input-all', function (e) {
  124. $.pjax.submit(e, PJAX_OPTS.container, PJAX_OPTS);
  125. });
  126. $(document).on('pjax:send', function () {
  127. $('body').addClass('pjax-loading');
  128. });
  129. $(document).on('pjax:complete', doPjaxComplete);
  130. $(document).on('pjax:error', function (xhr, textStatus, error) {
  131. console.warn('[pjax] error, fallback:', error);
  132. });
  133. $(document).on('pjax:end', function (event, xhr, options) {
  134. var $container = $(options.container || PJAX_OPTS.container);
  135. $container.find('script[type="module"]').each(function () {
  136. var oldScript = this;
  137. var newScript = document.createElement('script');
  138. newScript.type = 'module';
  139. // 如果是外链脚本 (<script src="..."></script>)
  140. if (oldScript.src) {
  141. newScript.src = oldScript.src;
  142. } else {
  143. // 如果是行内脚本 (<script>...code...</script>)
  144. newScript.textContent = oldScript.textContent;
  145. }
  146. // 插入到 body 中触发浏览器执行
  147. document.body.appendChild(newScript);
  148. // 运行完后建议移除,防止 DOM 变得混乱(不影响模块执行)
  149. newScript.remove();
  150. });
  151. });
  152. });
  153. })(jQuery);